Background:
I found this article on JavaWorld, where Allen Holub explains an alternative to Getters/Setters that maintains the principle that the implementation of an object should be hidden (his example code can also be found below).
It is explained that the classes Name
/EmployeeId
/Money
should have a constructor taking a single string - the reasoning is that if you type it as an int
, and later need to change it to a long
, you will have to modify all the uses of the class, and with this pattern you don't have to.
Question 1:
I was wondering: doesn't this simply move the problem to the parsing of the String
parameters being tossed about? For example, if all the code using the EmployeeId
(received from the Exporter
) parses the String
into an int
, and suddenly you start exporting long
values, you need to modify exactly as many uses... and if you start out parsing it as a long
it might well have to change to a double
(even though that makes no sense for id's)... and if you can't be sure what to parse the String
into, you can't implement anything.
Question 2:
Besides this question, I have another: I realise that the article is over seven years old, so could anyone point me to some recent overviews concerning OO-design, and specifically to ideas concerning the getter/setter and implementation hiding debate?
Listing 1. Employee: The Builder Context
public class Employee
{ private Name name;
private EmployeeId id;
private Money salary;
public interface Exporter
{ void addName ( String name );
void addID ( String id );
void addSalary ( String salary );
}
public interface Importer
{ String provideName();
String provideID();
String provideSalary();
void open();
void close();
}
public Employee( Importer builder )
{ builder.open();
this.name = new Name ( builder.provideName() );
this.id = new EmployeeId( builder.provideID() );
this.salary = new Money ( builder.provideSalary(),
new Locale("en", "US") );
builder.close();
}
public void export( Exporter builder )
{ builder.addName ( name.toString() );
builder.addID ( id.toString() );
builder.addSalary( salary.toString() );
}
//...
}