Interface with implied Constructor

J

Joerg Meier

[...]
While I have admittedly not followed the whole thread too closely, how
about this ?

public interface Bla {
public void setBlurg(int newBlurg);

public int getBlurg();

public Bla getInstance(int param, float difParam, Socket sockParam);
}

No more need for Reflection to search for something. On the implementation
level, getInstance can still decide to discard unneccessary parameters.
Since you already need an instance of a class implementing
Bla before you can call getInstance() on it, what's the point?
Perhaps you meant the interface to be BlaFactory (with getInstance()
still returning Bla)?
BlaFactory factory = BlaFactoryProvider.defaultFactory();
factory.setBlurg(86);
Bla instance = factory.getInstance(42, 42.0, null);

You are right, of course. That's what I get for thinking I found a better
solution based on skimming a topic ;) I simply didn't think it through.

Liebe Gruesse,
Joerg
 
R

Robert Klemme

On Sat, 20 Jul 2013 19:46:16 +0200, Robert Klemme wrote:

On 19.07.2013 23:21, Martin Gregorie wrote:
[...]
I take the opposite approach to Robert over that for one reason: that
the only way to report init errors in a constructor is to throw an
Exception,
which means the instance declaration often needs to go inside a
try/catch block which can screw up scoping.

In what ways does this screw up scoping?

Just that I often find that I need access to the instance outside the
try/
catch block containing the constructor call and I don't much like
initialising the pointer as null.

Then ... don't initialize it.

Thing thing;
try {
thing = new Thing();
} catch (DooWopDooWopDooWopException ex) {
logger.log(Level.SEVERE, "Eek!", ex);
throw ex;
}
System.out.println(thing.getSwing());
...

This form has the advantage that the compiler will complain if the
all-important `throw ex;' is forgotten, whereas initializing to null
would just get you an NPE.

Very occasionally there's a situation where you really do need
to use the null-ness of `thing' as an indication that construction
failed. In that case, I'd still suggest not initializing:

