Open-Closed principle antipatern.
I really adore MSDN, the quality of articles are top notch. However, following article full of violation of Open-Closed principle (SOLID).
I can understand that come up with some examples of switch-case violating Open-Close is not a piece of cake, but you can do better to avoid antipatterns.
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: d1f2a2fe-8279-e6b3-93e8-33398167655f
- Version Independent ID: 35191215-988f-3700-1f85-4751711f692e
- Content: Pattern Matching - C# Guide
- Content Source: docs/csharp/pattern-matching.md
- Product: dotnet-csharp
- GitHub Login: @BillWagner
- Microsoft Alias: wiwagn
I believe the whole point of pattern matching is that it inverts what is open and what is closed, compared with virtual methods:
- With
virtualmethods, the set of types is open, but the set of operations performed on those types is closed. - With pattern matching, the set of types is closed, but the set of operations performed on them is open.
Because of this, pattern matching will almost always violate the object-oriented open-closed principle, but that doesn't mean it's bad code. It's just code written with different goals in mind. And trying to force this principle here is probably not going to result in better code.
Because of that, I don't think the code in the article should be changed to conform to the object-oriented open-closed principle.
@Igor-Pchelko The analysis provided by @svick is correct. This style of code does invert what is open and what is closed.
I'm closing this as by design.
IMO Igor was right, it's a bad design. There are much better examples of switch and is then one that should not be done this way. Either virtual methods or an IShape interface would have been better for the compute area. The problem isn't that pattern matching is always bad it's that you chose a bad example. (the last example is not so bad...) Code like these examples are the kind of thing that people copy and get in the habit of using as a pattern for solving problems and the result is an unmaintainable mess and the overall degradation of quality in the apps built on .Net.