Visitor Design Pattern Is Giving Way To Pattern Matching Expressions!

  Рет қаралды 14,125

Zoran Horvat

Zoran Horvat

Күн бұрын

Become a patron and get access to source code and exclusive live streams: / visitor-design-81382001
The Visitor is one of the most beautiful design patterns for its unique capability to extend a hierarchy of classes by a method that none of the hierarchy members have. Still, with the progression of functional concepts in the C# language syntax, the Visitor is also progressing - to oblivion.
This video will teach you the working principle behind the Visitor design pattern and demonstrate a traditional approach to implementing and consuming it, like the one you might find in the Gang of Four book.
But, as we said, the C# language is changing. It is progressing towards supporting more functional designs, and one aspect of that change is the increasing support for pattern matching, including type-test-and-set patterns. By coincidence, that is the ground of the Visitor, too!
By the end of this video, you will learn how to implement Visitor-like mappings using novel C# syntax that includes type-matching patterns, switch expressions, and even the good-old extension methods.
You will even see the possibility of implementing impromptu visitors using lambdas, an approach well outside the scope of traditional Visitors based on classes.
Watch this video and learn why the Visitor design pattern mostly remains confined within library code today, while pattern-matching expressions tend to take the Visitor's place in business applications.
Thank you so much for watching! Please like, comment & share this video as it helps me a ton!! Don't forget to subscribe to my channel for more amazing videos and make sure to hit the bell icon to never miss any updates.🔥❤️
✅🔔 Subscribe ► / @zoran-horvat
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
⚡️Chapters:
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
⌚ 00:00 Intro
⌚ 00:48 Motivation for the Visitor pattern
⌚ 03:26 Implementing the Visitor
⌚ 08:38 Using type patterns to substitute a visitor
⌚ 13:31 Comparing the object-oriented and functional implementation
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
⭐ CONNECT WITH ME 📱👨
🌐Buy me a Coffee ► ko-fi.com/zoranhorvat
🗳 Pluralsight Courses ► codinghelmet.com/go/pluralsight
📸 Udemy Courses ► codinghelmet.com/go/udemy
📸 Join me on Twitter ► / zoranh75
🌐 Read my Articles ► codinghelmet.com/articles
📸 Join me on LinkedIn ► / zoran-horvat
For collaboration or any queries:
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
👨 About Me 👨
Hi, I’m Zoran, I have more than 20 years of experience as a software developer, architect, team lead, and more. I have been programming in C# since its inception in the early 2000s. Since 2017 I have started publishing professional video courses at Pluralsight and Udemy and by this point, there are over 100 hours of the highest-quality videos you can watch on those platforms. On my KZbin channel, you can find shorter video forms focused on clarifying practical issues in coding, design, and architecture of .NET applications.
❤️
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
⚡️RIGHT NOTICE:
The Copyright Laws of the United States recognize a “fair use” of copyrighted content. Section 107 of the U.S. Copyright Act states: “Notwithstanding the provisions of sections 106 and 106A, the fair use of a copyrighted work, including such use by reproduction in copies or phono records or by any other means specified by that section, for purposes such as criticism, comment, news reporting, teaching (including multiple copies for classroom use), scholarship, or research, is not an infringement of copyright." This video and our youtube channel, in general, may contain certain copyrighted works that were not specifically authorized to be used by the copyright holder(s), but which we believe in good faith are protected by federal law and the Fair use doctrine for one or more of the reasons noted above.
⭐For copyright or any inquiries, please contact us via a comment
#designpatterns #csharp #dotnet

