Tuesday, 10 May 2011

Breaking the Single Responsibility Principal

One of the most important programming principals is the Single Responsibility Principal (SRP), which states that an object should have one, and one only, reason to change its state. Unfortunately, this is one of the programming rules that is often broken, mainly because I think that too many of us think that once our code works, then our work is done.

So, below are a few hints on testing whether or not a class fulfils the SRP:
  • Firstly, naming is a really good clue. If a class has a really good descriptive and concise name then it probably doesn’t break the SRP. If a class name is ambiguous then it probably has more than one responsibility. Class names that include so called ‘weasel words’ such as Manager, Processor or Super are good examples of broken class names.
  • You should also be able to write a brief and succinct description of your class’s responsibilities without using any conjunctions: (‘and’, ‘but’, ‘or’ etc.) If you have to write something like: “This class is responsible for this and that, then you can be certain that you have a little refactoring to do.
  • If your class has method names that can be split into sets then there must be SRP problems.

    public class AppletManager {

     
    // Create the running thread
     
    void start() {
       
    // Some Code
     
    }

     
    // End the running thread
     
    void stop() {
       
    // Some Code
     
    }

     
    // Do the animation
     
    void run() {
       
    // Some Code
     
    }

     
    // call update so that the background does not refresh
     
    void update(Graphics g) {
       
    // Some Code
     
    }

     
    // Paint the applet
     
    void paint(Graphics graphics) {
       
    // Some Code
     
    }
    }

    The code above seems to be responsible for both thread management (start(), stop(), run()) and painting itself (paint(), update()); this can’t be right and some refactoring is necessary.

No comments: