Friday, May 30, 2008

In Your Face: Refactoring

I know we are all guilty of ignoring an obvious refactoring at one point or another. Even when we truly know better. But I'm dumb-founded by how some people just seem to lack any concept of even the simplest encapsulation techniques.

Should the following not be almost instinctive by now to even the most average of developers? The following refactorings should not take more than a few minutes, if not less.

When you write the same clumsy string concatenation more than once, it's time to refactor.

// bad
String userChangesTableName = "user_" + userName + "_workchanges";

//good
public static String getUserChangesTableName(String userName)
{
return new StringBuffer(64).append("user_").append(userName).append("_workchanges").toString();
}
// look, comes with optimization even!


When you have comments excessively explaining code, it's time to refactor.
// bad
// if records are present, user work is dirty.
boolean userWorkDirty = simulationDAO.isRecordsExist(getUserChangesTableName(userName), simulationId)

//good
public boolean isUserWorkDirty(String userName, int simulationId)
{
return this.isRecordsExist(UserWorkBusiness.getUserChangesTableName(userName), simulationId);
// possibly even consider inlining this, or just renaming the original method, or see below.
}


When your method name doesn't make grammatical sense, it is time to refactor.

// bad
public boolean isRecordsExist(String tableName, int simulationId){ ... }

// good
public boolean isSimulationDataPresentInTable(String tableName, int simulationId) { ... }


If you can't rename your method to something that is descriptive of what it is doing/telling you in a way that makes grammatical sense, THEN IT IS DEFINITELY TIME TO REFACTOR.

Only this time, it might take you a little longer than a few minutes.

You should have put those extra few minutes in here and there to start off with. Look at all that time you would have saved.

No comments: