Class Construction Techniques
I'd like to get some feedback on what people think of the following class construction techn开发者_如何学JAVAiques. If I'm in a situation where I have the choice of using either of the following:
- Initialise an object completely in the constructor,
- Initialise an object by way of it's public properties after the instance has been created.
[removed blogspam]
Wherever possible (and appropriate), create object instances in a usable state. (so No. 1)
I agree with Mitch, but sometimes there's more to it.
A Factory approach can make your code cleaner, easier to use and maintain. In some ways they aren't much more than glorified constructors but they do give you extra flexibility.
- The factory methods can be given names that match their case of use.
- Callers only need to supply the parameters required. Admittedly you can also do this for 'normal' constructors but it's clearer to the caller why they should use a given constructor if it also has an appropriate name.
- Moving all complex code out of the constructors makes your code easier to maintain.
- Using a Full blown Factory (one that returns an abstract class / interface) gives you some abstraction from the concrete class itself.
Examples:
// Typlical constructor
public Page(pageId, title, url, keywords, content, tags, lastModified, lastModifiedBy)
{
// All values are set via the constructor.
//...
}
Factory methods:
public static Page PageByID(pageId)
{
// All properties are set internally here
//(directly or delegated as appropriate).
//...
}
public static Page NewPage(title, url)
{
// All properties not passed in are given
// appropriate default values.
//...
}
public static Page Page404()
{
// All properties are given
// appropriate default values.
//...
}
As Mitch said, normally you'd create an object through a constructor that would at least put it in a stable state. You can use public properties later to set non-critical properties of the object.
However, sometimes you don't really have a choice. A framework might require a default constructor (without parameters). In that case you'll need to get the object in a stable state in another way. Using public properties is possible, but it would be easy to forget something. In these cases I'd advise creating an Initialize (or similar) method that you call directly after the object has been created. This method can then require you to fill in all the needed parameters for a stable state so you can't forget anything. The difference is that you can't really force calling this method unless you keep internal 'isInitialized' state that you check in each public member.
Edit: ah just saw the post about the factory. Yes, of course, in case of a framework requiring default constructors you could also get a factory back and call the methods on that.
精彩评论