I’m working on some classes that get part of their configuration from global variables, e.g.
class MyClass { public void MyClass(Hashtable<String, String> params) { this.foo = GlobalClass.GLOBALVAR.get('foo'); this.bar = GlobalClass.GLOBALVAR.get('bar'); this.params = params; } }
This is bad for a couple of reasons, GLOBALVAR talks to a database to get some of the variables and this makes it really hard to make unit tests. The other problem is that I have many (dozens) of classes that inherit from MyClass, so I can’t easily change the constructor signature.
My current solution is to create an additional default constructor and setter methods for params, foo and bar.
class MyClass { // Other code still here for backwards compatibility. public void MyClass() { // Do nothing much. } public void setParams(Hashtable<String, String> params) { this.params = params; } public void setFoo(Foo foo) { this.foo = foo; } public void setBar(Bar bar) { this.bar = bar; } }
Any ideas on a good way to refactor this, besides the way I did it? My other thought would be to use a factory method, but I’m afraid I’ll run into polymorphic substitution problems.
I think I would start by doing the following. It let’s your existing code work without modification, and allows you to add new constructors to the subclasses as you can. Once all of the subclasses have the new constructor, and all of the calls to the old constructors are gone, you can get rid of the GlobalClass and the constructors that use it. You can also then, hopefully, work on cleaning up the GLOBALVAR (the Car class in my code).