Just about anything

Yet another blog about programming, technology and general musings on life

Variable Precedence

Posted by calvinkrishy on May 25, 2007

Oracle ‘knows’ which token is a variable and which is a column in a table. This becomes important when you are using a variable whose name clashes with that of a column name in a predicate. Consider the following:

create table tbl (x number)
/
insert into tbl values(1)
/
declare
x number;
d number;
begin
select count(*) into d
from tbl where x > 0;
end;

This compiles fine under Oracle. Oracle ‘knows’ that the x referred to in the query is the column and not the variable. But a similar piece of code under Informix results in ‘-696 Variable () has undefined value’.

create table tbl(x int);
insert into tbl values(1);
create procedure demo_err()
define d, x int;
select count(*) into d
from tbl where x > 0;
end procedure;
call demo_err();

In fact, the Informix guide explicitly states that the local variable takes precedence.

Whose handling is more appropriate? Either way, I feel the IDS folks should throw up easily understandable error – ‘Variable () has undefined value’ spoilt a n00b’s afternoon :(

Posted in Database, IDS | Leave a Comment »

const-ness in Java

Posted by calvinkrishy on November 22, 2006

Immutability in Java either by your design (as seen in the previous posting) or as provided by the core libraries (as in the String class) is an all-or-nothing proposition. Immutability is determined by the design of the class itself, and not later while creating an object of this class. It’s all dandy if that’s what you want, but sometimes such rigidity gets your goat.

Consider a contact object that’s part of your person class:

class Contact{

    private String email_address;
    private String address;

   //With getters and setters
}

class Validator{
    static boolean isContactValid(Contact a, Contact b){
       ...
    }
}

public class Person{

    private Contact contactInfo;
    private String name;
    ...
    Person(String name){
            this.name = name;
    }
    public setContact(Contact contact){
        this.contactInfo = contact;
    }
    public getContact(){
        return this.contactInfo;

    }
   ...
    public static void main(String args[]){
         Person p = new Person("Calvin");
         Contact c = new Contact();
         //Set some values for this contact
         p.setContact(c);
    }
}

Should the contact object be immutable? Of course not. After all, people do tend to change their houses, phone number, email addresses etc.,.

Now what if you had to pass this contact information to another method? How can you ensure that the contact is not changed by that method i.e. how do you ensure that a method does not end up modifying the state of your object (probably inadvertently)?

Interestingly, this whole problem can be solved by one keyword in C++ – const. Adding const to a variable ensures that the values held in an object pointed to by that variable cannot be changed. So just declaring a variable as follows guarantees that the object referred to by that variable stays the same till the program terminates.

int main(){
    Person* p = new Person("calvin");
    const Person* q = p;
}

So in the above example, if you do a q->setName(“Hobbes”) it would be flagged by the compiler, but p ->setName(“Hobbes”) would be just fine. Simply put const-ness in C++ is an attribute attached to a variable and not to an object. This is one of the many myriad uses of const.

Sounds like time to use the keyword final for our variable in Java? Not so fast batman!

Adding the keyword final to a variable ensures that a particular reference cannot be changed again,it does not mean that the values pointed to by that reference are final (This is the equivalent of a const pointer in C++). What this means in the code snippet below, is that the variable obj cannot point to any other object but obj’s values can be changed. This of course applies only to higher level objects and not to primitives. A primitive once declared final cannot be changed.

final Person obj = new Person();
final int i = 10; // There is no way i can be changed
obj = new Person(); //Not allowed, a compilation error. Final always points to the same object till the end of time.
obj.setName("Calvin"); //This is fine, but this is what we want to make contextual

So what we need here is a mechanism that avoids an object’s value to be changed once it’s created. This does not necessarily mean that we need an immutable object. As I mentioned above under certain circumstances we want the ability to change the values in the Contact object but on certain other occasions we do not want the values to be touched.

Enter designing to an interface. An interface is a contract. When a class claims it has implemented an interface you immediately know the access points that class provides. In our preceding example, we would like to ensure that the isContactValid method doesn’t change any of the contact object’s properties. What we do now is to ensure that the Contact and Person be interfaces with only getters and their implementations provides mutable versions.

interface Contact{
    String getEmailAddress();
    String getAddress();
    ...
}

class ContactImpl implements Contact{

    private String email_address;
    private String address;

    //The getter methods as declared in the interface

    void setEmail(String email){
           this.email_address = email;
     }
     ...
}

class Person{

    private String name;
    private Contact c;

    void setContact(Contact c){
           this.c = c;
    }

    Contact getContact(){
           return this.c;
   }

   public static void main(String args[]){
          ContactImpl c = new ContactImpl();
          c.setEmail("email@example.com");
          ...
          Person p = new Person();
          p.setContact(c);
          Validate.isValidContact(c);
          c = (ContactImpl) p.getContact();
   }
}

What this does is that it exposes a immutable access point to your object and if a need arises you can very well cast it to the implementation and do the necessary mutating actions. You do not expose setter methods that might result in the object being changed. Now what is stopping isValidContact method from type casting to ContactImpl and wreck havoc? Well, nothing! But when you realize that you have to a type cast explicitly that should immediately ring a bell and lead to a rethink of your approach (hopefully!).

At this point no matter how many people vote, Sun is in no mood to add const to Java. So following this interface driven approach is one way to achieve limited const-ness in Java. Why do I say limited? Because I think there are things which can be achieved by using const that cannot be achieved in Java in a straight forward manner. One of them is the mechanism to ensure that a method doesn’t change any values. Or “codely” put how can we achieve the following in Java? Any ideas?

class Person{

   private:
       int age;
       float pension;    

   public:
    int getAge(){
        return age;
    }
    float getPension() const{
         if (age < 60)
             return 0;
          else{
            //Some calculation stuff
            age--; //BUG. This will be flagged an error during compilation. A probable logical bug that can be eliminated
            return pension;
          }
    };

Posted in Java | 1 Comment »

Immutability

Posted by calvinkrishy on November 2, 2006

Strings in Java are immutable. That is to say once you create an object of type String no amount of hand-waving, object wrangling can change that object. I will throw some light on immutability in this posting and in a subsequent post talk about const-ness.

Immutability guarantees that an object once created stays the same until the program terminates. The JLS mentions that String objects have a constant unchanging value stated otherwise Strings are immutable.

Immutability is achieved by following two simple rules
1. The class is declared final thereby ensuring that no other class can sub-class.
2. The properties of the class are declared private and the only way to set these properties is through the constructor. If there are methods in the class that need to operate on these properties and return a object then these methods should return new objects and not modify the property in anyway.

A quick note on the ‘final’ keyword before we start off. When the keyword final is attached to a variable it
is guaranteed that a subsequent assignment to that variable would not be allowed. But this does not mean the object thus created cannot be changed. The state of the object can still be changed by using methods exposed by the class for example setter methods. Therefore, just marking a variable final does not in any way guarantee immutability as long as the class that object belongs to has methods that allow the modification of the property.

The important point to remember when programming immutable classes in Java is that immutability is built into the class and is not a property of the object. What this means in simple terms is that the quality of an object to be changed depends on the way the class is designed and not on the context in which the object is used. Contrast this with const functionality provided by C++ – a language that Java derives much syntatic sugar from. Declaring a variable const in C++ guarantees that that particular object would not be modified. Calling a setXXX type method on a const object would result in compilation error. You could create a different object of the same class and that can be made modifiable.

This const-type behavior is achieved in Java using interfaces. More on that in a subsequent post.

Now onto immutability in a POJO. Consider the sample code below:

public class Parent{
    private int data;

    Parent(int data){
       this.data = data;
    }

    void setData(int data){
        this.data = data;
    }

    int getData(){
        return this.data;
    }

    public static void main(String args[]){
	final Parent c = new Parent(5);
        System.out.println(c.getData());
        /*The following is not allowed since c is declared final
          c = new Parent(6);
          But the class can still be changed using the setter provided!*/
          c.setData(4);

    }
}

Since our aim here is to make Parent immutable we remove the setter method thereby making it mandatory for the creators of the Parent objects to initialize data using the constructor. The class does not have any setter methods ensuring that there is only one way to set the value of the property. We remove the final keyword also from the variable since all we are interested here is to make the objects created immutable and not the variable that points to them.

public class Parent{
    private int data;

    Parent(int data){
	this.data = data;
    }

    int getData(){
        return this.data;
    }

    public static void main(String args[]){
	Parent c = new Parent(5);
        System.out.println(c.getData());
        /* The following cannot be done since the method just doesn't exist!
          c.setData(4); */
    }
}

Mm., so it appears we have achieved what we set out to achieve without making the class final. The property is private and there are no methods that allow the user to change the property. Or did we really achieve immutability? Since the class is non-final a sub-class could extend it and provide a mutable version. How does this affect immutability? Let’s take a look.

class Parent{
    private int data;

    Parent(int data){
	this.data = data;
    }

    final int getData(){
        return this.data;
    }

    public int hashCode(){
        return 37 * 17 + this.data;
    }

}

class Child extends Parent{
     private int data;

     Child(int i){
           super(i);
           this.data = i;
     }

     void setData(int data){
	this.data = data;
     }

     public int hashCode(){
        return 37 * 17 + this.data;
     }

}

class Thingamagic{
    public static void main(String args[]){
	Parent c = new Child(6);
        ((Child)c).setData(7);
    }
}

Isn’t this mutable? Since even now calling c.getData() will give us only 6 and not 7. The point is the state of the object has changed since it’s creation and that is exactly what we are trying to avoid. If immutability is guranteed a call to hashcode() on the object should return the same value throughout the life of the object but once this object becomes mutable, the hashcode changes and this can have implications in sections of code that depend on immutability (hashtable keys for example).

The reasons for maintaining immutability are subtle and often escape the vision of a developer. One case that is often cited is the usage of immutable objects as keys to hashtables. Consider the code below:

class Parent{
    private int data;

    Parent(int data){
        this.data = data;
    }

    int getData(){
        return this.data;
    }

    public int hashCode(){
	return 37 * 17 + this.data;
    }

    public boolean equals(Object obj){
        Parent comp = null;

        if(obj instanceof Parent)
            comp = (Parent)obj;

        if(comp.getData() == this.getData())
            return true;
        else
            return false;

    }

}

class Child extends Parent{

    private int data;

    Child(int data){
        super(data);
        this.data = data;
    }

    void setData(int data){
        this.data = data;
    }

    int getData(){
	return this.data;
    }

}
public class FinalVerify{
    public static void main(String rags[]){

	Hashtable<Parent, String> h = new Hashtable<Parent, String>();
	Parent fc = new Child(1);
	h.put(fc, "one");

	for(Parent f : h.keySet())
	    System.out.println(f.hashCode());

	((Child)fc).setData(2);

	for(Parent f : h.keySet())
	    System.out.println(f.hashCode());

	System.out.println(h.get(new Parent(1)));

    }
}

Hashtables use the hashCode() and the equals() method to determine the equality of keys and running the code above you’d observe that making the class non-final can result in the key being ‘lost’.

Marking the class final would avoid this problem since no other class would be able to derive from it and create a mutable version.

So a proper Immutable class in our case would be:

final class Parent{
    private int data;

    Parent(int data){
	this.data = data;
    }

    int getData(){
        return this.data;
    }

    public int hashCode(){
       return 37 * 17 + this.data;
    }

    //Hopefully other useful methods...
}

The String class satisfies both the points since the class is final and it does not expose any methods that allows one to change it’s state once a String object is created. James Gosling in an interview with Bill Venners has provided more insight on this.

References:
Joshua Bloch talks about designing an effective hashCode and equals method among other things in ‘Effective Java’ – http://java.sun.com/docs/books/effective/

Posted in Java | 4 Comments »

Hello world!

Posted by calvinkrishy on June 25, 2006

Hello world from WordPress!

Posted in General | 1 Comment »

 
Follow

Get every new post delivered to your Inbox.