What are (if any)the implied assumptions or restrictions and the differences of designing like:
A) this:
class SampleClass1
{
IWorker workerA;
IWorker workerB;
void setWorkerA(IWorker w);
void setWorkerB(IWorker w);
WorkResult doWork();
}
B) versus this:
class SampleClass2
{
WorkResult doWork(IWorker workerA, IWorker workerB);
}
I know it depends on the specific project but what if the above class is a part of a small framework? The first Class is able to maintain state and separate the steps more naturaly but Second class ensures "real time communication" with the external caller more naturaly since Worker are passed each time doWork() is called.
Are there any recommended usages or generic practices that guide the choice between the two above ways? Thanks.
SampleClass1
SampleClass2
In option (A) you are creating what is known as a Function Object or Functor, this is a design pattern that is well documented.
The two main advantages are:
Also if you are using a dependency injection framework (Spring, Guice etc...) the functor can be automatically initialized and injected wherever required.
Function objects are extensively used in libraries e.g. the C++ Standard Template Library
Another option, a variant of case A, is the following:
class SampleClass3 { SampleClass3( IWorker workerA, IWorker workerB ); WorkResult doWork(); }
Advantages:
It's harder to make the object defective, since you are required to supply all the workers that are needed at construction time (in contrast to case A).
You can still carry state inside SampleClass3 and/or one of the workers. (This is impossible in case B.)
Disadvantages:
If more than one method depends on IWorker a and IWorker b, I say do sample A.
If only doWork() uses both IWorker a and IWorker b, then do sample B.
Also, what is the real purpose of your SampleClass? doWork looks a bit like a utility method mroe than anything else.
A) is a bad design because it allows the object to be defective (one or both of the worker classes might not have been set).
B) can be good. Make it static though if you do not depend on the internal state of SampleClass2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With