Turnleaf Design Ramblings of a junior developer

19Sep/092

If, else and nothing else

When I was still very new to programming I had a bad habit of writing bloated code. One of my worse areas was when it came to the usage of If statements. Often times I would write a whole if/else block when I could had just as easily gotten the same results in just one line of code.

public class IfExample {

public static void main(String[] args){
boolean getBoolValue;
int a = 1, b = 2;

if(a > b){
getBoolValue = true;
} else{
getBoolValue = false;
}
}

Instead of writing the whole if/else statement instead you can just directly take the result of the test condition.

getBoolValue = a > b;

Some prefer to put parentheses around the comparison, however they are optional. I personally prefer a more minimalist code style.

Be the ternary

So what if you need something other than a boolean value? Enter the Java ternary operator. Which looks like this:

String isEven = (3 % 2 == 0) ? "Yes" : "No";

The element before the “?” is the test condition that is to be performed. The element before the “:” is the value that will be returned if the test condition is true and the element after the “:” is what will be returned if the test condition is false.

Bookmark and Share

Technorati Tags: ,

Related posts:

  1. A brief intro into unit testing with JUnit
  2. Foreach isn’t a reach in pre-1.5
Comments (2) Trackbacks (0)
  1. It’s not alwas the best thing to have a short line of code. Software is always changing and other people will have to change your code.

    if (a > b) {

    is more readable, because it’s a lot closer to our natural language.

    If a greater then b do that.

    For

    getBoolValue = a > b;

    you have to think about if it’s a condition or not.
    It’s an implicit condition.

    And for the sake of readability, I prefer using the explicit expression.

    And I have another point about shortening.
    You can shorten the if expression like this.

    int boolValue = true;
    if (a < b) {
    boolValue = false;
    }

  2. Be minimalist when it will lead to better code design. For you new guys out there try not to make the code “too cute” with look what I learned today type of stuff.

    Having said that, I think that it is great that you are hungry for learning new things. Your code and career will certainly be benefit from it.


Leave a comment


No trackbacks yet.