Roedy said:
Indeed that seems to be what it is, but that doesn't help answer the
question about whether it's a good idea. Here's an attempt to answer
that question.
1. Simple static factory methods
If a static method returns a single instance of Employee representing
its parameters, then there is a trade-off between that static factory
method and a constructor. The constructor is, obviously, much clearer
about what it's doing, but suffers from the limitation that it has to
return a new object. Depending on performance concerns and design
considerations, this may or may not be acceptable.
For example, if you treat Employee as a value object (i.e., it's
immutable, and overrides equals() and hashCode() to specify that it's
equal to any other object with the same state), then returning a new
instance isn't a problem for program correctness -- although performance
may still be a concern. But if you treat Employee as an entity object
(meaning that it's mutable and fails to override equals() and hashCode()
methods), then uniqueness of instances -- at least within a transaction
-- is probably critical for the program to work correctly, and a
constructor is just not possible.
2. Other methods
Something other than a static factory method has to live somewhere, so
for example the "getEmployees" method mentioned earlier would need to
either be static or live in a separate class.
The typical way to solve this is to introduce what I often call a
"universe class". That is, a class of which there's only intended to be
one instance within a single context (i.e., transaction or session),
which represents the entire scope of the system. The word universe is
used in the set theory sense: basically you ask "what's the universe
from which this application finds employees?" That is, it probably
doesn't deal with all employees of all companies in the whole world. It
might deal with employees of your company (in which case the universe
class may be called Company), or in your department (in which case the
universe class may be called Department). The static method on the
Employee class may then become an instance method on the universe class.
The choice between static methods and a universe class is clarity and
flexibility versus complexity. Clearly, introducing the new class adds
a bit to the complexity of the solution. For one, you need a way to get
an instance of the universe class... outside of a transactional
environment, it may just be a singleton; but in a transactional
environment, things get a little more interesting. On the other hand,
you have a natural place for a good bit of functionality that deals with
the whole collection of employees, and you get the flexibility of
maintaining per-transaction state for the containing entity, and perhaps
even expanding the scope of the application in the future.
--
www.designacourse.com
The Easiest Way to Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation