How to calculate square root

The other day I ran into a question in Stackoverflow asking how to implement square-root calculation. I started googling it up and some implementations seemed to me very cumbersome but then I found Newton’s method which is pretty easy to implement. Translating it to Java was a matter of a few lines of code:

 
class Sqrt {
    public static void main(String[] args) {
        System.out.println(sqrt(17)); // 4.123105985575862
    }

    final static double DELTA = 0.0001;
    /**
     * Newton's method:
     *
     * X1 = X0 - f(x)/f'(x)
     * x^2 = num
     * f(x) = x^2 - num
     * f'(x) = 2*x
     *
     * X1 = X0 - (X0^2 - num) / 2*X0
     * ...
     * Xn = Xn-1 - ((Xn-1)^2 - num)/2Xn-1
     *
     * Stop condition: |num - (Xn)^2| < DELTA 
     * */ 

    public static double sqrt(double num) { 
        double x = num / 2; // starting point
        while(Math.abs(num - x * x) > DELTA) {
            x = x - ((x * x - num) / (2 * x));
        }
        return x;
    }
}
How to calculate square root

Inheritance overflow…

Been fiddling with Java lately when I ran into the following cute quiz about inheritance.

Reading some articles about what’s Good/Bad in Java – I ran into the following code from an article called why Java sucks?:

class Boo{}
class Buzz extends Boo{}

class Play{

    static void foo(Boo b){
        System.out.println("in foo(Boo b)");
    }

    static void foo(Buzz b){
        System.out.println("in foo(Buzz b)");
    }

    public static void main(String...args){
        Boo b = new Buzz();
        foo(b);
    }
}
  • What would you think will be printed ?
  • Do you know why ?

Answer: variable b is declared as a reference to object of type Boo during compilation, and that’s why foo(Boo b) is chosen over the “more intuitive” option.

The reason that it works this way is that Java (as well as many other OO languages) is single dispatch. There are other languages like Common Lisp that supports “multiple dispatch”: the decision which version of a method will be called is based both on the class of the object as well as the run-time types of the arguments!

By the way, “multiple dispatch” behavior can be achieved in “single dispatch” Languages by using the Visitor pattern (described in “design patterns” book).

I started a list of my own about the things I like/don’t-like in Java and here’s the outcome:

Plus Minus
write once – run anywhere still slower than C++
Many good libraries (both java/javax as well as 3rd parties) no multiple inheritence
Garbage collection horrible character escaping when using regex
boxing can’t pass methods as a parameter
inner classes + anonymous classes handling primitives differently (why not treat them as objects?)
reduces boilerplate code every version (generics, try with resources, filters) still too verbose (open a file…)
If inner class wants to use a variable of the parent – it must be declared final
checked exceptions can be a pain with interfaces
Inheritance overflow…

I see dead code (homage for IntelliJ Idea)

intellij-624x120

About a month ago I went with my friend David to Silicon Valley CodeCamp. David met a few friends so we all set together and had lunch during which we discussed a few coding issues but we were also excited about the raffle which was to take place right after lunch. I told them that I’m not interested in the XBOX (which was considered as the best prize) and that what I would really LOVE is to get a license for intelliJ. First time I “met” intelliJ was

Back to our lunch at Silicon Valley CodeCamp. People were hoping to win the XBOX and I told them that I don’t care about the XBOX and that I wish they would throw in intelliJ licenses (one license worth $500). We finished our lunches and went to the main court where the raffle took place, and to my astonishment, the guy with the mic announced the list of prizes and among them, one intelliJ license. I was stunned. David laughed and said: “I’m going to win this one for you”.

And believe it or not – he did!

intellij_idea

A few days later, I’m sitting at my desk, installing the newest version of intelliJ, and it took me only a few seconds to see what I was missing so much…

Jetbrains, the company that made intelliJ had a booth there in SVCC – so I got myself a shirt that says: “I see dead code”. And now I really do: among many other cool features, intelliJ finds unused parameters and colors them in grey. This simple feature is priceless (and I’m not familiar with any equivalent feature in Netbeans/Eclipse).

iseedeadcode

The shirt I got at SVCC