Thing thing;
try {
thing = new Thing();
} catch (DooWopDooWopDooWopException ex) {
logger.log(Level.SEVERE, "Eek!", ex);
thing = null;
}
if (thing != null) {
System.out.println(thing.getSwing());
else {
System.out.println("It don't mean a thing");
}

IMHO, situations like this are suggestive of a poorly-designed Thing
class (which you may be forced to endure), or of a method that's trying
to do too many things and might better be split up.
This is a result of my dislike of using Exceptions to signal anything
except a fatal error and may well be a hangover from writing a lot of C
in the past. A method that returns reference to a library class whose
constructor can throw an exception, e.g. Integer, but does not itself
return an exception requires this sort of structure:

No, this is not _required_. It can be done differently. Just one way:

public int getHeight(String height) {
try {
final Integer h = new Integer(height);

if (h < 0) {
error = "Below MSL";
return -1;
}

error = null;
return alt = h;
}
catch (NumberFormatException e) {
error = e.getMessage();
return -1;
}
}

I think there are various aspects about this example class that are
worth discussing other than the scoping topic. But I don't want to go
there as we are currently discussing scope.

I believe the scoping is not screwed up by the constructor throwing an
exception but rather by your choice of how you access "h" in that example.
You're right, of course. But, please bear in mind that I concocted this
example at Robert's request to illustrate the sort of scoping situation
where I prefer to use a constructor that never throws an Exception plus
an init() method that can throw one rather than a constructor that does
it all but needs to throw an Exception if a recoverable error occurs in
the constructor.

If you concede that Eric is right here then you are basically saying you
provided the wrong example. The problem with these examples is that
they do not convey the point you are trying to make. So what do you
*really* want to say?

Cheers

robert
 
A

Arved Sandstrom

On 07/20/2013 04:12 PM, Martin Gregorie wrote:
[ SNIP ]
This is a result of my dislike of using Exceptions to signal anything
except a fatal error and may well be a hangover from writing a lot of C
in the past.

You probably know this, in fact I'm sure you do, but in OOP exceptions
are like 95% of the time used for everything but fatal errors. Well,
maybe 98 or 99 percent of the time.

A method that returns reference to a library class whose
constructor can throw an exception, e.g. Integer, but does not itself
return an exception requires this sort of structure:
[ SNIP ]

To the larger question, which I snipped, I'd still have the constructor
throw exceptions. It's just a method, and in this case a failure to
build is significant - it rates an exception. I don't know why it would
screw up scoping: I'd typically have the happy path inside the "try". If
you make your "try" blocks too small then you're defeating the purpose
and introducing unnecessary "is this thing null" checks.

AHS
 
M

markspace

To the larger question, which I snipped, I'd still have the constructor
throw exceptions. It's just a method, and in this case a failure to
build is significant - it rates an exception. I don't know why it would
screw up scoping: I'd typically have the happy path inside the "try". If
you make your "try" blocks too small then you're defeating the purpose
and introducing unnecessary "is this thing null" checks.

I wonder if the syntax is an issue here. Part of the reason lambdas are
being developed is to correct a "horizontal problem and vertical
problem" in Java code. That is, it takes a fair number of lines of
source code to create a fairly simple anonymous class, and that's seen
as a problem by a lot of people.

Perhaps something that removes some of the "vertical problem" in try
catch statements would be useful. Transforming this:

public Object someMethod( Object... params ) {
try ( stuff... )
{
more stuff...
}
catch( stuff ) {
}
}

Into something like this:

public Object someMethod( Object... params ) {

stuff...
more stuff...

return;
catch( stuff ) {
}
}

Might remove some of the visual clutter in using try catch statements.
Obviously this only works for top-level try-catch statements, but I
think keeping things simple is the best idea.


Moving to a different idea, I also wonder if it's possible to define a
lighter weight exception method that's more suited to "a quick
check/non-return value" than building a full exception, which I believe
can be very heavy weight (like, an order of magnitude more expensive to
return an exception rather than a simple value).

So maybe something like this

public void : int checkedMethod( Object... params ) {
...
}

Where the "void:" syntax is taken to mean "nothing, or" some return
value. The idea here is that the compiler should insert the test for
"void" (nothing, the error value) so the programmer doesn't have to
remember to test a flag or some special return code. This provides the
light weight advantages of a return code with out the fragility of a
programmer having to remember to test the return code.

I'm not sure exactly how to implement this, though. Some thoughts:

1. If the programmer doesn't test the return value, then an Error is
thrown. This builds a stack frame, because you want to know who isn't
testing for return values.

2. A special if test is allowed to test for invalid return values. This
provides fine grained testing.

3. A special catch pattern is allowed to test for "void:" return values.
This provides for coarser grained recovery when you want all
statements with a void: return value to do the same thing.

Alternately #1 could be a compile error instead of a runtime check.
Actually, this might be the better idea.


#2 Example

int i;
if( void : i = checkedMethod() ) {
// "void:" return code, error processing here...
} else {
// i was assigned a value here
}

#3 Example

try {
int i = checkedMethod();

// lots o' statements...

} catch( void ) {
// error processing here
}



....Just random thoughts by Y.T.
 
A

Arved Sandstrom

Of course. A factory instance can also be an initialized object.

I would hope that it would usually be. But since Socket got mentioned,
we see that that is not always the case.

But I have no aversion to factory methods.
In situations like Richard's (at least as I understand it) the
environment knows what information it has available and the interface
for the factory can be defined in such a way to pass data potentially
needed or the data that the environment is willing to provide. The
factory implementation then can decide which part of that information is
needed to create the instance and ignore the rest. It's surely better
to let the implementor of the construction process decide which
information to use than the implementor of the environment (or call it
"framework").

You know, I'd call that a 50/50, I think sometimes the caller is the
best judge, and sometimes the callee is.
What "specific situations" do you have in mind? As far as I can see the
name of the class to create is configured and Richard said reflection
will be used in his initial posting. I think that is a typical
situation where a factory class can be configured which is created via a
no arg constructor and which has a method createFoo(...) with
appropriate arguments. Then there is no need to fiddle with reflection
to analyze constructors and argument lists. Also, this gives more
flexibility as the factory can decide which class to instantiate at
runtime if need be.

Specific situation? The very essence of a factory method - you need to
create an object that can do such-and-such, but you don't (for one
reason or another), or can't, specify the exact class of the object to
be created.

By definition, if you *do* know exactly what you want to create, and
have appropriate constructors to do it with, why resort to a factory method?
My main point is that I dislike using reflection to _find_ an
appropriate method - be it a constructor or another method. I prefer
that method to be identified in an interface - whether that is an init()
method in the interface of the object I will eventually be using or a
create() method in another interface defining the factory API I care
less. I think Class.forName() and newInstance() is enough reflection to
get flexibility and decoupling but from there on I prefer to use methods
specified via an interface or abstract base class.

