While modeling classes what is the preferred way of initializing it,
- Constructors
- Factory Methods
and what would be the considerations of using either of them.
In certain situations I prefer having a factory method which returns null if the object cannot be constructed. This makes the code neat. I can simply check if the returned value is not null or else take alternative action in contrast with throwing an exception from the constructor. (I personally don't like exceptions :( )
Edit:
Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database. In case a record with the specified id value does not exists the constructor throws a RecordNotFoundException. In this case I will have to enclose the construction of all such classes within a try..catch block.
In contrast to this I can have a static factory method on those classes which will return null if the record is not found.
Which approach is better in this case?
- Constructor
- Factory Method