Interface with implied Constructor

R

Richard Maher

Hi,

I have an interface that requires an implementer to cut code that 99%
sure is going to need some variables that are built at run-time. The
class to be developed will also be loaded at run-time via Reflection.

Most people I have consulted recommend going the null Constructor in
combination with Setters, or an INIT() method, to communicate the
ambient variables to the loaded class. I, on the other hand, would like
to go the Constructor-Injection-esque root of attempting to invoke a
version of the Contstructor with the arguments I specify. (Maybe
failover to null constructor on InvocationException) Is there something
intrinsically wrong with doing this in Java? (I know there are Abstract
Classes but I have only Abstract Methods.)

If you like to know the real example then what I'd like to pass to the
Constructor is the ParentFrame and an Application name.
London-to-a-brick the callee will create a Dialog Box.

Cheers Richard Maher
 
R

Robert Klemme

I have an interface that requires an implementer to cut code that 99%
sure is going to need some variables that are built at run-time. The
class to be developed will also be loaded at run-time via Reflection.

Most people I have consulted recommend going the null Constructor in
combination with Setters, or an INIT() method, to communicate the
ambient variables to the loaded class.

That's what I'd do as well: make that method part of your interface and be done.
I, on the other hand, would like
to go the Constructor-Injection-esque root of attempting to invoke a
version of the Contstructor with the arguments I specify.

Why do you want to do that?
(Maybe
failover to null constructor on InvocationException) Is there something
intrinsically wrong with doing this in Java? (I know there are Abstract
Classes but I have only Abstract Methods.)

I think it could be that you are making things overly complicated.
If you like to know the real example then what I'd like to pass to the
Constructor is the ParentFrame and an Application name.
London-to-a-brick the callee will create a Dialog Box.

An alternative approach would be to not configure the class and instantiatethat via reflection but to use factory pattern: define another interface with a create method which receives all the necessary arguments and returns the interface you have already, load that class via reflection with defaultconstructor and let it create instances as needed.

Cheers

robert
 
R

Richard Maher

Why do you want to do that?

For me it's personal preference, but for some technical rationale: -

If you don't provide sufficient information to the constructor:
1) You get half-baked objects
2) Every real (non-init()) method now has to check "Has init() run? Am I
complete?"
3) If using setters, how do you enforce that they are called in the
correct order?

Most importantly, Why the hell do you think Java (and all other OO
languages) support arguments to constructors and overloading in the
first place??? Do you think the authors have been wasting their time or
providing redundant technology all these years?

So let me ask you "Why do you want to use setters or an init() method?"

Cheers Richard Maher
 
E

Eric Sosman

For me it's personal preference, but for some technical rationale: -

If you don't provide sufficient information to the constructor:
1) You get half-baked objects
2) Every real (non-init()) method now has to check "Has init() run? Am I
complete?"
3) If using setters, how do you enforce that they are called in the
correct order?

Most importantly, Why the hell do you think Java (and all other OO
languages) support arguments to constructors and overloading in the
first place??? Do you think the authors have been wasting their time or
providing redundant technology all these years?

Somebody's losing his cool ...
So let me ask you "Why do you want to use setters or an init() method?"

Because it's more flexible, perhaps. Do you feel that
HashSet should have an (int,boolean,boolean,int,int,Throwable)
constructor, just because DataTruncation also has one and both
classes implement Iterable?

Interfaces are about "contracts," about the "promises" an
implementing class makes. Constructors are about initialization
of particular class implementations. If interfaces were able to
legislate the existence of specified constructors, and if the
related "promise" was that an instance so initialized would be
complete and functional, then how could you ever implement a
class that needed just one little smidgen of additional state?

