> I'm personally not a fan of static methods but we seem to be using them to
load an object. For example if you have an Employee class rather then
instantiating an instance you call a static method 'GetEmployees' and it
returns a List of Employee objects.
I'm looking for what other people are doing and if you feel this is a good
or bad idea.
Hi,
IN A NUTSHELL
I know what you mean but the scenario your describe is pretty normal and ok.
That type of constructor is called a "static factory", in some circumstances
they are actually preferable. Sun use them quite a bit in Java itself.
Things like Xyz.getInstance(); Of course like everything else they need to
be used wisely.
MORE DETAILS
Pros of construction using static factory methods:
Generally you get more control and flexibility.
1. Regular constructors will create an object every time they are invoked
and only when they are invoked, but with a static factory you can have
pre-built objects. Sometimes this flexibility of *when* things are really
built is highly desirable.
2. Or you can defer real construction until the object is actually used
a.k.a lazy instantiation.
static private Blah blah;
static public Blah createBlah() {
if(blah==null)
blah= new Blah();
return blah;
}
This is good for "expensive" objects, they only get created if/when they
are used.
3. Can return any type.
eg return Collection of Whatever's
Your GetEmployees() is a good example.
4. static factory's can have meaningful names, this can be good
Whatever.createAllShoppingTrolleys()
Cons:
1. Poor naming conventions can make it hard to know that is going on
eg Whatever.getGizmo() could be a constructor but with that kind of name
you'd never know.
2. You cannot subclass (or extend) a class which only has static factory
constructors. You must use containment rather than inheritance.
Hope that helps?
Alex K