Brutish Programming

The term "brute force" applies to solutions where someone applies an obvious but excessive technique when more refined and effective alternatives are available. Novice programmers are frequently guilty of writing brute force code, probably because nobody ever told them how ugly it was, explained why, or told them a better way of doing it.  It compiled and ran so they figured that was good enough.  But it isn't.  80% of software budgets are spent on maintenance; brute force code costs your company real dollars.

Each of the tasks below shows one or more "brute force" solutions (in Java), an explanation of why it's a stupid solution, and then a better solution.  Study and learn, grasshopper.  Write  simple, concise, easy to maintain code and earn the respect of your peers.



Task 1:  Calculate x2.

Brute Force Solution:    square = Math.pow(x,2);

What's wrong with it?

Better Solutionsquare = x * x;

Similarly, Math.sqrt(x) is better than Math.pow(x, 0.5);



Task 2:  Converting an alphabetic character between A and Z to an integer from 0 to 25.

Brute Force Solution A:

switch (letter)
{
    case 'A': return 0;
    case 'B': return 1;
    case 'C': return 2;
    case 'D': return 3;
    case 'E': return 4;
    case 'F': return 5;
    case 'G': return 6;
    case 'H': return 7;
    case 'I': return 8;
    case 'J': return 9;
    case 'K': return 10;
    case 'L': return 11;
    case 'M': return 12;
    case 'N': return 13;
    case 'O': return 14;
    case 'P': return 15;
    case 'Q': return 16;
    case 'R': return 18;
    case 'S': return 18;
    case 'T': return 19;
    case 'U': return 20;
    case 'V': return 21;
    case 'W': return 22;
    case 'X': return 23;
    case 'Y': return 24;
    case 'Z': return 25;
    default: return 0;
}
Brute Force Solution B

Similar to solution A except uses multiple IF statements.

What's wrong with it?
 


Better Solution

return (letter - 'A');



Task 3: Determine if a character is a digit in the range 0 to 9.

Brute Force Solution A:

return  (letter == '0') || (letter == '1') || (letter == '2') || (letter == '3') ||
    (letter == '4') || (letter == '5') ||(letter == '6') ||(letter == '7') ||
    (letter == '8') ||(letter == '9') ;

Brute Force Solution B:

return (letter >= '0') && (letter <= '9');
 

What's wrong with it?


Better Solution

return Character.isDigit(letter);



Task 4: make a decision based on the results of some boolean function (for example,  isEmpty()).

Brute Force Solution

if (mystack.isEmpty() == true) dosomething;

What's wrong with it?
 


Better Solution

if (mystack.isEmpty()) dosomething;



Task 5: return a boolean value based on some boolean expression

Brute Force Solution

if (size > 0)
    return true;
else
    return false;

What's wrong with it?
 

Better Solution

return size > 0;



Task 6: initialize an array.

Brute Force Solution

private int[] scores = new int[10];

scores[0] = 5;
scores[1] = 3;
scores[2] = 7;
scores[3] = 8;
scores[4] = 2;
scores[5] = 3;
scores[5] = 5;
scores[7] = 6;
scores[8] = 9;
scores[9] = 3;

What's wrong with it?

Better Solution

private int[] scores = {5, 3, 7, 8, 2, 3, 5, 6, 9, 3};



Task 7:  Assign a value to a variable based on the value of a second variable.

Brute Force Solution

if (turn == 1) color = 1;
elseif (turn == 2) color = 2;
elseif (turn == 3) color = 3;
elseif (turn == 4) color = 4;
elseif (turn == 5) color = 5;
elseif (turn == 6) color = 6;
elseif (turn == 7) color = 7;
elseif (turn == 8) color = 8;
else color = 9;

What's wrong with it?

Better Solution

color = turn;



Task 8: Convert a string representation of a number into a Java int.

Brute Force Solution

public static int stringToInt(String input)
{
    int result = 0;
    int sLen = input.length();
    for (int i = 0; i < sLen; i++)
    {
        result = 10 * result + ((int) (input.charAt(i)) - 48);
    }
    return result;
}
 

What's wrong with it?

