Re: Interface with implied Constructor
On 10.07.2013 00:46, Richard Maher wrote:
On 7/9/2013 7:08 PM, Robert Klemme wrote:
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?"
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
--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/