Kind regards

robert
I'd differentiate between the use of reflection to find a method
(including ctors) and the more general discussion we strayed into, which
is simply when do you use ctors or factory methods or whatever.

In the last 5 years I think I've extensively used reflection in Java
_twice_. In one case, as I mentioned previously in this thread, it was
for construction of non-JPA entity result objects for native queries; I
adapted a third party class to modify and adapt how it searched for
constructors, but otherwise it was a reasonable use...compared to the
alternative.

In the other case I had to write a "command server" because of the
erstwhile fork+exec problem on Solaris, where RAM would get hammered.
This server basically took on the job of executing system programs
through Runtime and Process, running in a much smaller heap than the
calling apps. Because of it's very nature, it had to load or unload
command classes at runtime, and these classes did have to be written to
an interface. No need for specifying how they constructed themselves though.

AHS
 
E

Eric Sosman

On 07/20/2013 04:12 PM, Martin Gregorie wrote:
[ SNIP ]
This is a result of my dislike of using Exceptions to signal anything
except a fatal error and may well be a hangover from writing a lot of C
in the past.

You probably know this, in fact I'm sure you do, but in OOP exceptions
are like 95% of the time used for everything but fatal errors. Well,
maybe 98 or 99 percent of the time.

(Eighty-seven point three percent of cited statistics are
plucked out of thin air. ;-)

One problem is that "fatal" is ill-defined. Is an NPE
"fatal?" Quite often it is, but sometimes the application
is prepared to cope with it -- For example, think of some
code throwing NPE while being managed by an IDE's debugger,
of think of a servlet throwing NPE without taking down the
entire Web container.

Somewhere toward the other end of the spectrum, is a
NumberFormatException "benign?" Maybe, if the application
can protest and prompt for another number. Or maybe not,
if the string came from a configuration file and there's
nobody to respond to a prompt.

The "seriousness" of an exception is not a function of
the exception itself, but of the code that catches (or fails
to catch) it.
 
A

Arved Sandstrom

On 07/20/2013 04:12 PM, Martin Gregorie wrote:
[ SNIP ]
This is a result of my dislike of using Exceptions to signal anything
except a fatal error and may well be a hangover from writing a lot of C
in the past.

You probably know this, in fact I'm sure you do, but in OOP exceptions
are like 95% of the time used for everything but fatal errors. Well,
maybe 98 or 99 percent of the time.

(Eighty-seven point three percent of cited statistics are
plucked out of thin air. ;-)

One problem is that "fatal" is ill-defined. Is an NPE
"fatal?" Quite often it is, but sometimes the application
is prepared to cope with it -- For example, think of some
code throwing NPE while being managed by an IDE's debugger,
of think of a servlet throwing NPE without taking down the
entire Web container.

Somewhere toward the other end of the spectrum, is a
NumberFormatException "benign?" Maybe, if the application
can protest and prompt for another number. Or maybe not,
if the string came from a configuration file and there's
nobody to respond to a prompt.

The "seriousness" of an exception is not a function of
the exception itself, but of the code that catches (or fails
to catch) it.
No argument from me as to anything you said. An exception is just an
event that requires special processing, which as you say can range from
benign (NumberFormatException in a human-supplied input) through sorta
bad (NumberFormatException in a value read in from a .properties file,
but the program can use a default and log an error) [1], to something
demonstrably showstopping like not having DB access to the data that you
need to work with.

What it all boils down to is, I'd rather have a program that identifies
a serious problem, saves work, and requests to shut down, than one that
just breaks.

Having opined all that, I still consider a "fatal" problem to be one
that, even though the programmer has correctly coded for all
eventualities, is something that must terminate the program.

AHS

1. Adapting some of your examples.
 
G

Gene Wirchenko

On Thu, 18 Jul 2013 23:21:35 -0300, Arved Sandstrom

[snip]
I'll be honest, Robert, personally I consider the behaviour of an object
- the kinds of things you could specify in an interface - to be what the
*initialized* object can (should) do.

But there is more to it than that. There is also getting it
initialised. That should also be part of the API. I would not
enforce that it has to, but I sure would like the option to specify
constructor signatures in an interface.

Apart from other problems with constructors in interfaces (e.g. a class
implements 2 interfaces, both of which have constructors: which ctor do
you ignore and hence violate a contract?), what do you intend to mandate
by requiring a constructor with a given signature? That all implementing
classes create matching private fields that are exposed by accessors?
Why would you want to do that?

