Pages

Monday, April 09, 2012

How to Simplify your Java Code

Simplifying your programs code is important because it can decrease the size, speed, modularity, and flexibility of your program. Most of the time simplified code can be easier to read. For this post I will entertain two simple, but effective solutions to eliminate unnecessary (extra) code.

Wasteful Code Snippet #1: (BAD)
    private int mailBox1=2;
    private int mailBox2=5;
    private int mailBox3=1;
    private int mailBox4=3;
    private int mailBox5=4;


Solution #1A: (GOOD)
    private int mailBox1=2,
        mailBox2=5,
        mailBox3=1,
        mailBox4=3,
        mailBox5=4;
Explanation #1A I have eliminated the repeated code "private int". This works because private int is a declaration of a variable type which can be shared by using commas.

Solution #1B: (GREAT)
private int[] mailBoxes = new int[]{2,5,1,3,4};
//mailBoxes[0] is mailBox1, mailBoxes[1] is mailBox2, ect.

Explanation #1B I eliminated not only the extra declarations, but have also decrease the number of variables references in my program. There originally were 5 references, and now there is one, mailBoxes, which points to an array of integers. An array is simply a list of some data (normally all of equivalent type).


Wasteful Code Snippet Type #2: (BAD)

 boolean answer = userAnswer(); 
 if(answer==true){
  //then does something here
 }

Solution #2A: (GOOD)

 boolean answer = userAnswer(); 
 if(answer){
  //then does something here
 }

Explanation #2A Booleans are already conditional values, therefore do not need any comparison operator to verify their state in the if construct. Afterall, they are either true or false.

Solution #2B: (GREAT)

 if(userAnswer()){
  //then does something here
 }
Explanation #2B Elimination of a variable declaration can save memory, and a small instance of time in addition to making the code easier to read.

No comments:

Post a Comment