Java already has a function to do this.   This is a clear symptom of ignorance of the language.  This is only one of many examples of this kind of brutishness. Others functions already available in Java for which ignorant programmers write their own code include:


Better Solution

result = Integer.parseInt(input);



Task 9  Advance the turn among players in a multiplayer game (or any situation that needs to maintain a counter that "rolls over").

Brute Force Solution

if (player ==1)
{
 if (numberOfPlayers >= 2) player = 2;
 else player = 1
}
else if (player == 2)
{
 if (numberOfPlayers >= 3) player = 3;
 else player = 1
}
.
.
.   (repeats five more times!)
.
else if (player == 8)
{
 if (numberOfPlayers >= 9) player = 9;
 else player = 1
}

What's wrong with it?

Better Solution:
        player = player + 1;
        if (player > numberOfPlayers)
            player = 1;

Best Solution:
               player = (player % numberOfPlayers) + 1;
 


Task 10  Create a formatted phone number from the string of digits.

Brute Force Solution

            for(int i = 0; i <= 12; i++)
            {
                switch (i)
                {
                    Case 0:
                        formattedPhoneNumber.append("(")
                    Case 1:
                        formattedPhoneNumber.append(cleanPhoneNumber.Chars(0))
                    Case 2:
                        formattedPhoneNumber.append(cleanPhoneNumber.Chars(1))
                    Case 3:
                        formattedPhoneNumber.append(cleanPhoneNumber.Chars(2))
                    Case 4:
                        formattedPhoneNumber.append(") ")
                    Case 5:
                        formattedPhoneNumber.append(cleanPhoneNumber.Chars(3))
                    Case 6:
                        formattedPhoneNumber.append(cleanPhoneNumber.Chars(4))
                    Case 7:
                        formattedPhoneNumber.append(cleanPhoneNumber.Chars(5))
                    Case 8:
                        formattedPhoneNumber.append("-")
                    Case 9:
                        formattedPhoneNumber.append(cleanPhoneNumber.Chars(6))
                    Case 10:
                        formattedPhoneNumber.append(cleanPhoneNumber.Chars(7))
                    Case 11:
                        formattedPhoneNumber.append(cleanPhoneNumber.Chars(8))
                    Case 12:
                        formattedPhoneNumber.append(cleanPhoneNumber.Chars(9))
                }
            }
            return formattedPhoneNumber.toString();

What's wrong with it?


Task 11  Maintain an ArrayList in sorted order.

Brute Force Solution The Brute Force solution is to add each new item to the end of the list, then call Collections.sort() to sort the entire list.

    sortedList.add(item);
Collections.sort(sortedList);

What's wrong with it?

While it certainly is an obvious solution, the performance hit from sorting the entire list can surprise you with huge penalties if your application has to scale up.

Better Solution:
    // Search for the non-existent item
int index = Collections.binarySearch(sortedList, item);

// Add the non-existent item to the list
if (index < 0)
{
sortedList.add(-index-1, item);
}


Task 12  Performing an algebraic transformation on some value.

A common algorithm pattern is to loop a number of times and use the loop counter to index some data structure. 

Brute Force Solution:

for(int direction=0; direction < 4; direction++)
{
switch (direction)
{
case 0:
System.out.println("Some big calculation using 0");
break;
case 1:
System.out.println("Some big calculation using 90");
break;
case 2:
System.out.println("Some big calculation using 180");
break;
case 3:
System.out.println("Some big calculation using 270");
break;
}
}
What's wrong with it?
It uses logic statement (the switch) instead of a simple algebraic expression. 

Better Solution:
for(int direction=0; direction < 4; direction++)
{
int degrees = direction * 90;
System.out.println("Some big calculation using " + degrees);
}

Alternate Solution:
If there isn't a convenient algebraic expression, use a lookup table:
        final int[] degrees = {0,90,180,270};
System.out.println("Some big calculation using " + degrees[direction]);


Task 13  Printing the time in MM:SS format.

Frequently programmer store elapsed time in seconds, but want to display it in common MM:SS format. 