In that case, I would not have the constructor signature in the
interface.

What if I am not subclassing? Having the interface is then
documentation of the full API for the class.
Although it's usually an anti-pattern, I believe a better idea would be
to specify some important getters in an interface, if you need something
like this. Rather than wanting to control how an object initializes
itself and is implemented, typically what you're really after is to
require that an object can provide some synthetic state information.

Why? I do not need any getters. I just want a prototype of the
constructor with the rest of the prototypes.
The *body* of a method is implementation. Interface or no interface, the
method as called, the way it represents to callers, is behaviour.

I've seen people in threads make your argument. To call everything
behaviour is not helpful. A constructor builds an object. I don't
consider that behaviour.

What else could it be but behaviour? This definition for
behaviour is from dictionary.reference.com: "the action, reaction, or
functioning of a system, under normal or specified circumstances".
What is the behaviour of a constructor? It builds an object of type
_____. Redefining the word to suit your biases simply creates
confusion.
I don't consider a constructor a "call". Invoking a method on a properly
initialized method, yes; *building* the object, no.

It is called, implicitly, but called nonetheless. Once again,
you are trying to redefine a commonly-used term to your biases.

[snip]

Sincerely,

Gene Wirchenko
 
E

Eric Sosman

[...] I just want a prototype of the
constructor with the rest of the prototypes.

I don't think anyone's in doubt about what you and Richard
want. The question that still burns is:

"Why?"

Perhaps if you'd offer a concrete example...? To avoid charges
of made-up-ness, take an existing interface that you think would be
more useful if it could specify constructors, and exhibit the
constructors you'd like it to specify. Please use an interface
that's not some creature of your own; if the idea is useful, there
surely must be some java or javax interfaces that could use it.
(If there aren't, that casts some doubt on the utility of the
construct ...)

Then, maybe, we can get away from this childish "It's behavior!"
"No, it's implementation!" back-and-forth. A use case, please.
 
A

Arved Sandstrom

[...] I just want a prototype of the
constructor with the rest of the prototypes.

I don't think anyone's in doubt about what you and Richard
want. The question that still burns is:

"Why?"

Perhaps if you'd offer a concrete example...? To avoid charges
of made-up-ness, take an existing interface that you think would be
more useful if it could specify constructors, and exhibit the
constructors you'd like it to specify. Please use an interface
that's not some creature of your own; if the idea is useful, there
surely must be some java or javax interfaces that could use it.
(If there aren't, that casts some doubt on the utility of the
construct ...)

Then, maybe, we can get away from this childish "It's behavior!"
"No, it's implementation!" back-and-forth. A use case, please.
I agree with you in wanting to see an example that we can discuss.

Not so sure the "back-and-forth" is totally childish, although it's
close to being exhausted. I think it comes down to how one defines
object behaviour.

One prevalent definition is that object behaviour is defined by all the
methods that can be applied to it, so including accessors even. I would
not myself include constructors under this definition, even though they
resemble instance methods, because you only have a valid instance when
you leave the constructor.

And yet there are different types of object behaviour. I generally
distinguish between methods that could sensibly be in an interface, and
those that smack a bit too much of implementation. First category might be

translate2D(Double direction, Double distance)

and second might be

set2DPositionXY(Double x, Double y)

Granted, this is fuzzy, but I think there's some validity to the "would
this method ring true in an interface" test.

AHS
 
G

Gene Wirchenko

[...] I just want a prototype of the
constructor with the rest of the prototypes.

I don't think anyone's in doubt about what you and Richard
want. The question that still burns is:

"Why?"

An interface documents. I can put additional comments in there
and do because it helps the signatures make sense. Since I have all
this, why not have the constructors there, too? Then, I have the API
documented in one place.
Perhaps if you'd offer a concrete example...? To avoid charges

Read my pargraph above.
of made-up-ness, take an existing interface that you think would be
more useful if it could specify constructors, and exhibit the
constructors you'd like it to specify. Please use an interface
that's not some creature of your own; if the idea is useful, there
surely must be some java or javax interfaces that could use it.
(If there aren't, that casts some doubt on the utility of the
construct ...)

It would document the class in one place.

I have already done this. I added comments to my interfaces
stating what the constructor signatures were. I would like to have
Java enforce constructor signatures. Note that I am fine with this
being optional so you need not worry about it.
Then, maybe, we can get away from this childish "It's behavior!"
"No, it's implementation!" back-and-forth. A use case, please.

