Showing posts with label Code analysis. Show all posts
Showing posts with label Code analysis. Show all posts

Sunday, 26 June 2016

What are the common Exception handling rules ?


Exception handling rules


#1. Prefer exceptions over Returning Error Codes
if (deletePage(page) == E_OK) {
   if (registry.deleteReference(page.name) == E_OK) {
     ....
   } else {
      .....
   }
} else {
   ....
}

try {
   deletePage(page);

   registry.deleteReference(page.name);
} catch (Exception e) {
    logger.log(e.getMessage());
}



#2. Extract Try/Catch Blocks
Example. More better than above - 1 method with core logic , other with try/catch block only
try {
   deletePageAndAllReferences(page);
} catch (Exception e) {
   logError(e);
}


private void deletePageAndAllReferences(Page page) throws Exception {….}


#3. Use Unchecked Exceptions
Checked exceptions :
  • increases error handling in many parts of our system
  • Breaking Encapsulation
So, Use checked exceptions only when :
  • If the caller knows & wants how to handle it
  • Dealing with Critical Systems or libraries

#4. Don’t Eat the Exception
try {
  ...
} catch (Exception ex) { }


try {
   ...
} catch (Exception ex) {
   ex.printStackTrace();
}



#5. Resist Temptation to write a Single Catchall
Single handler for many errors reduces the reliability of your program.

#6. Always use Catchall after handling known ones
You may not be sure that you handled all possible exceptions, so provide a default handler (catchall)

#7. Don’t Return NULL
Returning null needs its handling at all the places, which makes code awful.
Solution
  • Return a special case object
  • Wrap with another method that throws exception

#8. Don’t Pass NULL
Passing NULL should be handled inside the method or NullPointerException will be thrown
Unless the used API is passing NULL, you should avoid it.

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");
  ...
}


What are the common Naming rules ?


NAMING RULES

#1. Use Intention-Revealing Names
int d; // elapsed time in days
int elapsedTimeInDays;

#2. Avoid Disinformation
Use below name only if this variable is a List type
accountList

#3. Long names which can take long time to differentiate
XYZControllerForEfficientHandlingOfStrings
XYZControllerForEfficientStorageOfStrings

#4. Use searchable names
Karakter
7
DAYS_PER_WEEK
week



#5. Make Meaningful Distinction
public static void copyChars(char a1[], char a2[]) {
  for (int i = 0; i < a1.length; i++) {
     a2[i] = a1[i];
  }
}


public static void copyChars(char[] source, char[] destination) {
   for (int i = 0; i < source.length; i++) {
      destination[i] = source[i];
   }
}



#6. Use Pronounceable Names
genymdhms

#7. Avoid Encodings
Example : Prefixing member variable with 'm_'
m_countryCode

Example : Interfaces & Implementation
Interface IShapeFactory {...}
Class ShapeFactory implements IShapeFactory {...}


Interface ShapeFactory {...}
Class ShapeFactoryImpl implements ShapeFactory {...}



#8. Avoid Mental Mapping
String url;
instead of 
String r;

#9. Don’t Be Cute
DeleteItems()
instead of
HolyHandGrenade()

dispatchRequest()
instead of
edenyFelRequest()

* Names based on cultural base or sense of humor will only be remembered by people who know it


#10. Pick One Word per Concept
Example : using fetch(), retrieve(), and get() in the same layer
* Caller will be confused which method to call ?


#11. Don’t Add Extra-free Context
Example : Prefixing every class with MBS in a Mobile Banking System
class MBSCustomer
class MBSSimCard

Thursday, 21 April 2016

How to install SonarQube ?


Install SonarQube
Sonar server
  • It acts as a sonar server. 
  • Download the Sonar Qube 4.0 from http://www.sonarqube.org/downloads/  
  • Extract the zip and put at the VM at a location (For example: /home/sonarqube-4.0)
  
MySQL 
   1. Download and install MySql version 5.x 
   2. Create a database named “sonar” 
   3. Start the mysql service through command prompt.
   4. Download SQL Yog and connect to MySQL with username and password. 


Configuration of SonarQube
1. Set Sonar properties  
Open sonarqube-4.0\conf\ sonar.properties

Update JDBC properties  
sonar.jdbc.url=jdbc:mysql://10.239.199.97:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useConfigs=maxPerformance 
sonar.jdbc.username=root 
sonar.jdbc.password=root 
sonar.jdbc.driverClassName=com.mysql.jdbc.Driver

Update Sonar server properties  
sonar.host.url=http://10.170.208.95:8090 
sonar.web.host=10.170.208.95 
sonar.web.port=8090 
sonar.web.context=/ 


2. Setup MySQL 
Create a database named “sonar” 
# su – mysql 
$ . myqenv 
$ mysql –uroot -proot  
create database sonar 

Ensure that MySQL instance is running and able to connect database “sonar” through SQLYog.
All the tables would be created automatically after the sonar ant task would run.

3. Start the sonar server  
Go to  sonarqube-4.0\bin and select your operating system (Eg: windows-x86-64 for window 7) and start Sonar server 
Example 
cd C:\E_Drive\sonarqube-4.0\bin\windows-x86-64 
Run the StartSonar.bat file.

Linux 
$ /home/sonarqube-4.0/bin/linux-x86-64/sonar.sh start | stop | status

Check sonar logs 
$ tail -f /home/sonarqube-4.0/logs/sonar.log

Check the sonar process  
$ ps -aef | grep java