Dirty Code – An Update

You might remember my little hack to sort list elements by their values:

TreeMap<Double, Integer> tree = new TreeMap<>(Collections.reverseOrder());
for (int i = 0; i < customerNumber; i++) {
    tree.put(requirement(i) + Math.random(), i);
}
List<Integer> orderedCustomers = new ArrayList<>(tree.values());

After a lot of research, I finally found a more elegant solution. First of all, I’m using a PriorityQueue instead of a tree. PriorityQueues allow duplicates, which is preferrable in this case since values are not guaranteed to be unique. Secondly, implementing a custom Comparable ensures a clear and readable structure.

class Element implements Comparable<Element> {

    private final int key;
    private final int value;

    Element(int key, int value) {
        this.key = key;
        this.value = value;
    }

    @Override
    public int compareTo(Element anotherElement) {
        return compare(getValue(), anotherElement.getValue());
    }

    private int compare(int x, int y) {
        return (x < y) ? -1 : ((x == y) ? 0 : 1);
    }

    public int getKey() {
        return key;
    }

    public int getValue() {
        return value;
    }
}

That’s it. This solution is still too complicated for my taste, but at least it’s easy to understand.

Understanding Algorithms

I’m currently taking a class on algorithms. While practising a bit, I found a cool trick: Most algorithms are easier to read when written in Python instead of pseudocode.

Why? Pseudocode doesn’t follow exact rules. Python’s syntax is very similar to pseudocode, but strictly regulated. Also, most style guides and best practices focus on readability. Python code is predictable; you get exactly what you expect. That’s why Python is perfect for studying algorithms.

You don’t believe me? Take a look at the Euclidean algorithm:

function gcd(a, b)
    while b ≠ 0
       t := b;
       b := a mod b;
       a := t;
    return a;

Here’s the same algorithm in Python:

def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

The second one requires less thinking, doesn’t it?

Of course, this trick also works on complicated, less famous algorithms. Continue reading “Understanding Algorithms”