For me, it is such a general situation that a use case is gilding
the lily. If you were to ask me for a use case for using a for
statement, it would be about the same level.

Sincerely,

Gene Wirchenko
 
J

Jim Gibson

Gene Wirchenko said:
[...] I just want a prototype of the
constructor with the rest of the prototypes.

I don't think anyone's in doubt about what you and Richard
want. The question that still burns is:

"Why?"

An interface documents. I can put additional comments in there
and do because it helps the signatures make sense. Since I have all
this, why not have the constructors there, too? Then, I have the API
documented in one place.

An interface only documents (requires or specifies, actually) /part/ of
class behavior. There are usually other aspects of the class that must
be addressed by its constructors. Those aspects are outside the scope
of the interface.

Classes can implement more than one interface. What should the compiler
demand in the case of multiple, mutually-exclusive constructor
requirements?
 
E

Eric Sosman

[...] I just want a prototype of the
constructor with the rest of the prototypes.

I don't think anyone's in doubt about what you and Richard
want. The question that still burns is:

"Why?"

An interface documents. I can put additional comments in there
and do because it helps the signatures make sense. Since I have all
this, why not have the constructors there, too? Then, I have the API
documented in one place.

An interface documents -- and also specifies, mandates,
requires, and enforces.
Read my pargraph above.


It would document the class in one place.

Are you proposing to do away with the class' own JavaDoc?
Also, what happens to "in one place" when a class implements
more than one interface?
I have already done this. I added comments to my interfaces
stating what the constructor signatures were. I would like to have
Java enforce constructor signatures. Note that I am fine with this
being optional so you need not worry about it.


For me, it is such a general situation that a use case is gilding
the lily. If you were to ask me for a use case for using a for
statement, it would be about the same level.

That level being "beneath contempt," I guess?

In summary, we've still seen not even one use case. We've
seen assertions by you and by Richard that the capability would
be of great utility, yet nobody's offered even one example of
a "well-known" interface that could benefit from it. That, I
think, should raise a doubt or two.
 
G

Gene Wirchenko

[snip]
An interface only documents (requires or specifies, actually) /part/ of
class behavior. There are usually other aspects of the class that must
be addressed by its constructors. Those aspects are outside the scope
of the interface.

Of course. I think that constructor signatures should be
possible to be one of them.
Classes can implement more than one interface. What should the compiler
demand in the case of multiple, mutually-exclusive constructor
requirements?

If they are really mutually exclusive, then that is an error.

Sincerely,

Gene Wirchenko
 
G

Gene Wirchenko

On 7/22/2013 3:39 PM, Gene Wirchenko wrote:
[...] I just want a prototype of the
constructor with the rest of the prototypes.

I don't think anyone's in doubt about what you and Richard
want. The question that still burns is:

"Why?"

An interface documents. I can put additional comments in there
and do because it helps the signatures make sense. Since I have all
this, why not have the constructors there, too? Then, I have the API
documented in one place.

An interface documents -- and also specifies, mandates,
requires, and enforces.
Read my pargraph above.


It would document the class in one place.

Are you proposing to do away with the class' own JavaDoc?
Also, what happens to "in one place" when a class implements
more than one interface?

No, but it would be nice for the API.
That level being "beneath contempt," I guess?

Well, you keep clamouring for a use case. It has already been
given. Maybe you disagree with doing it that way, but it is what some
of us want.
In summary, we've still seen not even one use case. We've

I have kept giving the example of documenting all of the API.
seen assertions by you and by Richard that the capability would
be of great utility, yet nobody's offered even one example of
a "well-known" interface that could benefit from it. That, I

I do not care whether it would not be useful for a well-known
interface; I care whether it would be useful for me.
think, should raise a doubt or two.

Well, I have not claimed that everyone would want to use it. I
found it odd when I first encountered Java interfaces that
constructors were not included in what could be specified. I continue
to do so.

Sincerely,

Gene Wirchenko
 
A

Arved Sandstrom

[snip]
An interface only documents (requires or specifies, actually) /part/ of
class behavior. There are usually other aspects of the class that must
be addressed by its constructors. Those aspects are outside the scope
of the interface.

Of course. I think that constructor signatures should be
possible to be one of them.
Classes can implement more than one interface. What should the compiler
demand in the case of multiple, mutually-exclusive constructor
requirements?

If they are really mutually exclusive, then that is an error.

Sincerely,

