Java Timing Code: Compare Execution Times of Methods

Often times, you will have two Java functions, and you will want to know which one performs better. You can use this Java class to time multiple methods to find out which one is faster.

Continue

Refactoring Deeply Nested if Statements

Deeply nested if statements are a pain to read and maintain, so you should try to avoid them as much as possible. Here are a couple of suggestions on how to get rid of nested if statements.

Most of these suggestions can be applied to most languages that have the if statement, at least most object oriented or procedural languages. But my main focus when writing this were Java and PHP.

Early Return

Early returns should be used a lot more often by pretty much everybody. It’s one of the easiest ways to avoid deeply nested if statements and one of the first things I would look for when refactoring code.

The main idea is that when checking a value, the negative case is moved up-front, the error handled, and then the method is exited:

boolean test1 = ...;
if (test1) {
    boolean test2 = ...;
    if(test2) {
        boolean test3 = ...;
        if(test3) {
            // do the stuff
        } else {
            // some error, handle it
        }
    } else {
        // something else
    }
} else {
    // some other error, handle it
}
return;

Here, you can move the checks to the top of the method and remove three levels of nested if statements:

boolean test1 = ...;
if(!test1) {
    // some other error, handle it
    return;
}
boolean test2 = ...;
if(!test2) {
    // something else
    return;
}
boolean test3 = ...;
if(!test3) {
    // some error, handle it
    return;
}
// do the stuff
return;

Refactoring if-if

I don’t see this too often, but it does happen:

if (test1) {
    if(test2) {
        // do stuff
    }
}

Should be:

if (test1 && test2) {
    // do stuff
}

Refactoring if-if-else

This if condition occurs a bit more often than the previous one. Quite often, there might be a return in the second if statement, which makes it harder to grasp that // do even more stuff will be executed when test1 = true; test2 = false;

if(test1) {
    if(test2) {
        // do stuff
    }
} else {
    // do other stuff
}
// do even more stuff

A better way would be:

if (!test1) {
    // do other stuff
} else if (test2) {
    // do stuff
}
// do even more stuff

Use else if

This is another beginners mistake: not using else if:

if (test1) {
    // do stuff 1
} else {
    if (test2) {
        // do stuff 2
    } else {
        if (test3) {
            // do stuff 3
        }
    }
}

With else if you can avoid the nested if statements:

if (test1) {
    // do stuff 1
} else if (test2) {
    // do stuff 2
} else if (test3) {
    // do stuff 3
}

Move Code to its own Function

If you tried everything else, and your code is still too deeply nested, move some of the functionality to its own function, and give that function an expressive name to make your code easier to read.

Redundant Checks

You can introduce redundant checks to reduce the number of nested if statements.

I’m not that big of a fan of this approach (it is bad for performance and even though it reduces nesting, it might make the code harder to grasp), but if your code is very deeply nested and cannot be fixed otherwise, this might be useful to you. If the tests are complex, definitely save the result in a well named variable.

One example would be:

if (test1 && test2) {
    // do stuff
    if (test3 && test4) {
        // do more stuff
    }
    // do even more stuff
}

Which could be rewritten as:

if (test1 && test2) {
    // do stuff
}
if (test1 && test2 && test3 && test4) {
    // do more stuff
}
if (test1 && test2) {
    // do even more stuff
}

Refactoring Simple Boolean Checks in if-Statements

How to refactor simple boolean checks in if statements and avoid bad practices.

This is the first post out of a number of posts dealing with refactoring. This particular post is aimed at beginners, but further posts will contain somewhat more advanced concepts.

The concepts presented here can be used in a lot of programming languages, but the article is written with Java, PHP, and JavaScript in mind.

For one-liners, the general formating will look like this:
some expression => better expression doing the same thing

Check if a Value is True or False

if (A == true) => if (A)
if (A == false) => if (!A)

This is something I see a lot of beginners do. It’s not the end of the world, but it does lead to harder to read code, possible bugs, and expresses a lack of deeper understanding.

