Thursday, October 21, 2010

Minimize ripple effects in OOP programing

What is the meaning of minimize ripple effect?
Minimizing the ripple effects means limit the force of  changes to a program. Simply saying by keeping details secret in your code (information hiding or encapsulation).


Basically there are three ways of doing it: 


By indirection 
  That means named constants replacing "magic numbers" in your piece of code.
  e.g: 
  A magic number is a direct usage of a number in the code. see the following piece of code as example     which is not best practice to use:


public class Foo {
     public void setPassword(String password) {
          // don't do this
          if (password.length() > 7) {
               throw new InvalidArgumentException("password");
          }
     }
}


 Best practice is in the following code: 







public class Foo {
     public static final MAX_PASSWORD_SIZE = 7;

     public void setPassword(String password) {
          if (password.length() > MAX_PASSWORD_SIZE) {
               throw new InvalidArgumentException("password");
          } 
}

***  It will improve the readability of the code and of course maintainability

***  Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies.


By minimizing visibility


 Use private fields, package-private classes to hide information from public access.


By generic references


Use  (polymorphism) - using high level references (interfaces or abstract classes) instead of low level references (concrete classes).



No comments:

Post a Comment