SaaS CMS has officially launched! Learn more now.

Aniket
Feb 26, 2023
  905
(0 votes)

The beauty of Decorator pattern in Optimizely

Decorator pattern is one of my favorite design pattern for backend code development.

From wikipedia:

A decorator pattern is a design pattern that allows a behavior to be added to an individual object dynamically, without affecting the behavior of other objects from the same classes.

Advantages

  • Helps you extend the behaviour of the classes/services without modifying the behavior.
  • Helps enforcing single responsibility principle (one class one responsibility) and Open/Closed principle (classes can be extended but not modified). 
  • More efficient than subclassing because the objects behavior can be augmented without definining an entierly new object.
  • Mainly used for caching keep the layer separate (including the keys can be made unique per functionality)
  • Additional scenarios - logging, alerting, processing etc.

Implementation:

A simple example is an alert needs to be sent every time an order is submitted or there's an unhandled exception in the order service after a user submits the order. It might be tempting to add an 'Alert Sender Email' dependency directly to the main order service class. However, if we need to stick to SRP and O/C SOLID principles, order service should only perform 1 job (submit the order). 

In that case, one way to extend the behavior of the order service class is to create a new class that inherits from the same interface (IOrderSubmitService) that sends the email. This means you don't need to add a new interface (unlike sub-classing) which makes the interfaces slim and helps the interface segregation principle indirectly. 

Sample code:

namespace RF.Website.CMS.Features.CartCheckout.OrderSubmit.Alerting
{
    using System;
    using System.Threading.Tasks;
    using RF.Website.CMS.Features.CartCheckout.OrderSubmit.Services;
    using RF.Website.CMS.Features.CartCheckout.OrderSubmit.ViewModels;
    using RF.Website.Common.Features.Foundation.Alerts.Services;

    public class AlertingOrderSubmitService : IOrderSubmitService
    {
        private readonly IOrderSubmitService _implementation;
        private readonly IAlertSender _alertSender;

        public AlertingOrderSubmitService(
            IOrderSubmitService orderSubmitService,
            IAlertSender alertSender)
        {
            _implementation = orderSubmitService ?? throw new ArgumentNullException(nameof(orderSubmitService));
            _alertSender = alertSender ?? throw new ArgumentNullException(nameof(alertSender));
        }

        public async Task<OrderSubmitViewModel> SubmitOrderAsync(string associateName, int cartVersion, string kountSessionId)
        {
            try
            {
                return await _implementation.SubmitOrderAsync(associateName, cartVersion, kountSessionId);
                // Potential to add code to send email after every successful submission. 
            }
            catch (Exception exception)
            {
                string subject = "SubmitOrderAsync Error";
                string body = "An error occurred while calling SubmitOrderAsync.";
                await _alertSender.SendAlertAsync(subject, body, exception);
                throw;
            }
        }
    }
}

The statement in the try block is the one that calls the implementation of the submit order

The IOrderSubmitService:

namespace ClientName.CartCheckout.OrderSubmit.Services
{
    using System.Threading.Tasks;
    using ClientName.CartCheckout.OrderSubmit.ViewModels;

    public interface IOrderSubmitService
    {
        Task<OrderSubmitViewModel> SubmitOrderAsync();
    }
}

Next you will need to ensure the above code wraps the main code by using a decorator pattern. Luckily, it comes as a part of the Structure map and can be easily incorporate this in your code.

public void ConfigureContainer(ServiceConfigurationContext context)
{
 context.StructureMap().Configure(container =>
{
   container.For<IOrderSubmitService>().Use<DefaultOrderSubmitService>();
  // Can be used for logging or extending other behaviors of the Submit Order service
  // container.For<IOrderSubmitService>().DecorateAllWith<LoggingOrderSubmitService>();
   container.For<IOrderSubmitService>().DecorateAllWith<AlertingOrderSubmitService>();
}

}

That's it. Add a breakpoint in the AlertingOrderSubmitService to see it in action. Every time it will hit the wrapper/decorator class and then into your concrete implementation of the functionality.

Happy coding!

Feb 26, 2023

Comments

Please login to comment.
Latest blogs
Optimizely SaaS CMS Concepts and Terminologies

Whether you're a new user of Optimizely CMS or a veteran who have been through the evolution of it, the SaaS CMS is bringing some new concepts and...

Patrick Lam | Jul 15, 2024

How to have a link plugin with extra link id attribute in TinyMce

Introduce Optimizely CMS Editing is using TinyMce for editing rich-text content. We need to use this control a lot in CMS site for kind of WYSWYG...

Binh Nguyen Thi | Jul 13, 2024

Create your first demo site with Optimizely SaaS/Visual Builder

Hello everyone, We are very excited about the launch of our SaaS CMS and the new Visual Builder that comes with it. Since it is the first time you'...

Patrick Lam | Jul 11, 2024

Integrate a CMP workflow step with CMS

As you might know Optimizely has an integration where you can create and edit pages in the CMS directly from the CMP. One of the benefits of this i...

Marcus Hoffmann | Jul 10, 2024

GetNextSegment with empty Remaining causing fuzzes

Optimizely CMS offers you to create partial routers. This concept allows you display content differently depending on the routed content in the URL...

David Drouin-Prince | Jul 8, 2024 | Syndicated blog

Product Listing Page - using Graph

Optimizely Graph makes it possible to query your data in an advanced way, by using GraphQL. Querying data, using facets and search phrases, is very...

Jonas Bergqvist | Jul 5, 2024