For example: In a recent thread somebody was talking about
a ColoredPoint class that carried the notion of a location and
an associated color. Let us suppose that this ColoredPoint class
implemented a Point interface, and that the interface demanded
the existence of an (int x, int y) constructor. Well then, how
can a ColoredPoint be sure of getting a color? You could write
the required constructor and default the color to mauve, but would
that be satisfactory? I don't think so: The eventual user of the
class would have to use a constructor not mentioned by the interface,
or would have to use a setter also not mentioned by the interface.
What benefit would the constructor-mandated-by-interface confer?

Granted, the line between "contract" and "promise" can be a
bit blurry sometimes. An interface can require the existence of
a method with a certain name and parameter list and can influence
the return type and visibility, but it cannot really say much
about what the function does: An Iterable must have a public
hasNext() method of no arguments returning a boolean, but as far
as Java is concerned `public boolean hasNext() { return false; }'
is entirely satisfactory. On the other side, conventions like
JavaBeans require the existence of no-argument constructors and of
methods whose names and signatures aren't specified in any
interface. I think it's best to think of these as awkwardnesses
in the language, shortcomings that should not be imitated except
when the need is pressing -- and definitely not as practice to be
formalized and sanctified.

Finally: If you want abstract classes, ...
 
M

markspace

Most people I have consulted recommend going the null Constructor in
combination with Setters, or an INIT() method, to communicate the

Well, that's something to consider. Personally, I don't see much
difference, although you've given us no details as to what you are
actually doing here, or any particulars at all. If most people you
consult say not to do something, maybe they know something we don't.

You may wish to compare with Java's DriverManager, which will load and
configure a class based on a single init string.

DriverManager.getConnection( "jdbc:vendor://username:password"
+ "@domain:port/schema",
connectionProps);

That isn't terrible, but it's not particularly elegant either, and your
colleagues may be concerned with maintenance issues, or other things.

I think you should forget reflection loading, and use a regular factory
if at all possible. Even better is to not use a factory and just access
the class directly. Is there a reason you can't just name the class and
use it? You're certain the actual class file must be supplied at
runtime, and can't possibly known at compile time?

What do you envision the API to load this class looks like? The public
one your colleagues will see, not your internal implementation.
 
D

Daniel Pitts

Hi,

I have an interface that requires an implementer to cut code that 99%
sure is going to need some variables that are built at run-time. The
class to be developed will also be loaded at run-time via Reflection.

Most people I have consulted recommend going the null Constructor in
combination with Setters, or an INIT() method, to communicate the
ambient variables to the loaded class. I, on the other hand, would like
to go the Constructor-Injection-esque root of attempting to invoke a
version of the Contstructor with the arguments I specify. (Maybe
failover to null constructor on InvocationException) Is there something
intrinsically wrong with doing this in Java? (I know there are Abstract
Classes but I have only Abstract Methods.)

If you like to know the real example then what I'd like to pass to the
Constructor is the ParentFrame and an Application name.
London-to-a-brick the callee will create a Dialog Box.

Cheers Richard Maher

Perhaps you need two interfaces instead. A factory interface, and the
actual business object interface.

Another way to handle this is to have some sort of injection where you
pass in only objects the class requires. For instance, Guice will let
you annotate a class and it will manage creating the instance for you,
injecting any objects (either via constructors or setters) that the
object needs. Spring beans will do similar things, but is more common
in web frameworks than GUIs.
 
R

Richard Maher

On 7/9/13 3:41 AM, Richard Maher wrote:

Another way to handle this is to have some sort of injection where you
pass in only objects the class requires. For instance, Guice will let
you annotate a class and it will manage creating the instance for you,
injecting any objects (either via constructors or setters) that the
object needs. Spring beans will do similar things, but is more common
in web frameworks than GUIs.

I've settled on a compromise. I will attempt to pass a single argument
"sessionAmbience" to the loaded class and if I get a MethodNotFound et
al Exception then I'll degrade to an empty Constructor.

The Tier3SessinAmbience Interface will describe all of the getters that
are available to the loaded class to assist in providing the
functionality that is required to implement the first Interface I
described in the OP. If the user's code doesn't need all of the lovely
goodies available for context then that's fine.

Cheers Richard
 
R

Richard Maher

I think you should forget reflection loading, and use a regular factory
if at all possible. Even better is to not use a factory and just access
the class directly. Is there a reason you can't just name the class and
use it? You're certain the actual class file must be supplied at
runtime, and can't possibly known at compile time?

I do not supply the class to be loaded I just require that the Interface
be implemented and that the class is part of the Tier3Client package.
What do you envision the API to load this class looks like? The public
one your colleagues will see, not your internal implementation.

I am adding a new argument HandShake {archive : "myJAR.jar", class :
"logon"} to my Tier3Client Javascript class. If it's not there at
run-time then the default login Handshake will be used, otherwise it
will be appended to the Applet's Archive list and appear on the CP. The
class will be loaded by Class.forName(appletParam).

Just to sexy for words!!!

An before you get up to your old nervous Nelly tricks and FUD about
"There be dragons" let me tell you that it all works with an unsigned
Applet.

Cheers Richard Maher
 
S

Stefan Ram

Daniel Pitts said:
Another way to handle this is to have some sort of injection where you

If Java would not forbid this, from the JVM POV, one would write:

interface example
{ public void <init>( final java.lang.String example )... };

. (Maybe some other JVM language even allows this.)
 
M

markspace

I am adding a new argument HandShake {archive : "myJAR.jar", class :
"logon"} to my Tier3Client Javascript class. If it's not there at

If you're the only one who will see this, then you can certainly do as
you like. I might suggest one single "Handshake" class, however, which
you supply in a required Jar file. Then to provide something other than
the default (which lives in its own Jar file), you just swap that Jar
file for another one.
 
D

Daniel Pitts

If Java would not forbid this, from the JVM POV, one would write:
The injection itself is not on the interface, but on the concrete type.
The OP was asking about specifying it on the interface, because it was
desired to have the code automatically inject it. Using reflection on
the concrete type does allow this, and there are libraries out there
specifically to handle this. I mentioned two, Guice and Spring. There
are probably others as well.
 
R

Richard Maher

If you're the only one who will see this, then you can certainly do as
you like. I might suggest one single "Handshake" class, however, which
you supply in a required Jar file. Then to provide something other than
the default (which lives in its own Jar file), you just swap that Jar
file for another one.
Yep, you got it.
 
K

Kevin McMurtrie

Richard Maher said:
For me it's personal preference, but for some technical rationale: -

If you don't provide sufficient information to the constructor:
1) You get half-baked objects
2) Every real (non-init()) method now has to check "Has init() run? Am I
complete?"
3) If using setters, how do you enforce that they are called in the
correct order?

Most importantly, Why the hell do you think Java (and all other OO
languages) support arguments to constructors and overloading in the
first place??? Do you think the authors have been wasting their time or
providing redundant technology all these years?

So let me ask you "Why do you want to use setters or an init() method?"

Cheers Richard Maher

There's a builder pattern than works. It's a little ugly but it's what
you have when you can't use abstract classes for some reason. Move
around the interfaces as you see fit.


MyThingBuilder.java:

public interface MyThingBuilder
{
interface MyThing
{
String doThing ();
}
MyThing build(int arg1, String arg2);
}



MyThingBuilderImpl.java

public class MyThingBuilderImpl implements MyThingBuilder
{
@Override
public MyThing build(int arg1, String arg2)
{
return new MyThingImpl(arg1, arg2);
}

private static class MyThingImpl implements MyThingBuilder.MyThing
{
private final int arg1;
private final String arg2;

MyThingImpl (int arg1, String arg2)
{
this.arg1= arg1;
this.arg2= arg2;
}

@Override
public String doThing()
{
return "MyThingImpl(" + arg1 + ", " + arg2 +')';
}
}
}


Main code:

public static void main (String args[]) throws Exception
{
//From factory Class
final Class<? extends MyThingBuilder> c= MyThingBuilderImpl.class;
System.out.println(c.newInstance().build(1, "two").doThing());

//From Factory instance
final MyThingBuilder thing= new MyThingBuilderImpl();
System.out.println(thing.build(2, "three").doThing());
}
 
R

Robert Klemme

There's a builder pattern than works. It's a little ugly but it's what
you have when you can't use abstract classes for some reason. Move
around the interfaces as you see fit.

<snip/>

I'd call that "factory pattern". Why did you pick "builder"?

Kind regards

robert
 
R

Robert Klemme

For me it's personal preference, but for some technical rationale: -

If you don't provide sufficient information to the constructor:
1) You get half-baked objects
2) Every real (non-init()) method now has to check "Has init() run? Am I
complete?"

Using a constructor to initialize an object does not make it necessary
to do that via reflection. You can have the same functionality simpler
with a factory.
3) If using setters, how do you enforce that they are called in the
correct order?

Either throw IllegalStateException or use a single method for
initialization right away.
Most importantly, Why the hell do you think Java (and all other OO
languages) support arguments to constructors and overloading in the
first place??? Do you think the authors have been wasting their time or
providing redundant technology all these years?

Hammers are useful tools - but I usually don't use them to fix a screw.
So let me ask you "Why do you want to use setters or an init() method?"

I opted for the init() method OR factory method pattern. Both are type
safe because in both cases a method in an interface needs to be
implemented. Picking a constructor solely based on argument types has a
looser coupling between the contract and the implementation of it. An
interface makes that coupling explicit.

Cheers

robert
 
K

Kevin McMurtrie

Robert Klemme said:
<snip/>

I'd call that "factory pattern". Why did you pick "builder"?

Kind regards

robert

They're similar. I've seen the term "builder" used more often when the
construction is done by the implementor and "factory" more often when
the construction is performed by a single system. Builder also has a
pattern of SomeThing a= new
Builder().with(Options.B).add(x).add(y).addAll(Z).makeImmutable(); It's
a way to specify arguments after construction without allowing access to
a partially built object.
 
D

Daniel Pitts

They're similar. I've seen the term "builder" used more often when the
construction is done by the implementor and "factory" more often when
the construction is performed by a single system. Builder also has a
pattern of SomeThing a= new
Builder().with(Options.B).add(x).add(y).addAll(Z).makeImmutable(); It's
a way to specify arguments after construction without allowing access to
a partially built object.
I would say the difference is that a builder is a type of factory which
can be configured before the factory method is invoked.
 
E

Eric Sosman

I would say the difference is that a builder is a type of factory which
can be configured before the factory method is invoked.

Ah, the old FactoryFactory pattern. That's the second time
it's been pulled on me this week!

(Sorry about that, Chief.)
 
R

Robert Klemme

They're similar. I've seen the term "builder" used more often when the
construction is done by the implementor and "factory" more often when
the construction is performed by a single system. Builder also has a
pattern of SomeThing a= new
Builder().with(Options.B).add(x).add(y).addAll(Z).makeImmutable(); It's
a way to specify arguments after construction without allowing access to
a partially built object.

But you do not use that feature of chaining in your sample code. To me
that's a plain factory. If you had taken advantage of Builder you would
have had an interface like this, I believe:

interface MyThing {
...
}

public interface MyThingBuilder {
MyThingBuilder addArg1(int arg1);
MyThingBuilder addArg2(int arg1);
MyThing finish();
}

The consistency checking ("Do we have all the arguments?") is put into
the MyThingBuilder implementation and the client can rely on the
returned MyThing to be complete so not all methods of MyThing have to
check state (a concern that has been voiced).

It's a bit like Command pattern applied to object construction: the
command object's configuration methods (addArg1 and addArg2 above)
replace constructor arguments and the construction is eventually done by
a no argument method.

Kind regards

robert
 

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

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,736
Latest member
zacharyharris

Latest Threads

Top