Java Interface usage

R

Rod

I recently saw some code that looked like the example below ..
my question is why the developer used
"this(SOME_WORDS)" in the constructor for SomeClass.

Seems to me that the static string array SOME_WORDS would have been
available to SomeClass without this code in the constructor ....

========================================================
public interface SomeWords{

static final String SOME_WORDS[] = {
"Tom",
"Dick",
"Harry"
};
}

public class SomeClass implements SomeWords {

public SomeClass() {
this(SOME_WORDS);
}

public void sillyMethod() {
System.out.println("I am here");
}

}
 
R

Roedy Green

public interface SomeWords{

static final String SOME_WORDS[] = {
"Tom",
"Dick",
"Harry"
};
}

public class SomeClass implements SomeWords {

public SomeClass() {
this(SOME_WORDS);
}

the problem with static finals is you can't count on them being
defined before everything else is. The code is fragile. It depends on
the ordering of the methods and variables. So to make SURE they are
defined before anything else, you split them off into an interface.

I just invented this trick myself a few days ago, after getting nailed
by the repercussions of using eclipse to reorder methods to keep them
in a consistent order. I decided I wanted to write code that would
work no matter how the ruddy methods and variables were scrambled.



--
Bush crime family lost/embezzled $3 trillion from Pentagon.
Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video.
http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm

Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes
 
R

Roedy Green

I just invented this trick myself a few days ago, after getting nailed
by the repercussions of using eclipse to reorder methods to keep them
in a consistent order. I decided I wanted to write code that would
work no matter how the ruddy methods and variables were scrambled.

There is another reason for using interfaces:

they collect together logically related fields. If you dump them all
in one big class they can be hard to find, especially it you use an
auto-reordering tool that makes them alphabetic rather than grouped by
function.

The Eclipse extract interface is great for this, taking a hodge podge
and breaking it up into separate interfaces.

The catch is Interfaces can only hold compile time known constants
that can be computed in a single line and no arrays. I'm not sure if
that is official. but it is the way the compiler seems to behave.
..
--
Bush crime family lost/embezzled $3 trillion from Pentagon.
Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video.
http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm

Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes
 
R

Roedy Green

The catch is Interfaces can only hold compile time known constants
that can be computed in a single line and no arrays. I'm not sure if
that is official. but it is the way the compiler seems to behave.

Turns out that is not so. I did some experiments. Here is what I
found:

An interface is like a class with some restrictions.

1. All its methods must be abstract instance methods.

2. All the variables defined in an interface must be static final,
i.e. constants. Happily the values need not be known at compile time.
You can do some computation at class load time to compute the values.
The variables need not be just simple ints and Strings. They can be
any type.

3. No static initialiser blocks. You must do your initialisations in
one line per variable. And of course no static initialialiser helper
methods. If you need them, them must be defined outside the interface.

Eclipse refactoring leaves array constants behind when you ask it to
move them off to an interface. However, you can move them manually
yourself. It is perfectly ok to have array constants in an interface.
--
Bush crime family lost/embezzled $3 trillion from Pentagon.
Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video.
http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm

Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes
 
G

Gordon Beaton

I recently saw some code that looked like the example below .. my
question is why the developer used "this(SOME_WORDS)" in the
constructor for SomeClass.

Seems to me that the static string array SOME_WORDS would have been
available to SomeClass without this code in the constructor ....

========================================================
public interface SomeWords{

static final String SOME_WORDS[] = {
"Tom",
"Dick",
"Harry"
};
}

public class SomeClass implements SomeWords {

public SomeClass() {
this(SOME_WORDS);
}

Yes, the code could refer directly to SOME_WORDS anyway, but then any
application using this class is locked in to a single word list, and
the class isn't nearly as useful or flexible as it could be. In order
to use a different word list, you'd need to recompile the SomeWords
interface.

This constructor is obviously missing from your example:

public SomeClass(String[] words) {
/* ... */
}

So the default constructor (the one you showed) initializes the class
with the given wordlist, and maybe that is all that's needed in most
cases. However an application needing different words can do something
like this:

String[] my_words = WordFileReader.readWordsFrom("special_words.txt");
SomeClass sc = new SomeClass(my_words);

/gordon
 
A

Andrew McDonagh

Roedy said:
quoted :


I just invented this trick myself a few days ago, after getting nailed
by the repercussions of using eclipse to reorder methods to keep them
in a consistent order. I decided I wanted to write code that would
work no matter how the ruddy methods and variables were scrambled.


you just re-invented the interface constants anti-pattern.

http://www.google.co.uk/search?hl=en&q=anti-pattern+interface+constants&btnG=Google+Search&meta=

take a pick from any of the google results...
 
S

Stefan Schulz

the problem with static finals is you can't count on them being
defined before everything else is. The code is fragile. It depends on
the ordering of the methods and variables. So to make SURE they are
defined before anything else, you split them off into an interface.

Not true. Static finals (and indeed all statics) are guaranteed to be
defined before the constructor gets invoked (after class loading to be
precise). Non-final statics may be re-defined later on.

As for in which order statics are defined is dependant on their relative
positioning, but code that relies on this feature is fragile at best,
broken at worst.
 
S

Stefan Schulz

they collect together logically related fields. If you dump them all
in one big class they can be hard to find, especially it you use an
auto-reordering tool that makes them alphabetic rather than grouped by
function.

Don't do that, then
 
S

Stefan Schulz

3. No static initialiser blocks. You must do your initialisations in
one line per variable. And of course no static initialialiser helper
methods. If you need them, them must be defined outside the interface.

Hmm, this works for me:

interface Foo {
public static final int x = 1
+ 3
+ Math.max(3, 7)
+ (int) (Math.random() * 7);
}
 
R

Roedy Green

3. No static initialiser blocks. You must do your initialisations in

Hmm, this works for me:

interface Foo {
public static final int x = 1
+ 3
+ Math.max(3, 7)
+ (int) (Math.random() * 7);
}

I should have said "one statement" rather than "one line".


--
Bush crime family lost/embezzled $3 trillion from Pentagon.
Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video.
http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm

Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes
 
R

Roedy Green

As for in which order statics are defined is dependant on their relative
positioning, but code that relies on this feature is fragile at best,
broken at worst.

Let's say you do need an ordering. how do you ensure that ordering is
not broken?

You could use a distinctive alpha naming convention so any sorting
would put them in the correct order e.g. aainit01_xxxx aainit02_xxx,
but those names destry their usefulness for any other purpose.

You could move the precondition to an interface (an antipattern)

you could make a note that will be ignored.


--
Bush crime family lost/embezzled $3 trillion from Pentagon.
Complicit Bush-friendly media keeps mum. Rumsfeld confesses on video.
http://www.infowars.com/articles/us/mckinney_grills_rumsfeld.htm

Canadian Mind Products, Roedy Green.
See http://mindprod.com/iraq.html photos of Bush's war crimes
 
R

Raymond DeCampo

Roedy said:
but sooner or later you will, or somebody using your code will. It is
not polite to hand out fragile code.

Just because your IDE gives you a button doesn't obligate you to press
it. :)

Ray
 
R

Raymond DeCampo

Stefan said:
Not true. Static finals (and indeed all statics) are guaranteed to be
defined before the constructor gets invoked (after class loading to be
precise). Non-final statics may be re-defined later on.

As for in which order statics are defined is dependant on their relative
positioning, but code that relies on this feature is fragile at best,
broken at worst.

Is this fragile:

public void x()
{
String y = "abc";
String z = y + "def";
String w = y + z;
}

Is that really so different from:

public class X
{
private final static String y = "abc";
private final static String z = y + "def";
private final static String w = x + y;

}

Ray
 
V

Virgil Green

Raymond said:
Just because your IDE gives you a button doesn't obligate you to press
it. :)

