Getters and Setters

“Best practices” always tell us to use getters and setters instead of exposing properties directly on a class. This is true for just about every language where it makes sense, but I want to look at two particular cases, Java and ActionScript.

How often have you seen classes that do this?

[cc]
class Employee
{
private String firstName;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
}
[/cc]

Most of the time, this is unnecessary. It’s 6 extra lines of code for every property cluttering up the source files for little benefit. The typical reasoning for why you need getters and setters is that it gives you the opportunity to go back later and add additional functionality, like say dispatching an event when a property is changed. In certain circumstances this makes sense.But most of the time, the cost, in terms of the loss of clarity and the additional lines of code to maintain, outweighs the benefit.

If you used a public member instead of accessors and later did want to change your mind, what’s the impact? When you make the change, your compiler or IDE will tell you all the references that you need to fix. It might even offer to do it for you.

In ActionScript, there is even less need to write getters and setters for properties, because you can go back and change your mind later. In ActionScript, the Employee class might look like this:

[cc]
class Employee
{
private var _firstName:String;
public function get firstName():String
{
return _firstName;
}

public function set firstName(value:String):void
{
_firstName = value;
}
}
[/cc]

But if you used the simple version:

[cc]
class Employee
{
public var firstName:String;
}
[/cc]

And you later needed to override what happens when you set or get firstName, you can change the property to private and add getters and setters without having to update the clients.