Saturday, October 21, 2006

Don't repeat yourself

The code says everything once and only once, which is the essence of good design. -- Martin Fowler




[Time: 4:44 mins]


  • Repititive code makes maintainance more difficult
    • There are more places to change
    • We may forget to change some of them
    • Increases probability of bugs
  • Types of repitition
    • In methods in a class
    • Accross the entire software 


Example 1: DRY violated



















public class Account {

  public void transferFunds(double amt, Account dest) {

    //transfer funds

    //generate email... create connection

    //create message

    //dispatch email

  }



  public void delete() {

    //delete account

    //generate email... create connection

    //create message

    //dispatch email

  }

}




Java2html







Example 2: DRY honoured



















public class Account {

  public void transferFunds(double amt, Account dest) {

    //transfer funds

    dispatchEmail(...);

  }



  public void delete() {

    //delete account

    dispatchEmail(...);

  }



  public dispatchEmail() {

    //generate email... create connection

    //create message

    //dispatch email

  }

}




Java2html




Resources:

  • http://www.artima.com/intv/dry.html
  • http://c2.com/cgi/wiki?DontRepeatYourself
  • http://c2.com/cgi/wiki?OnceAndOnlyOnce



Note: This post was originally posted on my blog at http://www.adaptivelearningonline.net

No comments: