You May Have Never Learned This Lesson Right

แชร์
ฝัง
  • เผยแพร่เมื่อ 9 ก.ค. 2024
  • Ever since extension methods were added to C#, programmers have struggled to figure out the proper use for them and their purpose in software design.
    There are three principal roles where extension methods come in handy:
    1. In metaprogramming - we extend a type without modifying it. That lets us add orthogonal concerns to classes we develop and even to foreign types we have no control over. How wonderful! It is a pity that this idea brings a whole pile of novel problems we didn't have before.
    2. In functional extensions - we add pure functions that operate on models, typically generically, so that they apply to any model. We can seamlessly extend the domain model in ways never conceived during their design. How wonderful! But beware: this approach requires implementation purity and interface generality. That is a formidable combination of goals if you plan to achieve them.
    3. When attempting to combine models, especially object-oriented and functional ones - that is the programming model that modern C# advocates. You can implement features that apply to specific models or even to a larger class of models if the method is generic. By systematically using extension methods, you can achieve great interoperability of models in a complex application.
    Watch this video to learn how to utilize extension methods in domain modeling effectively. That skill will pay off manifold once you encounter a difficult situation with many responsibilities pertaining to a set of models. Knowing which responsibilities fit extension methods and which should remain as instance-level methods is sometimes the decisive factor in either developing a successful or failing to do so.
    ✅🔔 Become a patron ► / zoranhorvat
    ✅🔔 Subscribe ► / @zoran-horvat
    ⭐ Learn more from video courses:
    Beginning Object-oriented Programming with C# ► codinghelmet.com/go/beginning...
    ⭐ Collections and Generics in C# ► codinghelmet.com/go/collectio...
    ⭐ Making Your C# Code More Object-oriented ► codinghelmet.com/go/making-yo...
    ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
    ⚡️Chapters:
    ⌚ 00:00 Intro
    ⌚ 02:11 Metaprogramming extension methods
    ⌚ 04:37 Functional extension methods
    ⌚ 08:54 Functional extensions with OO model
    ⌚ 12:01 Conclusion
    ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
    ⭐ CONNECT WITH ME 📱👨
    🌐Become a patron ► / zoranhorvat
    🌐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
    ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
    👨 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 TH-cam 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 at zh@codinghelmet.com
    #csharp #dotnet #functionalprogramming
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 26

  • @vyrp
    @vyrp 7 หลายเดือนก่อน +4

    Just a detail, not related to the main point of the video:
    If `CompareTo` returns `int.MinValue`, negating it results in `int.MinValue` again.
    That's why I prefer inverting the arguments instead of negating the result when reversing the sort direction: `b.Height.CompareTo(a.Height)`.
    But anyway, most `CompareTo` implementations don't return `int.MinValue`, so this is not a big deal.

    • @zoran-horvat
      @zoran-horvat  7 หลายเดือนก่อน +1

      That is a good point and a reminder to stay away from extreme values in a range.

    • @krccmsitp2884
      @krccmsitp2884 7 หลายเดือนก่อน +1

      In checked mode you would get an overflow error at compilation time.

  • @zoran-horvat
    @zoran-horvat  7 หลายเดือนก่อน +3

    Download the source code for this video: www.patreon.com/posts/source-code-for-93364170
    Enroll the *Advanced Defensive Programming Techniques* course ► codinghelmet.com/go/advanced-defensive-programming-techniques
    Learn more from the video course *Beginning Object-Oriented Programming with C#* ► codinghelmet.com/go/beginning-oop-with-csharp
    How to Avoid Null Reference Exceptions: Optional Objects in C# ► th-cam.com/video/8-2xr_kBRnQ/w-d-xo.html
    Build Your Own Option Type in C# and Use It Like a Proth-cam.com/video/gpOQl2q0PTU/w-d-xo.html
    This Decorator Pattern Implementation Will Make Your Day! ► th-cam.com/video/Pqow_rfuZSU/w-d-xo.html
    Clean Code Tip: Favor Method Chaining Over Nested Calls ► th-cam.com/video/zWn0O0xzWMA/w-d-xo.html

  • @lindermannla
    @lindermannla 2 หลายเดือนก่อน +1

    Excelent content. Congratulations!

  • @vulcanobyte
    @vulcanobyte 7 หลายเดือนก่อน +2

    Thanks GOAT

  • @coderider3022
    @coderider3022 7 หลายเดือนก่อน +1

    12:20 is key bit. I probably over use them but love them. I get a bit frustrated at times having to add packages to give me more methods and namespace conflicts arise. The main ‘must have packages’ handle this differently.

    • @zoran-horvat
      @zoran-horvat  7 หลายเดือนก่อน

      I was driving to that point through the entire video. That indeed is the whole point.

  • @yanivrubin7202
    @yanivrubin7202 7 หลายเดือนก่อน +4

    I used to hate extension methods when they came out. Thought of them as just a glorified static methods, and static was the enemy. But with time learned to enjoy the way they make the code more readable. I think i am over using them now.

  • @thomasschroter3802
    @thomasschroter3802 7 หลายเดือนก่อน

    I just don't catch where the functional code in the Smallest function is. IComparer is an interface and thus "comparer" appears as an instance object and that is not functional at all?! Also, the sorting is a pretty weak example, as it can be replaced with built-in functionality....
    var list = new int[] {7, 9, 2, 6, 8, 1, 4, 5, 0, 3}; //etc.
    var top3 = list.Pick ( 3, (a, b) => (a < b) ? -1 :(a == b) ? 0 :1 );
    public static class SortingExtensions
    {
    public static IEnumerable Pick (this T[] list, int count, Comparison comparison)
    {
    var sorted = list.ToList();
    sorted.Sort (comparison);
    return (count

    • @zoran-horvat
      @zoran-horvat  7 หลายเดือนก่อน +1

      It is not important that a method is instance level to conclude it is not functional in languages such as C# or Java. Delegated are all instances and "calling" a delegate (such as Comparer) in C# is nothing but a call to its instance-level method Invoke.
      Java has the term "functional interface" for interfaces like IComparer. You could freely assign a Comparison delegate or even a lambda to a reference declared as IComparer.
      For a method to be substantially functional, it must satisfy the same conditions as in any functional language: to depend on no mutable state, make no observable side effects, produce stable output, things like that. You would be surprised to learn how large areas, and even entire libraries in .NET, are now built in functional style.
      BTW, your solution violates the requirements, which specifically say that the input is large. You should neither sort it, nor keep it in memory.

  • @silop
    @silop 7 หลายเดือนก่อน

    Where do extension methods belong when working in a clean architecture/vertical slice architecture?
    Great video!

    • @zoran-horvat
      @zoran-horvat  7 หลายเดือนก่อน +3

      Extension method is just a function - it is up to you to decide when to call it and where from. When an extension method contains domain logic, and consequently belongs to one vertical slice, then you would probably want to inject it through a Func delegate when there is the need for variation. Otherwise, if it is an orthogonal concern, like methods from LINQ, then it can reside in a separate, reusable namespace and never belong to any vertical slice.

  • @sandromagalli8587
    @sandromagalli8587 7 หลายเดือนก่อน +1

    this is something i'm experiencing now in my third year as a programmer, before it was learning different technologies and actually complete projects, regardless of how much were they put togheter with tape. Now it's expecially the code i write, sometimes things being null when they shouldn't, checking for null and throwing exception because a method might return null in other cases but in this one it shouldn't! Then those extensions methods "ToDto" or putting them directly in the model class. Well let's try owned entities in EF Core! lol gotta be carefull to update them with reference when setting current values. What about complicated entities that are used in many places, should the sorting be done by the viewmodel on the Ui or always be the same in the model to ensure invariance?
    In other words your videos are the only ones online helping me to clear this confusion.

    • @zoran-horvat
      @zoran-horvat  7 หลายเดือนก่อน +1

      So many hard questions in one post...

  • @nickw656
    @nickw656 7 หลายเดือนก่อน

    why the properties FirstName and LastName of the model class Person are private?

    • @zoran-horvat
      @zoran-horvat  7 หลายเดือนก่อน +2

      Because the model started off as pure OO, and in OO we tend to hide the components and expose methods that use them (a.k.a. tell, don't ask).

  • @_NguyenManhToan_
    @_NguyenManhToan_ 7 หลายเดือนก่อน

    ❤❤❤❤❤❤❤

  • @jonasng9554
    @jonasng9554 7 หลายเดือนก่อน +2

    My colleagues hate using extension methods because it is within static class, hence you cannot mock it... However, when the extension is put on the object that is mockable, that shouldn't be a problem, right? Professor Zoran I love functional programming, but my colleagues and company culture thinks we need to keep things as simple as possible, so when junior programmers come in, they wont have to learn all the functional secrets that we left behind. What us your thought on this??

    • @zoran-horvat
      @zoran-horvat  7 หลายเดือนก่อน +10

      They should mock things that vary. Static methods don't vary. Actually, the variation is implemented by selecting one static method or the other.
      Programmers who avoid static methods due to tests are missing the point entirely, both of methods and of tests.

    • @jonasng9554
      @jonasng9554 7 หลายเดือนก่อน +2

      As always, a well seasoned answer. Thanks!

  • @mocococo2877
    @mocococo2877 7 หลายเดือนก่อน

    I can't agree that complicating code for the sake of some imaginary biblical rules is justified.
    Especially in the second example where for just avoiding one if statement you clime the mount Everest and return back. I don't think that this is lighter on resource expenses and speed either.
    How in the world if statement breaks the whatever rule ? Except that you invented that rule and then you say it breaks it.

    • @zoran-horvat
      @zoran-horvat  7 หลายเดือนก่อน +1

      You are taking a demo and acting as if it were a production-grade application. It is not "an if". It is "ten thousand ifs" in a domain model.
      Now that we are on the same page, we can start talking programming. What was your concern, then?

  • @anm3037
    @anm3037 7 หลายเดือนก่อน

    LINQ is quite remarkable, but I avoid it like crime because of the horrible performance it has.

    • @zoran-horvat
      @zoran-horvat  7 หลายเดือนก่อน +11

      I think you should reconsider that because the performance of LINQ is often better than an alternative nowadays, and it is anything but horrible.