Wednesday, November 16, 2011

Is this a valid use of an interface?

I saw a piece of code that made me wonder if this was normal when using interfaces or if it is just abusing the functionality of an interface... The code looks like so:
 
public interface Constants {
    public static final String URL = "localhost:1099";
    ... // Other constants defined
}

Later on it is used like so:
 
public class Something implements Constants {
     ...
     Context ctx = new InitialContext( PropertiesFactory.getProperties( URL ) );
     ...
}

Is  it normal practice to create an interface with a bunch of constants in an interface (without any methods defined), then implement the interface in a class and use the constants? 

I would have just statically accessed those parameters directly rather than doing it this way. If you have an opinion, answer to my thought or are just bored, let me know.  Well, perhaps not if you're bored.

Wednesday, November 2, 2011

Now this is funky

I wrote something funky today. I was trying to create an instance of an inner-class that was part of my Blah DTO. In Blah, there is a List of Foo objects that needs to be populated based on some logic.

private void populateBlah(Blah var) {

   ...
   Foo foo = var.new Foo();
   ...
}

At first glance, I was baffled at the syntax. I had tried doing the obvious

Foo foo = new Foo();

but Eclipse would have none of it. It threw one of these at me when I tried that

No enclosing instance of type Blah is accessible. Must qualify the allocation with an enclosing instance of type Blah (e.g. x.new A() where x is an instance of Blah).

This still made no sense to me after reading. The Syntax just didn't seem right. I was expecting maybe to create an instance of this perhaps:

Foo foo = new Blah.Foo();

but again, that wasn't the case. Anyway, above is apparently how you instantiate a non-static inner class variable. Who knew. You learn something new every day.