Empty if-Statement

if(A) {
} else {
    // do the thing
}

This can be written a lot cleaner by negating the condition:

if(!A) {
    // do the thing
}

Check Multiple Values, Some of which are the Same

if ((A && B) || (A && C) || (A && D)) => if (A && (B || C || D))

This is possible because AND and OR are distributive.

Simplify Complex if Condition

If you are not that well versed with boolean logic, you should read up on negation and boolean algebra in general (especially de Morgan and distributivity).

Just a couple of examples of how complex if conditions can be simplified using boolean logic:

  • !(!A || !B || !C) => A && B && C
  • A && (A || B)) => A
  • (A || B) && (!A || C) && (B || C) => (A || B) && (!A || C)

Bin Packing Algorithm (Java)

In this post I will present example Java code for solving the Bin Packing Problem. I will not go into what exactly Bin Packing is, as there are enough websites that do a good job describing it. As always, wikipedia is a good start to get a general overview: Wikipedia Bin Packing Problem.

Bin Packing: Brute Force Solution

To check all possible solutions for the bin packaging problem (brute force), a recursive approach can be used: Iterate over all bins, try to put the current item in the bin and – if it fits – call the same method with the next item.

    /**
     * bruteforce solution to bin packing problem.
     *
     * @param in list of items to be packed
     * @param currentPosition position in input list
     */

    private void bruteforce(List<Integer> in, int currentPosition) {
        if (currentPosition >= in.size()) { // reached last item, done with this iteration
            int filledBins = getFilledBinsCount();
            if (filledBins < currentBestSolution) { // is this solution better than the current best?
                currentBestSolution = filledBins; // then save it
                currentBestBins = deepCopy(bins);
            }
            return;
        }
        // iterate over bins
        Integer currentItem = in.get(currentPosition);
        for (Bin bin : bins) {
            if (bin.put(currentItem)) {
                bruteforce(in, currentPosition + 1);
                bin.remove(currentItem);
            } // else: item did not fit in bin, ignore
        }
    }

Bin Packing: First Fit Decreasing Algorithm

The Bin Packing Problem can also be solved by an algorithm, called first fit decreasing. Implementing the first fit decreasing algorithm is quite simple. Just sort your input (descending), and then iterate over it, packing each item into the first bin it fits into.

    /**
     * first fit decreasing algorithm for bin packing problem
     */

    public int firstFitDecreasing() {
        Collections.sort(in, Collections.reverseOrder()); // sort input by size (big to small)
        bins.add(new Bin(binSize)); // add first bin
        for (Integer currentItem : in) {
            // iterate over bins and try to put the item into the first one it fits into
            boolean putItem = false; // did we put the item in a bin?
            int currentBin = 0;
            while (!putItem) {
                if (currentBin == bins.size()) {
                    // item did not fit in last bin. put it in a new bin
                    Bin newBin = new Bin(binSize);
                    newBin.put(currentItem);
                    bins.add(newBin);
                    putItem = true;
                } else if (bins.get(currentBin).put(currentItem)) {
                    // item fit in bin
                    putItem = true;
                } else {
                    // try next bin
                    currentBin++;
                }
            }
        }
        return bins.size();
    }

Download Source Code for Bin Packing Problem

Java Bin Packing Source Code [3.9 kB]

Linux Mint: Remove PPA

Linux Mint does not provide the option to remove a ppa.

If you try it, this will be the result:

sudo add-apt-repository --remove ppa:somePPA/ppa
Usage: add-apt-repository [options] repository

add-apt-repository: error: no such option: --remove

But you can still manually remove a ppa in Linux Mint by removing the file that defines it. All ppa are defined in /etc/apt/sources.list.d . So you can do the following:

# find the correct ppa file to delete by listing all ppa files:
ls /etc/apt/sources.list.d

# delete the ppa that you would like to remove:
sudo rm /etc/apt/sources.list.d/some-ppa-to-remove.list

# update
sudo apt-get update

And that is it, you should now have removed the ppa.