Docsity

Decorator Pattern: A Comprehensive Guide with Examples, Summaries of Software Engineering

Partial preview of the text

Download Decorator Pattern: A Comprehensive Guide with Examples and more Summaries Software Engineering in PDF only on Docsity!

CNG/SNG 353 Software Design Patterns 2024-5 Fall

Week 5

IS INHERITANCE EXTINCT? A CLOSER LOOK AT THE DECORATOR

PATTERN

Exploding Class Hierarchy

To the Rescue Comes the Decorator Pattern

Decorators Queue

Testability

Other Advantages

Drawbacks

Decorator Pattern Has Native Support

Abstract Decorator

When Should We Use Inheritance?

1. IS INHERITANCE EXTINCT? A CLOSER LOOK AT THE

DECORATOR PATTERN

  • A decorator, unlike inheritance, may function on any implementation of a

given interface, eliminating the need to subclass a whole class hierarchy.

Furthermore, using the decorator approach results in clean, testable code.

  • Unfortunately, many of today’s software engineers are unfamiliar with the

decorator pattern. This is due in part to a lack of knowledge, but it is also

related to the fact that programming languages have not kept up with the

advancement of object-oriented design principles in a manner that

encourages developers to understand and utilize those patterns.

  • In this part, we will examine the advantages of utilizing the decorator pattern

over inheritance and argue that it should be supported natively in object-

oriented programming languages. In fact, we believe that the decorator

pattern should be used more frequently than inheritance in clean and tested

programs.

Exploding Class Hierarchy

When the number of classes required to add additional functionality to a given class hierarchy rises exponentially, the class hierarchy explodes. Consider the following interface as an example: public interface IEmailService { void send(Email email); Collection listsEmail(int indexBegin, int indexEnd); Email downloadEmail(EmailInfo emailInfo); }

If an email server request fails, the default implementation of EmailService

raises an exception. We’d want to improve the EmailService implementation

such that unsuccessful queries are retried a few times before failing. We’d also

want to specify whether or not the implementation is thread-safe.

We can add optional retries and thread-safety capabilities to the EmailService

class itself. The class’s constructor would take arguments that activate or

disable each functionality. This method, however, violates both the Single

Responsibility Principle (since the EmailService would have additional jobs)

and the Open-Closed Principle (because the class itself would have to be

modified for extension). Furthermore, the EmailService class may be included

in a third-party package that we are unable to modify.

Exploding Class Hierarchy

Structure of class. It should be noted that the ThreadSafeEmailServiceWithRetries might also derive from EmailServiceWithRetries or ThreadSafeEmailService (or both if multiple inheritance is supported). The number of classes, though, and the consequent functionality, would be comparable. In addition to retries and thread safety, we’d like to add logging to our email service API as an option. We utilize inheritance once more to increase the class hierarchy, which becomes as follows:

Exploding Class Hierarchy

Extended structure of class. It is worth mentioning that the number of extra classes required for adding logging functionality is equal to the entire number of classes in the current hierarchy. To the Rescue Comes the Decorator Pattern

  • Instead of inheritance, the decorator approach enhances object capabilities through composition.
  • It solves the problem of ballooning class hierarchy by requiring only one decorator for each new feature. As an example, let’s make a decorator for the retries functionality. A basic for loop with three retries is employed for simplicity. The EmailServiceRetryDecorator looks like this:

Decorators Queue

