søndag den 10. juni 2007

Getters and Setters are evil

In my current employment I am a part of a project that is founding a new system, root up.

What I keep seeing myself doing is adding getters and setters allover my code, but only inside well-defined components. I ask you though, how well-defined must a component be to consider encupsulation for properties?

I have come to the conclusion, that each and every class is a component in it's own right.. so I should drop getters and setter entirely. Ouch, some refactoring to be done.. hmm how to accomplish it, I wonder.

Consider the case of Logging in. The usual way to go about this is to have a user obect compared to some stored data, and then doing some behind the scenes bullshit of connecting to this, and refering to that. What you essentially end up with is a function, like this


boolean login(String username, String password);


and it is placed somewhere on your mother of an application runnable.

Application{
void run(){
splashScreen();
//Hack info from the User and crack away
loginInfo = gatherLoginInfo();
login(loginInfo.name, loginInfo.pass);
}
}

That doesn't seem at all like OO programming though. One would expect this method to be a method of a User. Then the application would ask the user to log themselves in. So instead the implementation would be

User{
void login();
}

Application{
void run(){
splashScreen();
//we have a new User here
User user = new User();
//user, could you please log ourself in?
user.login();
}


Seems more accurately OO-like... right?

Some good reading:
http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html?page=5