Sunday, September 20, 2009

Puzzle 53 – Statically Speaking.

Language – Java | Type – Concept | Last date 27-Sep-2009 12:00 p.m. IST | Points 3

This puzzle is interesting because it's based on a real life incident that happened with a colleague of mine. To give you a gist of what happened, here is the code (well this isn't the real code – just the important part)

package com.twister;
class MyData{
String author
= com.twister.Constants.AUTHOR;
//lot of other stuff comes here…

public static void main(String[] args) {
MyData mydata
= new MyData();
System.out.println(mydata.author);
}
}

package com.twister;
class Constants{
public static final String AUTHOR = "SAM"; //Me of course

}

Here is what happened. This was some code that I had written – see my name in the Constants file. Well my colleague picked up my code and just modified the String Author to his, recompiled the Constants file and went on to show a demo to the manager. Ops something went wrong here, which got him into a lot of trouble. Can you figure out what went wrong? (Assume he codes using Notepad). What are the possible solutions to this problem?

Got an answer? Do leave it here.

4 comments:

  1. Constants are inlined by compiler. So old AUTHOR value used in MyDate class even after Constants was recompiled.

    ReplyDelete
  2. static final fields are not referenced but are inlined into the code.

    your friend in this case only compile 1 part of the code which will not replace the text where it is inlined.

    sollution:

    1) re-compile the complete code.
    2) don't use static final :)

    ReplyDelete
  3. The class variable AUTHOR in Constants is a final variable making it a compile time constant.
    From JLS:
    'Simple names that refer to final variables whose initializers are constant expressions' (qualify to be compile-time constants)

    References to compile time constants are resolved at compile-time to a copy of the compile-time constant value and hence accessing these fields does not cause an initialization of the class containing the field.

    The easiest fix here would be to make AUTHOR a non-final variable.

    class Constants{
    public static String AUTHOR = "ANEESH";
    }

    or keep the final keyword , make it non-static and initialize it in the Constructor

    class Constants{
    public final String AUTHOR;

    public Constants(){
    AUTHOR="ANEESH";
    }
    }

    That requires more changes than the first one of-course.

    ReplyDelete
  4. This is got to be something with static keyword. I also dont have the complete idea about , what happens when we declare a variable as static . Luking forward to hear a good answer from you.

    Thanks.

    ReplyDelete

Solution for this question?