At first look, it may appear that the decorator pattern can only add one functionality to a particular implementation. The options are unlimited, though, because decorators may be piled on top of one another. For example, we can develop a dynamic equivalent to the EmailServiceWithRetriesAndCaching that we established through inheritance as follows: IEmailService emailServiceWithRetriesAndCaching = new EmailServiceCacheDecorator( Furthermore, by rearranging decorators or utilizing the same decorator at various levels, we may design novel implementations that would be impossible to develop using inheritance. For example, we may log before and after retries as follows: IEmailService emailService = new EmailServiceLoggingDecorat or(new EmailServiceRetryDecorator( The status of the request before and after retries will be noted with this combination. This enables verbose logging, which may be utilized for troubleshooting or creating complex dashboards.

Testability

Another significant advantage of the decorator over inheritance is testability. Consider building a unit test for the retries functionality as an example. Because there is no means for replacing a parent class with a stub, we cannot test EmailServiceWithRetries in isolation from its parent class (EmailService) (also known as mocking). Furthermore, since EmailService makes network connections to a backend server, unit testing all of its subclasses becomes tough (because network calls are often slow and unreliable). In such instances, integration tests are often used instead of unit tests. However, since the EmailServiceRetryDecorator constructor requires a reference to IEmailService, the decorated object may be simply substituted with a stub implementation (i.e., mock). This allows you to test the retry functionality in isolation, which inheritance does not allow. As an example, consider writing a unit test that confirms that at least one retry is completed. In contrast to an integration test, which would rely on the development of EmailService and remote service calls, this test is simple, rapid, and consistent. // Create mock that fails first time and then succeed IEmailService mock = mock(IEmailService.class ); when(mock.downloadEmail( emailInfo))

. thenThrow(new EmailServiceTransientErr or()) . thenReturn(email); EmailServiceRetryDecorat or decorator = new EmailServiceRetryDeco

Testability

Drawbacks (Continue) Consider the following IProcess interface and develop a decorator for it to demonstrate the difficulty of forwarding methods. If the process fails to start, the default implementation of the start method throws a FailedToStartProcessException. We’d want to modify the default implementation such that launching the process is attempted three times before failing. The decorator pattern would use in the following implementation:

Testability

Drawbacks (Continue) It’s worth noting that this approach has a lot of boilerplate code. In fact, the only significant element of the code is the implementation of the start method. Such boilerplate might be viewed as a productivity and maintenance burden for interfaces with multiple methods. Another disadvantage of the decorator pattern is its low popularity, particularly among junior developers. In reality, being less popular frequently implies more difficulty to grasp, which might result in a longer development period. Decorator Pattern Has Native Support Both of the disadvantages highlighted in the preceding section may be solved if the decorator pattern has native support in object-oriented programming languages (similar to what is provided today for inheritance). Indeed, with such native support, forwarding methods would be unnecessary, and the decorator pattern would be simpler to implement. Furthermore, native support for the decorator pattern would undoubtedly expand its popularity and use. The addition of native support for the Observer pattern in C# is a nice illustration of how computer languages may influence the adoption of design patterns (also known as events). To transmit events across loosely connected classes, today’s C# developers (including junior ones) readily employ the Observer design. Many developers would build direct dependencies between classes to transmit events if events did not exist in C#, resulting in code that is less reusable and more difficult to verify. Likewise, native support for the decorator pattern would encourage developers to design decorators rather than modifying existing classes or erroneously using inheritance, leading to higher code quality.

Abstract Decorator If, like us, we frequently utilize the decorator pattern and end up with several decorators for each interface, there is a way we can use to reduce the boilerplate of forwarding procedures (in the meantime until native support for the decorator pattern becomes available). The solution is to create an abstract decorator that implements all methods as forwarding methods and derive (inherit) all decorators from it. Only decorated methods will need to reimplement since forwarding methods are inherited from the abstract decorator. This solution makes use of the native inheritance capabilities to implement the decorator pattern. The code below exemplifies this method.

Abstract Decorator (Continue) One disadvantage of this technique is that decorators cannot inherit from other classes (for languages that do not enable multiple inheritance).

References

  • bin Uzayr, S. (2022). Software Design Patterns: The Ultimate Guide (1st ed.). CRC Press. https://doi.org/10.1201/
  • Ağca, M. A., et.al. (2022). A survey on trusted distributed artificial intelligence. IEEE Access, 10, 55308-55337. https://ieeexplore.ieee.org/abstract/document/
  • AĞCA, M. A. (2019, December). A holistic abstraction to ensure trusted scaling and memory speed trusted analytics. In 2019 International Conference on Computational Science and Computational Intelligence (CSCI) (pp. 1428-1434). IEEE. https://ieeexplore.ieee.org/abstract/document/