Re: [Hampshire] Happy Happy Joy Joy

Top Page

Reply to this message
Author: Graham
Date:  
To: Hampshire LUG Discussion List
Subject: Re: [Hampshire] Happy Happy Joy Joy
Apologies to everyone for straying OT...

On Sun, 2007-09-23 at 11:32 +0100, Samuel Penn wrote:
> Generally though, you don't need destructors in Java (I've only
> seen them used once, and they ended up being removed because
> they caused a bug by closing something that was still being used
> rather than simply letting the GC 'do the right thing').


I think like anything, if you're not used to using it, you'll work
around it without thinking about it. Nevertheless, it is useful. A
typical example, you have a logical model that has a lock and unlock.
You provide a class, so that it has the lock() call in the constructor
and unlock() in the destructor. When your logical lock goes out of
scope you want the model to be unlocked. Not possible in java since
there's no guarantee the destructor will ever be called, so now you have
to make the lock call yourself and unlock in a finally{} block. All
very well until you forget your finally block.

> > As for final, it is not the same as const. It only indicates that a
> > variable won't be reassigned, but you can still change its state.
>
> Okay, I see. Can't say I've ever needed to do this, and don't
> see it as being much of an issue. If you're writing X yourself,
> you'd make the private variable final, or remove the setter
> (it really shouldn't have a setter in the first place, if i is to
> be final). Or wrap it in another class which has no setter. How
> often do you really need to do this?


And that's often a solution, but its a convoluted solution to a simple
problem.

A C++ solution:

public class X{
  public:
    X(const int i) : m_i(i){}
    int getX()const { return m_i; }
    void setX(const int i) { m_i = i; }
  private:
    int m_i;
}


const X x(123);

In C++ we can x.getX() but we can't x.setX() else we get a compiler
error. That gives us a simple solution to a simple problem.

In Java, we might do something like this:

public interface ReadOnlyX
{
int getX();
}

public class X implements ReadOnlyX {
public void X(final int i) { m_i = i; }
public int getX() { return m_i; }
public void setX(final int i) { m_i = i; }
}

const ReadOnlyX x = new X(123);

Now we have a read only copy of X, but I think this is bad because it
obfuscates the code. It requires an unnecessary level of abstraction
that I find becomes a more problematic in larger projects. Essentially
it's working around deficiencies in the language.

My opinion is that the language is the weakest part of java. :)


Graham