So, at that same first day when I started using intelliJ again, I went over some code, looking for something, and then I run into the following method (two points to the readers that find what’s wrong with this method):

  private String getContractName(Connection conn, int contractOrderId) {

    String methodName = "getContractName";
    PreparedStatement st = null;
    ResultSet rs = null;
    String contractName = null;
    try {
      //get contract name
      String sqlQuery = "SELECT CONTRACT_NAME FROM __CONTRACTS WHERE contract_order_id=?";
      st.setInt(1, contractOrderId);
      rs = st.executeQuery();

      if (rs.next()) {
        contractName = rs.getString("CONTRACT_NAME");
      }
    }
    catch (Exception e) {
      Utils.writeLog(className + ":" + methodName +"- Warning: " + className + ":" + methodName + "-" + e.getMessage(), DEBUG);
    }
    finally {
      Utils.closeConnections(null, st, rs, null);
    }
    return contractName;
  }

Without intelliJ it’s not easy to see it, but if you figured it out – way to go!
Between the following two lines:

String sqlQuery = "SELECT CONTRACT_NAME FROM __CONTRACTS WHERE contract_order_id=?";
st.setInt(1, contractOrderId);

there’s one “little” line missing:

st = conn.prepareStatement(sqlQuery);

This could be easily detected with intelliJ since “Connection conn” passed in the method’s signature was marked grey. Actually, there isn’t only one wrong thing with this method, now that we understand the problem, we can also see that every time this method is being called, an exception is being thrown on:

st.setInt(1, contractOrderId);

and that this exception is caught six lines below – but the only thing that is being done is a “debug” printing to log (not even an error!) and then the method ALWAYS returns null and continues.

How many bad practices do we see here – can you count ?

1. we don’t “fail-fast” (the method should have either thrown an error or at least print ERROR to log instead of DEBUG).
2. we throw and catch an exception (which is costly!) without really handling it.
3. we return a default value which is meaningless
4. I’m 100% sure that no unit-tests, functionality tests, regression, end-to-end or any kind of tests were written and used here – otherwise this bug would have been easily caught.

So here’s a call to all you decision makers, think about the hours of debugging, fixing, reviewing the code-fix, QAing the fix and deploying – that could be saved, not to mention potential damage that could be done to your company and your clients. Always consider purchasing the best tools you can for your engineers. It might look like an “expensive investment” but it’ll pay off, trust me (and if you can’t trust me, you should believe Joel. Check-out item #9 on his list).

I see dead code (homage for IntelliJ Idea)

Guava is much more than a delicious fruit!

google

Yesterday I went to a meet-up organized by Silicon Valley Java User Group, the subject was An Overview of Guava: Google Core Libraries for Java. Naturally, it was hosted at Google. Since I was already late, Murphy decided it would be a good idea to f*ck with me: traffic on 101 was crawling at ~20mph (I’m sure that those of you from the valley will totally understand…).

Anyways, I was only 20 minutes late, when I found out there was still plenty of pizza and drinks, apparently I wasn’t the only one who was late. I still had bout half an hour for mingling, but developers are not great at socializing, so I found myself cursing for not bringing with me my Nexus 7″.

Finally the place filled up, it looked like this:

meetup
An Overview of Guava @Google headquarters

Picture credit: Lawrence

A few words about Guava:
Guava is a collection of Google Java-based libraries which includes: caching, hashing, concurrency, collections, I/O and more. The main reason I wanted to attend this event was hearing about their caching solution, unfortunately, right at the beginning of the lectureKurt Alfred Kluever said that caching deserves a separate talk. The good news are that the organizer of the meet-up sent a link to this video right after the talk (the first twenty seconds are in French so don’t get stressed ;)

I asked a couple of questions, one about their caching-library – if it was properly benchmarked and compared to other alternatives (memcache for instance) and the answer I got was that many people decide to implement their own benchmarking and do it poorly, so Guava team assigned one of their team-members to work on a micro-benchmarking library!

A couple of other cool stuff they implemented are the MultiMap (a Map which can hold multiple values for one key) and the BiMap (Map which supports mapping the values back to keys). You can download the slides from the talk here. Also, you can find here some code-examples.

To sum up:

  • Guava looks like something I will definitely check
  • Google looks like amusement-park for developers!
Guava is much more than a delicious fruit!