Property getters & setters
In traditional OOP, if we wanted to get or set an object's private member, we would need to write a public method to do the job.
The reason behind making a member data private and then accessing it through a public method is to avoid the implementing-user to access it directly.
There can be many reasons for prohibiting direct access to member data to the implementing-code.
For example, you may want a radius of a Circle to be within the range of 10 - 500.
In languages like PHP & Python which has a weak type system, a further check of the data type may be necessary.
But for Python unfortunately even traditional getter & setter methods cannot be implemted because Python doesn't have a public or private. Everything is public by default - though a member can be made private by prefixing two underscores to it. But this is only for convention, it doesn't really serve its true purpose.
PHP 5 and C# .NET have a getter and setter method feature, making it look like we're accessing the data member directly.
C# .NET 3.0 has introduced Automatic Properties where you don't need to specify code for the getter & setter - the compiler takes generates the method body.
JavaScript does seem to have a getter and setter method which I came across just now when searching for the official source to Java 7's new features' documentation, but :
- only within an object initializer - not inside a function so it doesn't seem to be of much use as we can't create instances
- doesn't hide the member from being accessed directly
- doesn't work in IE.
The Getter & Setter feature does not seem to be a much "wanted" feature in the Java community.
Still, this has been proposed by Rémi Forax for JDK 7.
| Filed Under : C#, Java, JavaScript, php | |||||||||
| Posted by Anjanesh on Monday, February 25, 2008 | 0 comments | ||||||||