Pages

Friday, February 2, 2007

getters and setters

Recently I had to cleanup some very old Java code. Just simple batch applications that take some data from one database and transfer it to another database. I noticed a funny "pattern" in the legacy code: one static method iterates the ResultSet and collects the results into a Vector using String[], like:

List list = new ArrayList();
while (rs.next()){
String [] row = String[3];
row[0] = rs.getString(1);
row[1] = rs.getString(2);
row[2] = rs.getString(3);
list.add(row);
}

The second method then iterates the results, performs some calculations, and inserts new values to database:

for(int i = 0; i < list.size(); i++){
String[] row = (String[])list.get(i); // yaaggghhhhhh!?!
....
}

Smells like C... Personally I have nothing against C, but not inside Java code. I'd better introduce a bean class to encapsulate the values.

OK. let it be:

// as all the logic fits into one class i'd better make this class private
private class MyBean {
String a;
String b;
String c;
MyBean(String _a, String _b, String _c){
a = _a; b = _b; c = _c;
}
}

What I realized now - no point of having getters and setters for the inner class' members. Why?
1) This is used only inside the host class, thus no encapsulation needed.
2) Getters and setters will just flood the source code without bringing any value and making the code less readable.
Instead, I set default access to the bean class members.

The moral is that getters and setters aren't absolutely necessary for simple code. I believe this is trivial, but some people wouldn't agree I guess.

Take care :)

No comments:

Disqus for Code Impossible