Пікірлер: 49
@zoran-horvat
@zoran-horvat Жыл бұрын
Become a patron and get access to source code and exclusive live streams: www.patreon.com/posts/visitor-design-81382001
@iPazooki
@iPazooki Жыл бұрын
That UnreachableException was a great bonus! Thanks for your excellent content.
@zoran-horvat
@zoran-horvat Жыл бұрын
I'm glad to hear you liked it!
@sunnypatel1045
@sunnypatel1045 Жыл бұрын
I always struggle to find a use case for this pattern. You opened my eyes!
@BoteeQ
@BoteeQ Жыл бұрын
Great video! I am waiting for other design patterns with practical use cases, especially those infrequently used.
@sudqi
@sudqi Жыл бұрын
This the same thing came to my mind when I've read why Accept method needs be added and do a double dispatch. Thanks for showing that here.
@pawel131657
@pawel131657 Жыл бұрын
Very accessible way of explaining programming patterns! Imo even better than nick chapsas channel :) You have my sub sire!
@xrysav11
@xrysav11 4 ай бұрын
Just found, nice tutorial. Got to see more your videos. Thanks
10 ай бұрын
Well, in traditional visitor compiler won't capture "a new class" error because the domain class hierarchy is required. Compiler will generate a call to superclass Accept method. No compile time, no runtime error will occurr, heavy debugging time...
@vladas6645
@vladas6645 Жыл бұрын
Quite effective video! I like the "fluency" or how well the writing code is aligned with the talk. The first thing that comes to me is to check if there's some analyzer that can ensure exhaustive pattern matching at compile time, perhaps that is good fit for larger projects?
@mollybjork5499
@mollybjork5499 Жыл бұрын
Very nice video Zoran, good work!
@zoran-horvat
@zoran-horvat Жыл бұрын
Thanks!
@mdev3987
@mdev3987 Жыл бұрын
Thank you so much for this video, was interesting to see VDP!
@zoran-horvat
@zoran-horvat Жыл бұрын
Visitor is by far the least frequently used pattern. But it is still irreplaceable in usages such as transforming expression trees and similar.
@majixx
@majixx Жыл бұрын
Amazing video. Thank you for sharing.
@djpaulytee
@djpaulytee 9 ай бұрын
Great video and format!
@joaomachado9105
@joaomachado9105 Жыл бұрын
your content is awesome, pretty glad i found it :D
@Quimoth
@Quimoth 4 ай бұрын
I think the main benefit for the visitor pattern is when you expect others to write their own visitors to walk your (sealed) composite structure. In LINQ there is an abstract ExpressionVisitor that you could use to translate the Expression to whatever you like, using whatever you want. You could ofcourse still opt for pattern matching instead when walking the Expression object but why would you if you could just have your class inherit from the abstract so you get all the different types in their own method with autocomplete from your IDE? This does seem like the sole reason for this pattern to stay around in C# however.
@milandjukic88
@milandjukic88 Жыл бұрын
Koji si ti kralj. Tako je lepo slusati te
@zoran-horvat
@zoran-horvat Жыл бұрын
Vežbalo se...
@koboldhelper
@koboldhelper Жыл бұрын
Between the traditional visitor and pattern matching approaches is there any significant performance difference? Is the pattern matching just compiler magic that is type checking under the hood (which you could do in older c# direct with “is” and cast) which is slower than a polymorphic call?
@HizusHiz
@HizusHiz 6 ай бұрын
No, it converts to "as" construct with null checking for reference types. And these works faster than double virtual calls.
@rezakaaccount
@rezakaaccount 9 ай бұрын
SwitchExpressionException is better suited for this scenario as it can also capture the value of unmatched case.
@zoran-horvat
@zoran-horvat 9 ай бұрын
That is an interesting suggestion. I will consider it next time, though it has a drawback that it is telling out the implementation detail. But I see your point and I will give it some time of thinking.
@crazyfox55
@crazyfox55 29 күн бұрын
One big thing you forgot to mention is that these are extension methods so its also possible to call them from the name itself. Name.CommonName()
@zoran-horvat
@zoran-horvat 29 күн бұрын
What do you mean forgot? I made that an extension method.
@carlosboyanosky8044
@carlosboyanosky8044 Ай бұрын
original visitor design pattern can leverage dependency injection? Given the functional pattern matching approach lacks of it that could mark a difference
@zoran-horvat
@zoran-horvat Ай бұрын
You can inject dependencies into functions, too. The pattern matching expression can operate within a closure.
@adambickford8720
@adambickford8720 Жыл бұрын
I think the compile time error is a pretty big difference. I don't' know as its worth all the complexity and boiler plate just to prove its well-formed, but it is a difference.
@zoran-horvat
@zoran-horvat Жыл бұрын
That difference is important in sensitive portions of code, like tree transformation visitors, library code, and similar. Take ExpressionVisitor in C# as a good example. It is virtually unimaginable that someone could transform expressions in .NET using any approach other than implementing the explicit visitor. On the other hand, most business applications do not have that problem. You would model business concepts as they appear and then define mappings to other concepts for years. Practice shows that adding variants to a business concept happens so rarely that you can safely ignore the nuisance that comes with that. How hard can it be to augment mapping expressions for a domain type once in two years? That is how often that happens! Of course, there are certain prerequisites to making it work that way. For one thing - discipline, discipline, discipline. Make every concept a small one. Build larger concepts by applying composition to smaller ones, not by deepening the hierarchies. Avoid hierarchies more than one level deep. Any hierarchy deeper than that must come with a rock-solid justification.
@adambickford8720
@adambickford8720 Жыл бұрын
@@zoran-horvat Just pointing out to viewers that the OO version is solving a 'harder' problem, it isn't just verbose for the sake of it. The real question is do you have this problem and even if you do, is it worth this price to solve? Probably not.
@Sindrijo
@Sindrijo 2 ай бұрын
This approach saves on complexity in the implementation but requires a special tool/testing to ensure correctness before deployment. It would be nice to be able to instruct the compiler that a type matching switch statement must be exhaustive over the derived types. Though it is probably not hard to write an analyzer for that.
@wertrager
@wertrager Жыл бұрын
Very similar to a catamorphism in F#
@obinnaokafor6252
@obinnaokafor6252 Жыл бұрын
Thank you.
@MoA-fm8ph
@MoA-fm8ph Жыл бұрын
@zoran-horvat Thank you very much for the demonstration of the visitor pattern, excellent work keep them coming, one question about the names, in most systems you get the names from a database or an API and then you map them to a single DTO like `Person` record but in your solution, you have 3 records `SimpleName`, `Mononym` and `CompoundName`. and for the pattern to work you need multiple DTOs to work How would you resolve this problem if you want to implement the Visitor pattern?
@Quimoth
@Quimoth 4 ай бұрын
For reference: kzbin.info/www/bejne/qqKYq6eQhJloY8k The thing you need to ask yourself is whether the receiving party of your API cares which type of name the person is using. The visitor in this example is meant to return a string representation of the name object, regardless of its type. So your DTO, or receiving end would simply have a string property. In this case traffic would be one way and you would need a different approach if you were to ever allow creating or updating of the names. The Author API would probably care a lot about the types of names, but in the publications/books API you simply want to know the names. You could also change the return type of your visitor, exploring a different pattern/approach altogether might in the end be better.
@Darebit2k1
@Darebit2k1 Жыл бұрын
If we remove the "pattern matching" in the "implicit visitor" we'd have a "type checking" analysis into that method, Which would smell, and be a little confusing because besides, the proposed "implicit visitor" pattern looks more like the "factory method" pattern than the "visitor" pattern. That's my doubt.
@zoran-horvat
@zoran-horvat Жыл бұрын
Type matching expressions are the basis of working with discriminated unions in functional programming and discriminated unions are the basis of domain modeling. It is interesting to note that the Visitor pattern is adding this technique to object-oriented languages, whereas that same technique is supported natively in any functional language. Therefore, the Visitor was introduced to overcome the native deficiency of OOP. As C# gains more functional elements, pattern matching, including type matching, will gain more and more prominence. Regarding code smell: it could turn into a code smell if target objects were mutable. In an immutable design, it is a mapping like any other.
@Darebit2k1
@Darebit2k1 Жыл бұрын
Professor Horvat thank you very much for your explanation, it was very enriching.
@redcrafterlppa303
@redcrafterlppa303 9 ай бұрын
I think the visitor pattern plays well with java sealed class hierarchies. It would be nice to have something like that in c# as well. It's a powerful feature on its own allowing for example exhaustive enum like hierarchies similar to rusts enums. For the "implicit visitor" in particular it allows for a exhaustive switch without an catch all and giving you an compile error once someone adds a class to the sealed hierarchy.
@furo.v
@furo.v 3 ай бұрын
Many design patterns are way easier to implement with functional programming. Strategy is just a function with the specified signature (params and return). My only complain here is that languages like Rust would not need the _ => wildcard for the matching pattern, since implementing all subtypes is already exhaustive in my opinion.
@dwhxyz
@dwhxyz Жыл бұрын
The idea of needing to know/remember to implement code somewhere else (along with nasty switch/if class type checking and exception throwing if it does not exist) once a new class implementation is added to the solution has always felt wrong to me. Its not something I personally would do with the only exception being if I was trying to extend existing classes which reside inside a third party library and even then I would probably do it a different way.
@zoran-horvat
@zoran-horvat Жыл бұрын
Here is the answer I have already posted on a similar question: The problem of having or not having compile-time safety is important in sensitive portions of code, like tree transformation visitors, library code, and similar. Take ExpressionVisitor in C# as a good example. It is virtually unimaginable that someone could transform expressions in .NET using any approach other than implementing the explicit visitor. On the other hand, most business applications do not have that problem. You would model business concepts as they appear and then define mappings to other concepts for years. Practice shows that adding variants to a business concept happens so rarely that you can safely ignore the nuisance that comes with that. How hard can it be to augment mapping expressions for a domain type once in two years? That is how often that happens! Of course, there are certain prerequisites to making it work that way. For one thing - discipline, discipline, discipline. Make every concept a small one. Build larger concepts by applying composition to smaller ones, not by deepening the hierarchies. Avoid hierarchies more than one level deep. Any hierarchy deeper than that must come with a rock-solid justification.
@dwhxyz
@dwhxyz Жыл бұрын
@@zoran-horvat I agree that in reality adding another implementation may be infrequent or never happen but it still feels sloppy to me. I would say there is a case that the matching approach in the video breaks OCP but even I would say nothing is ever perfect and there could be times where breaking a SOLID rule(s) might be ok. Anyway, I'm really enjoying your videos - you're a very clever guy who deservers more subs/views.
@alxjones
@alxjones Жыл бұрын
The fact that this is not checked at compile-time creates an unnecessary cost, and a cost which is atypical for functional-style design. An unreachable exception is just a run-time crash for something you failed to check at compile-time, and should be considered a code smell. This seems to be a symptom of squeezing a functional pattern into an object-oriented context. A functional language would have PersonalName as a sum type, and so it could be checked at compile-time if all the summand types are handled in pattern matching. I'm not sure that this is impossible to check for the class hierarchy of OOP, but it's clear that C# at least isn't interested in doing that check.
@zoran-horvat
@zoran-horvat Жыл бұрын
Everything you said is right - to a point. By requesting compile-time safety, you are dismissing entire programming languages. C# is going this path for the last 15 years already and you can expect that all remaining deficiencies in its current state are temporal.
@alxjones
@alxjones Жыл бұрын
@@zoran-horvat I'm not trying to be a stickler about compile-time checking everything. I will always prefer it, but I understand that there are reasons to not have it, and some people like those reasons enough. My issue is that we took something that can be compile-time checked in OOP (interfaces), replaced it with a feature that can be compile-time checked in FP (pattern matching), and somehow ended up with something that isn't compile-time checked. It seems like a waste to not be able to check this.
@zoran-horvat
@zoran-horvat Жыл бұрын
@@alxjones I see your point, and indeed the things will settle down once we get discriminated unions in C#.
@ppasieka
@ppasieka Жыл бұрын
And this is precisely why I still prefer to use the Visitor pattern explicitly. The compile-time checks are very compelling 😇
Tame the Power of the Iterator Pattern and yield return in C#
11:36
Master the Design of Functional Behavior in C#
19:17
Zoran Horvat
Рет қаралды 2,3 М.
La final estuvo difícil
00:34
Juan De Dios Pantoja
Рет қаралды 27 МЛН
🍟Best French Fries Homemade #cooking #shorts
00:42
BANKII
Рет қаралды 16 МЛН
Miracle Doctor Saves Blind Girl ❤️
00:59
Alan Chikin Chow
Рет қаралды 38 МЛН
Clean Code Tip: Favor Method Chaining Over Nested Calls
10:23
Zoran Horvat
Рет қаралды 24 М.
Understanding The Visitor Design Pattern
32:08
Ryan Schachte
Рет қаралды 56 М.
How to Avoid Null Reference Exceptions: Optional Objects in C#
18:13
Why Use Design Patterns When Python Has Functions?
23:23
ArjanCodes
Рет қаралды 97 М.
Visitor: How I Mastered the Toughest Programming Pattern
12:59
Build Your Own Option Type in C# and Use It Like a Pro
18:31
Zoran Horvat
Рет қаралды 12 М.
Use Null Object Pattern in Your Rich Domain Model
13:16
Zoran Horvat
Рет қаралды 10 М.
17 Pieces of C# Syntax That Make Your Code Short
12:41
Zoran Horvat
Рет қаралды 17 М.
Выложил СВОЙ АЙФОН НА АВИТО #shorts
0:42
Дмитрий Левандовский
Рет қаралды 1,2 МЛН
👎Главный МИНУС планшета Apple🍏
0:29
Demin's Lounge
Рет қаралды 489 М.
Топ-3 суперкрутых ПК из CompShop
1:00
CompShop Shorts
Рет қаралды 261 М.
Теперь это его телефон
0:21
Хорошие Новости
Рет қаралды 1,7 МЛН