There is an existing functionality with below pseudo code
class MyMessageSink implements MessageSink {
public void sendToFulfillment();
}
Now, I would like to add transaction & locking capability to the sendToFulfillment
method. I did this using wrapper pattern
class TransactionalMessageSink{
private MessageSink sink;
public TransactionalMessageSink(MessageSink sink){
this.sink = sink;
}
public void sendToFulfillment(){
//start transaction
sink.sendToFulfillment();
//end transaction
}
}
Similarly, I created a LockingMessageSink
and the client code became
new LockingMessageSink(new TransactionalMessageSink(new MyMessageSink())).sendToFulfillment
However, the transaction & locking code is very less, simple and straightforward (since we are using a framework which does most of the boilerplate work for us). So I though of another approach -
class MyMessageSink implements MessageSink {
public void lockAndSendToFulfillmentInTransaction(){
//locking start
sendToFulfillmentInTransaction();
//locking end
}
public void sendToFulfillmentInTransaction(){
//transaction start
sendToFulfillment();
//transaction end
}
public void sendToFulfillment();
}
The problem here is obvious, there is a tight coupling between the locking and transaction code but avoids creation of 2 additional classes for simple functionality.
I personally like the first approach, but still am not convinced that this is the best one.
My question - Is there a better way other than using Wrapper, i.e any efficient way to handle these in a single class without compromising on the design aspect.