Let Design by Contract Be Your Highest-Valued Design Method

SdĂ­let
VloĆŸit
  • čas pƙidĂĄn 4. 10. 2023
  • Become a patron and download source code: / source-code-for-90343492
    What do you think about having bugs in your code?
    You know that old joke: it's scary when you see them; it's scarier when you don't. So, how can you tell that your code has no bugs?
    When we design microservices, for example, we use service contracts. In this video, you will learn how to use contracts in your regular classes, too.
    The idea is not new. It is the Design by Contract technique. It has been around for a couple of decades already and it dismisses the possibility of making certain kinds of bugs in classes and methods.
    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.đŸ”„â€ïž
    ✅🔔 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...
    ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
    ⭐ 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 CZcams 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 #objectorientedprogramming
  • Věda a technologie

Komentáƙe • 34

  • @zoran-horvat
    @zoran-horvat  Pƙed 8 měsĂ­ci

    Enroll video course *Beginning Object-Oriented Programming with C#* â–ș codinghelmet.com/go/beginning-oop-with-csharp
    Download the source code: www.patreon.com/posts/source-code-for-90343492
    Learn from related videos:
    Avoid Returning Null From Methods - There Is a Better Way To Write Them! â–ș czcams.com/video/HRLdcMil7Ec/video.html
    Use the Decorator Pattern To Reduce Code Duplication in Complex Models â–ș czcams.com/video/7N0LpGAI5T4/video.html
    Master the Power of Composite Pattern in Rich Domain Modeling â–ș czcams.com/video/1l_hHoMgTV0/video.html

  • @rustamhajiyev
    @rustamhajiyev Pƙed 8 měsĂ­ci +5

    It's indeed very hard. Mental burden is very high and requires you to constantly reevaluate all pre and post conditions after writing almost each next line of code. It would be so helpful to offload that information into method description, and let the compiler to track and notify us when something doesn't match. Dreams, sweet dreams 😅
    Thanks for the content as always 👍😊

    • @zoran-horvat
      @zoran-horvat  Pƙed 8 měsĂ­ci +3

      There was an attempt to add DbC to dotnet years ago. That effort was abandoned later, so far as I know, but it has shown what can and what cannot be verified at compile time. That was a wild ride.

    • @harrytsang1501
      @harrytsang1501 Pƙed 8 měsĂ­ci

      What you described is data flow analysis. I used to program in typescript and their data flow analysis by types is quite good.
      Value boundaries by type declaration is not a feature of typescript but there are other tools that try to do that.

  • @mateuscortianoschwarz7276
    @mateuscortianoschwarz7276 Pƙed 8 měsĂ­ci +5

    I don't even program in C# but I love your channel. So many valuable insights.

  • @7th_CAV_Trooper
    @7th_CAV_Trooper Pƙed měsĂ­cem

    This seems like a DDD style implementation of value types.

  • @piotrkozbial8753
    @piotrkozbial8753 Pƙed 8 měsĂ­ci +2

    Of course it's hard. In my current company they just ignore it completely. You want to know the contract? Read the code.
    That said, static enforcement of arbitrary contracts is simply impossible to be done automatically, because we're getting into the territory of theorem proving. Functional languages with dependent types (e.g. Idris) are able to encode arbitrary contracts in the type of a function, but you must be prepared to supply a formal proof.

  • @jensingels5958
    @jensingels5958 Pƙed 8 měsĂ­ci

    Imagine a tool, similar to SpecFlow, that enables you to visually represent your requirements through step definitions and then automatically generates and applies them to a middleware. Is there an existing tool that offers this capability? Furthermore, since deeper contract validation aligns closely with business requirements, having it separate from technical requirements could be a compelling approach.

    • @zoran-horvat
      @zoran-horvat  Pƙed 8 měsĂ­ci +1

      There were attempts in that direction, the earliest I remember seeing as old as the late 1990s. However, that didn't bring us much closer to the goal and we don't have such tools available. One of the problems is that there are so many situations where DbC becomes more complex than the code itself and/or imposes a prohibitive performance penalty.

  •  Pƙed 8 měsĂ­ci

    What languages have support for DbC and to what extent?
    C# has poor support via attributes, like Returns, NotNull. Also nullable classes (?).

    •  Pƙed 8 měsĂ­ci +1

      It's not well known, but the original language that was designed around DbC and other nice OO concepts developed by Bertrand Meyer is Eiffel. Even if you don't go the Eiffel way, I recommend to read the classic book by Meyer, Object Oriented Software Construction.

    • @zoran-horvat
      @zoran-horvat  Pƙed 8 měsĂ­ci +1

      Yes, Eiffel was the first language to have DbC built in natively. I cannot testify that it was a giant success, nor do I see it as a great success in other languages, such as Kotlin, Scala and similar. It is not just preconditions/postconditions. There is a lot more there. Imagine a method calling another method while invariants are broken, but it restores them before returning. Can you figure out what has happened? There are many nasty corner cases.
      Languages like Java and C# depend on third-party libraries. C# had Code Contracts library but it is dead for quite some time. I think nothing was done in .NET Core to support it.
      However, you can apply DbC in any language that supports debug assertions to a certain level. It will not be comfortable, but it will be to the point. Just assert whatever Boolean condition you think should be part of the contract.

    •  Pƙed 8 měsĂ­ci

      In Eiffel, the invariant is enforced every time you call a method outside of the class. It was really a tight, clean design. There's a number of reasons why it didn't succeed, but the DbC implementation was certainly not one of them.

    • @zoran-horvat
      @zoran-horvat  Pƙed 8 měsĂ­ci +1

      @ Eiffel indeed has an elegant implementation of DbC (that is where I learned about DbC the first time). But the problem lies elsewhere and I think it is in the promise DbC makes, which is too high.
      I have tried to apply it to one complex project, using the Code Contracts library for dotnet, and found several corner cases that I couldn't solve. In all cases it was working with sequences where contract validation required a stateful algorithm, where the underlying operation was stateless. In effect, some heavy duty methods grew from linear to square time complexity and from constant to linear space - the application couldn't work anymore even though the definition of contracts was sound.
      There is a grain of truth in that old adage, that DbC is a great way to define a stack.

    •  Pƙed 7 měsĂ­ci

      ​@@zoran-horvat Well I don't know about your case, but certainly you cannot have a complete DbC implementation if it is not integrated with the language and the compiler, so any dotnet implementation is probably bound to be limited. Also, DbC is intended to be partially or totally disabled when going to production.

  • @Mefator
    @Mefator Pƙed 8 měsĂ­ci

    What do you think about moving the postconditions wrapping into some extension methods on IDiscount? It would improve readability and imply that postconditions are applied after the discount is constructed.

    • @zoran-horvat
      @zoran-horvat  Pƙed 8 měsĂ­ci +2

      All elements of the contract must be verified by the class itself, because they are the same no matter who is calling its methods. The caller has nothing to do there.

  • @guy7524
    @guy7524 Pƙed 8 měsĂ­ci

    Can someone translate what the video is about

    • @zoran-horvat
      @zoran-horvat  Pƙed 8 měsĂ­ci +1

      Design by Contract.

    • @guy7524
      @guy7524 Pƙed 8 měsĂ­ci

      @@zoran-horvat A C# interface is a contract. So why not call the video using interfaces in C#? Unless it explains another concept. Then what is that concept?

    • @zoran-horvat
      @zoran-horvat  Pƙed 8 měsĂ­ci +1

      @@guy7524 Did you watch the video?
      Contract, as in DbC, is the set of rules, named preconditions, postconditions and invariants, that evaluate to true (when satisfied) or false (when violated).
      Any ruke belonging to the contract can either be evaluated at compile time or at run time.
      Nullable reference types are an example of pre/postconditions verified at compile time. Compiler is performing static code analysis (SCA) in that case. In interpreted languages, one can use a separate SCA tool for the same purpose.
      I have explained all that in the video, I believe. An interface is not a contract, at least not in DbC terms.

    • @guy7524
      @guy7524 Pƙed 8 měsĂ­ci

      ​@@zoran-horvat ​ Seems over-engineering to me that can be solved with guard clauses.

    • @zoran-horvat
      @zoran-horvat  Pƙed 8 měsĂ­ci +3

      @@guy7524 You are mixing concepts. DbC is not engineering and hence cannot be overengineering either. It is a formal method of proving that there is no bug.
      When it comes to guard clauses, they serve a totally different goal.

  • @jrgalyen
    @jrgalyen Pƙed 8 měsĂ­ci

    This is terrible. You are Design by code, not contract. You have to start with OpenAPI, json schema, avro, or some type of structured documentation contract. Here, there is so much more than contracts going on. Everything you did in this video is accomplishable with OpenAPI + nswag -> code generation
    And here I thought you had something worthwhile to present. *shakes head*. And yes. Data Contract spec -> code generation was called RAD, rapid application development. It has also been around the last 30+ years

    • @zoran-horvat
      @zoran-horvat  Pƙed 8 měsĂ­ci +2

      Did you not mix up the theories?
      The word 'contract' is common to them, but those are different topics altogether.
      Start from here: a.co/d/cLujwRD

    • @zoran-horvat
      @zoran-horvat  Pƙed 8 měsĂ­ci +2

      And, out of curiosity, why are you mentioning OpenAPI, JSON and avro on every one of my videos, even though you must be aware this is backend code? Is that some kind of fetish?

    • @iorch82
      @iorch82 Pƙed 7 měsĂ­ci

      A C# interface is a contract. Another debate is how C# devs have perverted its meaning because using it as a testing commodity.

    • @zoran-horvat
      @zoran-horvat  Pƙed 7 měsĂ­ci

      @@iorch82 How does a C# enforce a contract on an interface?