Gene Wirchenko
Let's say that constructors are allowed in interfaces. There'd be no
problem in having multiple constructors in a single interface. The
requirement would be, as for other methods, that you define all of them
in an implementing class.

Any given interface would be satisfied if you constructed an object
using one of those declared constructors.

But now mix in interface #2, with its own constructor signatures. You
can't very well expect interface designers to be aware of all other
interfaces, for starters, so if any interface is allowed constructor
signatures, *all* of them ought to be.

And it seems reasonable to me that each interface can expect _one_ of
its constructors to be used.

I don't see this being practical. Constructors are about what an object
*is*, interfaces specify what an object *does*.

AHS
 
E

Eric Sosman

I suspect he meant "mutually disjoint", i.e. have no arguments in common,
which is a distinct possibility. To me that sounds like a good argument
for excluding constructors from interface definitions.

"Ayeh." It would be even more confusing, I think, if two
interfaces specified constructors with identical signatures but
different intent:

interface Flexible {
Flexible(double stiffness); // constructor spec.
... methods ...
}

interface Edible {
Edible(double caloriesPerGram); // constructor
... methods ...
}

class LicoriceStick implements Flexible, Edible {
// Constructor mandated by both interfaces:
LicoriceStick(double whatAttributeDoesThisGovern) {
In any case, you can always lock down the whole interface by declaring
an abstract class that implements the methods in the interface(s) as
abstract methods and declares concrete constructor(s).

That still doesn't mandate any particular form of constructor
for concrete subclasses. It does, however, require that each
subclass constructor have enough information available to use in
an invocation of one of the abstract class' constructors, so a
certain amount of influence is present.
 
R

Robert Klemme

Let's say that constructors are allowed in interfaces. There'd be no
problem in having multiple constructors in a single interface. The
requirement would be, as for other methods, that you define all of them
in an implementing class.

Since constructors are unnamed (or put it differently: you have no
choice) the likeliness of real conflicts seems higher to me than for
ordinary methods in interfaces. (A conflict I am talking about is for
example when two methods with identical argument list but different and
incompatible exceptions exist. Ordinary methods would also have to share
the name but the constructor declaration would probably use a specific
keyword.)

interface X {
construct (int x, int y) throws FooBarException;
}
I don't see this being practical.

+1

Kind regards

robert
 
S

Steven Simpson

I would like to have
Java enforce constructor signatures.

In following this thread, I'm finding this desire for interface
constructors totally bizarre. I wouldn't be surprised if I once
(briefly) wanted them, but now I immediately think 'factory interface',
concoct something, and find it totally satisfactory. If you want to be
able to create a Foo from an argument list, define an interface type to
express it:

interface FooFactory {
Foo createFoo(int x, int y);
}

It totally decouples construction from the functionality of a Foo. The
FooFactory implementation just acts as an adapter between the available
arguments and the configuration required by a particular Foo
implementation's constructors. Not all of the configuration needs to
come from the arguments; fill in missing parts with constants or get
them from the environment. Not all arguments need to be used. The
factory could choose different constructors depending on argument
values, or return cached/pooled objects if that's compatible with the
factory type's informal contract, or pass in some arguments via the
constructor and others via reconfiguration methods. Multiple FooFactory
implementations could use the same Foo implementation. Multiple factory
types could be used when there are multiple contexts (with varying
available arguments) that all, nevertheless, demand the creation of a Foo.

Coding to use a factory in the dynamic case (where a factory class's
name is given as a string) is simple:

Foo foo = Class.forName(clazzName)
.asSubclass(FooFactory.class)
.getConstructor()
.newInstance()
.createFoo(x, y);

This is type-safe and easy to refactor the argument list.

If you had a way to impose a constructor Foo(int x, int y) on all Foo
implementations, what would you write instead?

Foo foo = Class.forName(clazzName)
.asSubclass(Foo.class)
.getConstructor(new Class<?>[] { Integer.CLASS, Integer.CLASS })
.newInstance(new Object[] { x, y });

I think this is identical to what you'd write according to the OP's
preferred option, where you assume that the named class has a compatible
constructor. It still lacks the type safety and refactorability of the
factory code, and all you gain is the assurance that getConstructor
won't fail. But is that very valuable, when either approach could fail
at run time simply by naming a class that doesn't implement
Foo/FooFactory, or by naming a non-existent class?
 

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,772
Messages
2,569,593
Members
45,104
Latest member
LesliVqm09
Top