A readable example of how code become unreadable

Consider the following problem: You need to calculate how many dots are there in a square triangle for a specific width, for example

.
..
...

Has an area of 6

.
..
...
....

Has an area of 10
The catch is, you are not allowed to use the mathematical formula to calculate the number instantly, so there’s two ways remaining to solve this problem:

  • Use two for loops
  • Recursion

We will follow the second direction because it’s probably shorter to write, so someone wrote

public class TrianglePrinter {
    static int getTriangleArea(int width) {
        int result = 0; // Default return
        if (width > 0) { // Stop condition
            result = getTriangleArea(width - 1) + width; // Split the problem
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(getTriangleArea(4));
    }
}

This can be “optimized” to become a one-line method, short code gives longer lives!

public class TrianglePrinter {
    static int getTriangleArea(int bottomWidth) {
        return (bottomWidth > 0) ? getTriangleArea(bottomWidth - 1) + bottomWidth : 0;
    }

    public static void main(String[] args) {
        System.out.println(getTriangleArea(4));
    }
}

Then when it is compacted (like, in Javascript…)

public class TrianglePrinter {
    static int g(int w) {
        return (w > 0) ? g(w - 1) + w : 0;
    }

    public static void main(String[] args) {
        System.out.println(g(4));
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.