When modelling classes, what is the preferred way of initializing:
- Constructors, or
- Factory Methods
And what would be the considerations for 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 before taking alternative action, in contrast with throwing an exception from the constructor. (I personally don’t like exceptions)
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 the case where a record with the specified id does not exist, 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 or factory method?