KUP Assessments – Implementation Diary -TDD & Refactoring

The next few posts are going to be more like diary entries than posts on specific topics. They will have show my train of thought and therefore will be full of assumptions.

Last year I did a course of TDD with Jpassion.com. It was a useful course and allowed me to also refine and expand on many of my projects. However it did not cover when starting projects you start creating tests. My first instinct was to start straight away however it meant an a lot of mocking and from my searches of the net, there are mixed feelings regarding mocking.

So I have settled on a actual sql database for building the account database as I can also be assured that the SQL statements work. I have had a quandary of refactoring. Consider the following statements:

public Boolean createAccount(String username, String email) throws StoringAccountException, AccountAlreadyExistsException{
connect();
if (checkAccountAlreadyExists(username)) {
close();
throw new AccountAlreadyExistsException();
}
try {
conn.prepareStatement(generateNewAccountSQLStatement(username, email)).execute();
close();
return true;
} catch (SQLException e) {
e.printStackTrace();
close();
throw new StoringAccountException();
}
}


public boolean updateAccountEmail(String username, String updatedEmail) {
 connect();
     if(!checkAccountAlreadyExists(username)) {
      close();
      return false;
     } 
     try {
 conn.prepareStatement(generateUpdateAccountStatement(username, updatedEmail)).execute();
 } catch (SQLException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 close();
 return false;
 }
     close();
     return true;
 }
public boolean deleteAccount(String username) {
 connect();
      if(!checkAccountAlreadyExists(username)) {
       close();
 return false;
 }
      try {
   conn.prepareStatement(generateDeleteAccountStatement(username)).execute();
   return true;
   } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   close();
   return false;
   }
 
      
 }

Now I could refactor these as there is a some repetition here. However, some of the methods throw specific exceptions. How do I refactor and keep the exceptions? Or is the issue that some of methods throw exceptions and some don’t. A lack consistency in the interface. Should all the methods throw an exception which may make it easier to refactor? These crud methods however may change further and refactoring could complicate adding the functionality. I will have to return to this issue later and see if I can refactor once other functionality e.g SQL injection prevention is included. I can of course use a finally clause to tidy up the code.

Leave a Reply

Your email address will not be published. Required fields are marked *