Brute Force Solution:

    /**
     * getTime returns a string representing the current formatted time elapsed.
     */
    private String getTime()
    {
        final int kSecondsPerMinute = 60;
        final int kTwoDigit = 10;
        int minutes = time / kSecondsPerMinute;
        int seconds = time % kSecondsPerMinute;

        String colon, minZero;
        // Set the colon spacing if the current seconds is a single digit.
        if(minutes < kTwoDigit)
        {
            minZero = "0";
        }
        // Set the colon spacing if the current seconds is a double digit.
        else
        {
            minZero = "";
        }

        // Set the colon spacing if the current minutes is a single digit.
        if(seconds < kTwoDigit)
        {
            colon = ":0";
        }
        // Set the colon spacing if the current minutes is a double digit.
        else
        {
            colon = ":";
        }

        return(minZero + minutes + colon + seconds);
    }

Better Solution:
The selection statements above can be replaced with a formatter:
    java.text.NumberFormat formatter = new java.text.DecimalFormat("00");
    return formatter.format(minutes) + ":" + formatter.format(seconds);


Task 14  Removing certain characters from a string.
A common task is to replace or remove certain characters from a string, e.g, remove vowels.

Brute Force Solution:

char[] vowels = {'a', 'e', 'i', 'o', 'u'};
String result = "";
for (int index = 0; index < word.length(); index++)
{
    boolean isVowel = false;
    for (int index2 = 0; index2 < vowels.length; index2++)
    {
        if (word.charAt(index) == vowels[index2])
        {
            isVowel = true;
        }
    }
    if (!isVowel)
    {
        result += word.charAt(index);
    }
}

Better Solution:
The String class has a built-in method to accomplish this task:
            result = word.replaceAll("[aeiou]",""); 


Task 15 Use named constants instead of numeric literals.
Many coding standards recommend avoiding numeric constants (literals) and replace them with a named constant. (E.g., section 10.2 of Sun Java Coding standard).

Brute Force Solution:

private final int kSeven = 7;
What's wrong with it?
'kSeven' doesn't provide any more meaningful explanation than 7. Seven what?  

Better Solution:
private final int kDaysInWeek = 7;
Now we know what 7 refers to; the named constant provides meaningful information.


Task 16: Select a String from a list of constants.
Brute Force Solution:
    public String getValueString()
    {
        String valName = "";
        // Given a value replaces it with an appropriate string
        switch (value)
        {
            case 1:
                valName = "Ace";
                break;
            case 2:
                valName = "Two";
                break;
            case 3:
                valName = "Three";
                break;
            case 4:
                valName = "Four";
                break;
            case 5:
                valName = "Four";
                break;
            case 6:
                valName = "Six";
                break;
            case 7:
                valName = "Seven";
                break;
            case 8:
                valName = "Eight";
                break;
            case 9:
                valName = "Nine";
                break;
            case 10:
                valName = "Ten";
                break;
            case 11:
                valName = "Jack";
                break;
            case 12:
                valName = "Queen";
                break;
            case 13:
                valName = "King";
                break;
        }
        return valName;
    }
What's wrong with it?
Better Solution
  String[] ranknames = {"","Ace","Two","Three", "Four","Five","Six","Seven",
                        "Eight","Nine","Ten","Jack","Queen","King"}
  return ranknames[value];



Task 17: Define a finite set of named constants.
Brute Force Solution:
    public static final int RED = 1;
    public static final int YELLOW = 2;
    public static final int GREEN = 3;
or
    public static final String LEFT = " < ";
    public static final String RIGHT = " > ";
    public static final String CENTER = " . ";
What's wrong with it?



Task 18: Iterate over all characters in a String.
Brute Force Solution:
String letters = "ABCDEF";
String[] array = letters.split("");
List list = Arrays.asList(array);
for (String item: list)
{
    System.out.println(item);
}
What's wrong with it?
It's much more complex than needed; it converts the String into an Array, then into a List.

Better Solution A
A classic for loop and charAt().
for (int pos=0; pos<letters.length(); pos++)
{
    System.out.println(letters.charAt(pos));
}
Better Solution B
Use String's toCharArray() and then an enhanced for loop,
for (Character ltr: letters.toCharArray())
{
    System.out.println(ltr);
}


Home