Ray

I regularly feel compelled to push all the buttons in my IDE.
 
T

Thomas G. Marshall

Virgil Green coughed up:
I regularly feel compelled to push all the buttons in my IDE.


That can be a *big* problem with eclipse in particular, whose buttons and
features still confuse the bejeebers outta me. One day I was pressing
buttons randomly just trying to get it to work and my toilet flushed.
Another time it made my neighbor's lights flicker on and off.


--
Puzzle: You are given a deck of cards all face down
except for 10 cards mixed in which are face up.
If you are in a pitch black room, how do you divide
the deck into two piles (may be uneven) that each
contain the same number of face-up cards?
Answer (rot13): Sebz naljurer va gur qrpx, qrny bhg
gra pneqf naq syvc gurz bire.
 
T

Thomas G. Marshall

Rod coughed up:
I recently saw some code that looked like the example below ..
my question is why the developer used
"this(SOME_WORDS)" in the constructor for SomeClass.

Seems to me that the static string array SOME_WORDS would have been
available to SomeClass without this code in the constructor ....

========================================================
public interface SomeWords{

static final String SOME_WORDS[] = {
"Tom",
"Dick",
"Harry"
};
}

{sound of screeching brakes, collision, and idle hub cap wobble...}

<Foaming location=Mouth>

