Thursday, June 11, 2009

No getters and setters

To design good software working with Domain language and making it part of Object's is very important. One way to get this, I think is to get away from the "get" and "set" polluted code.

consider this code:

public class Person {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}

We would end up using this code in its simplest form like this:
Person theOne = new Person();
theOne.setName("Neo Anderson");
System.out.println(theOne.getName());

Instead we can easily modify this code to make it more "domain driven"
public class Person {
public String name() {
return name;
}
public void nameIs(String name) {
this.name = name;
}
private String name;
}

Our new code would be:
Person theOne = new Person();
theOne.nameIs("Neo Anderson");
System.out.println(theOne.name());

you can tell this is more english like code as well. You can easily read line 2 in the code there as "The one's name is Neo Anderson". You can easily read line 3 as "Print the one's name"

I believe in this approach. The easiest way implement this approach is:
1. If you have a private variable names "varName", your getter method would be named "varName"
2. The setter method would be named "varNameIs" .... append with an Is

No comments:

Post a Comment