Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I don't really think the problem is setter vs. constructor injection. The problem is you're using <code>null</code> to mean too many things...</p> <p>As for : <code>/* A null value should create a unique meaningful default */</code></p> <p>Using it as a "magic" value in the <code>setId()</code> method is also something that really seems like a bad code smell. If you never call <code>setId()</code> then <code>getId()</code> returns <code>null</code>, but if you call <code>setId(null)</code> then <code>getId()</code> returns some generated value?</p> <p>Something like this would seem to make more sense:</p> <pre><code>public abstract class MyIdentityBaseClass implements IMyIdentityInterface { private String _id; private IMyIdentityInterface _parent; public MyIdentityBaseClass () {} @Override public String getId() { return _id; } @Override public void setId(String id) { _id = id; } @Override public IMyIdentityInterface getParent() { return _parent; } @Override public void setParent(IMyIdentityInterface parent) { _parent = parent; if (_id == null) { // if id isn't already set, set it to the generated id. _id = Helpers.makeIdFromParent(parent, getClass()); } } } </code></pre> <p>If your model really requires a parent feel free to use constructor injection, that's what it's there for. But realize you're still going to have to provide a default constructor for top level items... and then what's to stop someone from using the default constructor for an item that's not top level and then call <code>setParent()</code> on it later. I'd look at creating some kind of Container/Component architecture and make a special class (or classes) for the top level items. (You may have this already, as you've only given one example class and an abstract one at that.)</p> <p>BTW - Also, the IInterface and _name conventions aren't Java naming conventions. If this is an exposed API that other people are supposed to use expect some complaining.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload