design-patternsaopaspectjaspects

Can I have my core logic to update object status in Aspect



I have a requirement where I will be performing a set of operation in a chain pattern ClassA->ClassB->ClassC by invoking common method action(). Ideally ClassA, ClassB and ClassC implements interface IClass having method action().

At the end of action() method, its status(failed/success) should be updated in the Database.
So my doubt is,
- Is it a good design to leverage Aspect's around advice for method "action" and update the status in Aspect class once the action got executed.
- Our since it is core logic to update the action status, it shouldn't be part of cross-cutting framework like aspect?


Solution

  • I don't think aspect is the right option to implement above behaviour. Aspect is a common code which is used across multiple classes / modules.

    Typical examples are transaction management, logging

    The better option could be to write one interface and implementation like below-

    public interface StatusUpdater{
        updateActionStatus();
    } 
    

    Have one class implement this interface.

    public class StatusUpdaterImpl implements StatusUpdater{
        updateActionStatus();
    }
    

    Have this class injected into Class A , B and C and delegate the db update to this class.

    This you will have flexibility in changing the Db update behaviour if required .

    Have one more class implanting StatusUpdater interface and inject into target