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 :)

Thursday, February 1, 2007

What if... C#?

Programming covers many different business areas and therefor it seems narrowminded to me to be sticked 100% to Java and JVM. Today I thought, what if I will have to develop something in C#? I have no expirience with .NET yet. But I'm so used to the programming practices/tools that I gained with Java - like Ant, JUnit, cruisecontrol, O/R mapping, and Spring Framework of course.
While googling for a while I found that all the tools or some similar exist for .NET:

NHibernate
NUnit
NMock
NCover
log4net
Spring.NET

With such set of tools it seems that there's almost no difference in Java vs C# programming - just a matter of syntax - moreover it is similar for both.

Disqus for Code Impossible