Analyzing Several Ways to Implement the Decorator Pattern in C#

The problem always has a solution. Even more than one.

Sasha Marfut
Geek Culture

--

Photo by Paul Esch-Laurent on Unsplash

Learning about multiple ways to accomplish the same task and comparing them, analyzing the pros and cons of each is an interesting exercise aimed at expanding the developer’s mindset.

The goal today is to explore multiple different ways to solve a common problem in software development — decorate an existing object with some cross-cutting behavior like measuring execution time, logging, throttling, caching etc.

Way 0: No Decorator Pattern

When there is a need to extend the behavior of an existing object, the decorator pattern or any other patterns or design principles are not needed at all. The easiest way to achieve the goal is to inject new logic directly into the object.

For example, there is CheckUserAccessQueryHandler object that checks if the user has access to anything by querying the database. We now receive the requirement to measure the exact time it takes for the query handler to execute, so we need to implement some benchmarking logic. This is how it might look:

--

--

Sasha Marfut
Geek Culture

1 million+ views on Medium | .NET, Design Patterns, Architecture, API