Sunday, 26 June 2016

What are the common Method writing rules ?


METHOD WRITING RULES

#1. Small
Method should be :
  • Small
  • A screen-full or 
  • should hardly ever be 20 lines long.
Example
public static String renderPage (PageData pageData, boolean isSuite) throws Exception {
   if (isTestPage(pageData))
         includeSetupAndTeardownPages(pageData, isSuite);
   return pageData.getHtml();
}


#2. Do One Thing
  • Method should do one thing only and should do it well.

#3. One Level of Abstraction per Method
  • Don't mix levels of abstraction within a method 
    • Confusion between a essential and detail

#4. Avoid switch statements
  • It violates "Do One Thing" rule
  • Convert switch statement into Abstract Factory
  • Always not possible but Try to get rid of Switch statements

#5. Use descriptive names
Consider : 
  • It may take time to choose a good name
  • Name can be long

#6. Minimize method arguments
  • Pass the objects

#7. Have no side effects
Example : Below method name is checkPassword but it also initializing session
public boolean checkPassword(String userName, String password) {
  User user = UserGateway.findByName(userName);
  if (user != User.NULL) {
     String codedPhrase = user.getPhraseEncodedByPassword();
     String phrase = cryptographer.decrypt(codedPhrase, password);
     if ("Valid Password".equals(phrase)) {
          Session.initialize();
          return true;
     }
  }
  return false;
}


Problem. If someone doesn't know it is also initializing session, and calls it just for checking password only, it may cause data loss.

Solution. If we can't divide it, change its name to : checkPasswordAndInitializeSession


#8. Separate Command from Query
Methods should either do something or answer something
if (set("username", "unclebob"))...

if (attributeExists("username")) {
  setAttribute("username", "unclebob");
  ...
}


No comments:

Post a Comment

Note: only a member of this blog may post a comment.