I absolutely loath this mis-feature of interfaces. It is in my mind not
just an anti-pattern, but an anti-anything-good. :-| It allows you to
specify a constant, sure, but that constant can be accessed *without
qualification* making it potentially murder to find if you're programming
without an IDE. To me it is sloppy and I'm amazed that it was ever allowed.

Interfaces should establish behavioral contracts, devoid of implementation.
Many have argued that sometimes constant data is part of that contract, but
if so it should be a requirement that it be accessed in a name-qualified
manner----not fully, just the interface name is good enough. Just having
ID's float in space throughout the hierarchy without an anchor is just a
Freaking Horrible Idea (tm), IMO.

</Foaming>


--
Puzzle: You are given a deck of cards all face down
except for 10 cards mixed in which are face up.
If you are in a pitch black room, how do you divide
the deck into two piles (may be uneven) that each
contain the same number of face-up cards?
Answer (rot13): Sebz naljurer va gur qrpx, qrny bhg
gra pneqf naq syvc gurz bire.
 
A

Alan Krueger

Thomas said:
Virgil Green coughed up:

That can be a *big* problem with eclipse in particular, whose buttons and
features still confuse the bejeebers outta me. One day I was pressing
buttons randomly just trying to get it to work and my toilet flushed.

One time I flushed the toilet and came back to Eclipse only to see a
"Exception running validator" error message in the Visual Editor plugin.

I hope it was coincidence.
 
A

Alan Krueger

Roedy said:
Let's say you do need an ordering. how do you ensure that ordering is
not broken?

You could use a distinctive alpha naming convention so any sorting
would put them in the correct order e.g. aainit01_xxxx aainit02_xxx,
but those names destry their usefulness for any other purpose.

This is pointless. You assume someone will want to use the collation
sequence you're most familiar with. There are innumerable *other*
collation sequences that will change the ordering, too.

I would submit that this is a deficiency in the code formatter rather
than the code.
 
H

Hemal Pandya

Rod wrote:

And then many other wrote. But I don't think any of the responses
answer OP's question, which was:
my question is why the developer used
"this(SOME_WORDS)" in the constructor for SomeClass.

Seems to me that the static string array SOME_WORDS would have been
available to SomeClass without this code in the constructor ....

Difficult to to say. I wonder why OP chose to skip the implementation
of the one constructor that accepts a String array. But my guess is
that the objects SomeClass work with arrays of string that are subsets
of SOME_WORDS and the instance created using default constructor works
with the entire set SOME_WORDS.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,832
Latest member
GlennSmall

Latest Threads

Top