Design patterns are solutions to software design problems you find again and again in real-world application development. Patterns are about reusable designs and interactions of objects. Some of them are very popular, like singleton, factory, and strategy; others are not widely used, like the flyweight pattern.
Sometimes patterns are not well implemented by developers, which can generate design issues and reduce the benefits of using them. It’s interesting to detect where they are not well implemented and correct their implementation.
To detect these kinds of issues, we need as much information as possible about the source code, including:
- Attributes of classes, methods, and fields.
- The inheritance between classes.
- Dependencies between classes, methods, and fields.
- Where classes are instantiated.
generates a code model that contains all this data and lets you query it using CQLinq. Let’s try to detect the misuse of two patterns: Singleton and Strategy.
Singleton
The singleton pattern is a design pattern that restricts the instantiation of a class to one object. However, using this pattern has become controversial, and not all architects and designers recommend it; here’s an article about the singleton controversy.
A common mistake when implementing the singleton pattern is not making the constructor private.
The following query detects all classes with the same traits as a singleton — i.e. classes containing one static field referencing themselves and a static method returning this field — but without a private constructor.

Strategy
There are common situations where classes differ only in their behavior. In this case, it is a good idea to isolate the algorithms in separate classes, so you can select different algorithms at runtime. The strategy pattern is a good candidate for such needs.
Here’s the UML diagram of this pattern:

As the diagram shows, the context class uses the abstract class “Strategy” and has no knowledge of the concrete implementations. However, in some implementations the concrete classes are used directly by the context class. Here’s a sample of this mistake:

Let’s search with CQLinq for all classes using this strategy pattern. For this purpose, we can search for abstract classes having multiple derived classes where the client directly uses the methods of the concrete implementations instead of the abstract ones.

The result of this query gives us the derived types used directly by other methods instead of the abstract ones. You just have to search for the methods using them to know where to correct the strategy pattern implementation.
However, it won’t give us the exact places where the strategy pattern is not well implemented, but rather potential places where the problem could exist; the developer will then manually check whether it’s an issue or not.
Conclusion
Design patterns improve design quality. However, if they are not well implemented, they can become a source of many issues and bugs.
