Wednesday, 23 February 2011

When Object Design Goes Wrong...

There are a good many well documented 'code smells' and 'anti-patterns', but I've always found the following couple of items useful...


Objects are not:

Objects are not structures. They do not have public member variables (either other objects or primitive data types). Too many Get/Set methods is a bad sign (unless the object is a Data Transfer Object or DTO used for passing data over the wire). In an OO world, it should be remembered that objects do things.

Objects and Type Variables

Objects do not need 'type of' variables and if they do, then it's usually a sign of a problem in the class hierarchy.

public class TypingProblem {

 
private final String objectType;

 
public TypingProblem(String objectType) {
   
this.objectType = objectType;
 
}
}

To resolve this problem, add a base class to the design.


Switch Statements

Objects containing too many switch statements usually have similar problems with polymorphism and inheritance. The 'switch statement' problem is similar to the previous problem.

  public String checkInput(int typeInt) {

   
String output = "";

   
switch (typeInt) {
   
case 1:
      output =
"fred";
     
break;
   
case 2:
      output =
"bill";
     
break;
   
case 3:
      output =
"ted";
     
break;
   
case 4:
      output =
"alice";
     
break;
   
case 5:
      output =
"bob";
     
break;
   
}

   
return output;
 
}

Some links to Code Smells

http://martinfowler.com/bliki/CodeSmell.html
http://www.codinghorror.com/blog/2006/05/code-smells.html
http://c2.com/cgi/wiki?RefactoringImprovingTheDesignOfExistingCode

No comments: