Refactoring


isPalindrome

The isPalindrome method expends almost twice as much effort as necessary to determine whether a string is a palindrome. While normally you shouldn't worry about performance until it is a problem, an algorithm should be clean. Doing something unnecessarily in an algorithm demonstrates poor understanding of the problem. It can also confuse future developers.

You only need to traverse the string up to its middle. The current implementation traverses the string for its entire length, which means that all or almost all characters are compared twice. A better implementation:

 public static boolean isPalindrome(String string) {    if (string.length() == 0)       return true;    int limit = string.length() / 2;    for       (int forward = 0, backward = string.length() - 1;        forward < limit;        forward++, backward)       if (string.charAt(forward) != string.charAt(backward))          return false;    return true; } 

Fibonacci and Recursion

Java supports recursive method calls. A recursive method is one that calls itself. A more elegant solution for the Fibonacci sequence uses recursion:

 private int fib(int x) {    if (x == 0)       return 0;    if (x == 1)        return 1;    return fib(x - 1) + fib(x - 2); } 

Be cautious when using recursion! Make sure you have a way of "breaking" the recursion, otherwise your method will recurse infinitely. You can often use a guard clause for this purpose, as in the fib method (which has two guard clauses).



Agile Java. Crafting Code with Test-Driven Development
Agile Javaв„ў: Crafting Code with Test-Driven Development
ISBN: 0131482394
EAN: 2147483647
Year: 2003
Pages: 391
Authors: Jeff Langr

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net