Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. Other Discussions
  3. The Weird and The Wonderful
  4. The changing landscape of OOP (from class to struct)

The changing landscape of OOP (from class to struct)

Scheduled Pinned Locked Moved The Weird and The Wonderful
csharpcomfunctionalperformancetutorial
62 Posts 24 Posters 9 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • R raddevus

    Just started reading this (just released) book, The C# Type System (no starch press)[^] and the first chapter is kind of blowing my mind. Step 1 Author starts out with the following example and says, "You must use better named variables so dev users know what they mean."

    Displacement(double t, double v, double s)
    {
    var x = v * s * Math.Cos(t);
    var y = v * s * Math.Sin(t) - 0.5 * 9.81 * Math.Pow(s, 2);
    return (x, y);
    }

    Yes, that makes sense. Step 2 Then he says, "Oh, you can add meaning with this new idea of named arguments so users don't have to remember order that they should be passed in."

    var result = Displacement(angle: .523, speed: 65, elapsedTime: 4);

    Ok, yes, that is good advice with the modern capabilities. Step 3 May Blow Your Mind He mentions that the code is still confusing because all three arguments are the same primitive type (double) and this leads into...

    From the book:

    Primitive Obsession code smell, which describes any code that has an overreliance on primitive types—that is, those types that are built into the language, such as int, double, and string.

    The solution is... Wrap All the Primitive Types In Structs 🤯🤯🤯🤯🤯

    public struct Angle
    {
    public double Size {get; set;}
    }
    public struct Speed
    {
    public double Amount {get; set;}
    }

    The Paradigm Has Shifted Now, when the user attempts to call the Displacement method the compiler will know that the argument type is wrong. Now, there's no way to pass the wrong value into the method, because the compiler will know the type. Wow, that is a very different paradigm!! Step 4 Is Immutability Now, make each struct immutable

    J Offline
    J Offline
    John Chadwell
    wrote on last edited by
    #38

    I once worked with a programmer 28 years ago who was approaching retirement. We worked on an accounts receivable/payable system together. He did all of the backend calculations in exactly the same format as step 1. If I remember correctly even his function names were single letters of the alphabet. I think I would have done at least step 2. I thought it was the simplest code you could possibly write. Back then there was no intellisense so we just documented our code thoroughly! I don't see any value in step 3 or 4. Seems like unnecessary layers of code.

    R 1 Reply Last reply
    0
    • R raddevus

      Just started reading this (just released) book, The C# Type System (no starch press)[^] and the first chapter is kind of blowing my mind. Step 1 Author starts out with the following example and says, "You must use better named variables so dev users know what they mean."

      Displacement(double t, double v, double s)
      {
      var x = v * s * Math.Cos(t);
      var y = v * s * Math.Sin(t) - 0.5 * 9.81 * Math.Pow(s, 2);
      return (x, y);
      }

      Yes, that makes sense. Step 2 Then he says, "Oh, you can add meaning with this new idea of named arguments so users don't have to remember order that they should be passed in."

      var result = Displacement(angle: .523, speed: 65, elapsedTime: 4);

      Ok, yes, that is good advice with the modern capabilities. Step 3 May Blow Your Mind He mentions that the code is still confusing because all three arguments are the same primitive type (double) and this leads into...

      From the book:

      Primitive Obsession code smell, which describes any code that has an overreliance on primitive types—that is, those types that are built into the language, such as int, double, and string.

      The solution is... Wrap All the Primitive Types In Structs 🤯🤯🤯🤯🤯

      public struct Angle
      {
      public double Size {get; set;}
      }
      public struct Speed
      {
      public double Amount {get; set;}
      }

      The Paradigm Has Shifted Now, when the user attempts to call the Displacement method the compiler will know that the argument type is wrong. Now, there's no way to pass the wrong value into the method, because the compiler will know the type. Wow, that is a very different paradigm!! Step 4 Is Immutability Now, make each struct immutable

      C Offline
      C Offline
      Choroid
      wrote on last edited by
      #39

      Complete Novas HERE When I look at Wrap All the Primitive Types In Structs This looks logical to me ? That said it took me a little time to learn to use {get;set;} example below so my question is this code structure a good design or as stated just a fancy new way to write your code If this is considered a programming question sorry just delete the post. I try to follow the rules honest I did read all the replies

      namespace CRUDLibrary
      {
      public partial class frmCRUD : Form
      {
      public static string dbName = "Contacts.db";
      private string result;
      public string fn { get; set; }
      public string ln { get; set; }

      1 Reply Last reply
      0
      • R raddevus

        Just started reading this (just released) book, The C# Type System (no starch press)[^] and the first chapter is kind of blowing my mind. Step 1 Author starts out with the following example and says, "You must use better named variables so dev users know what they mean."

        Displacement(double t, double v, double s)
        {
        var x = v * s * Math.Cos(t);
        var y = v * s * Math.Sin(t) - 0.5 * 9.81 * Math.Pow(s, 2);
        return (x, y);
        }

        Yes, that makes sense. Step 2 Then he says, "Oh, you can add meaning with this new idea of named arguments so users don't have to remember order that they should be passed in."

        var result = Displacement(angle: .523, speed: 65, elapsedTime: 4);

        Ok, yes, that is good advice with the modern capabilities. Step 3 May Blow Your Mind He mentions that the code is still confusing because all three arguments are the same primitive type (double) and this leads into...

        From the book:

        Primitive Obsession code smell, which describes any code that has an overreliance on primitive types—that is, those types that are built into the language, such as int, double, and string.

        The solution is... Wrap All the Primitive Types In Structs 🤯🤯🤯🤯🤯

        public struct Angle
        {
        public double Size {get; set;}
        }
        public struct Speed
        {
        public double Amount {get; set;}
        }

        The Paradigm Has Shifted Now, when the user attempts to call the Displacement method the compiler will know that the argument type is wrong. Now, there's no way to pass the wrong value into the method, because the compiler will know the type. Wow, that is a very different paradigm!! Step 4 Is Immutability Now, make each struct immutable

        L Offline
        L Offline
        Leonardo Pessoa
        wrote on last edited by
        #40

        Just curious where did you manage to get that book. Everywhere I search for it says it is pre-order to be delivered by the end of next month.

        - Leonardo

        R 1 Reply Last reply
        0
        • R raddevus

          Just started reading this (just released) book, The C# Type System (no starch press)[^] and the first chapter is kind of blowing my mind. Step 1 Author starts out with the following example and says, "You must use better named variables so dev users know what they mean."

          Displacement(double t, double v, double s)
          {
          var x = v * s * Math.Cos(t);
          var y = v * s * Math.Sin(t) - 0.5 * 9.81 * Math.Pow(s, 2);
          return (x, y);
          }

          Yes, that makes sense. Step 2 Then he says, "Oh, you can add meaning with this new idea of named arguments so users don't have to remember order that they should be passed in."

          var result = Displacement(angle: .523, speed: 65, elapsedTime: 4);

          Ok, yes, that is good advice with the modern capabilities. Step 3 May Blow Your Mind He mentions that the code is still confusing because all three arguments are the same primitive type (double) and this leads into...

          From the book:

          Primitive Obsession code smell, which describes any code that has an overreliance on primitive types—that is, those types that are built into the language, such as int, double, and string.

          The solution is... Wrap All the Primitive Types In Structs 🤯🤯🤯🤯🤯

          public struct Angle
          {
          public double Size {get; set;}
          }
          public struct Speed
          {
          public double Amount {get; set;}
          }

          The Paradigm Has Shifted Now, when the user attempts to call the Displacement method the compiler will know that the argument type is wrong. Now, there's no way to pass the wrong value into the method, because the compiler will know the type. Wow, that is a very different paradigm!! Step 4 Is Immutability Now, make each struct immutable

          J Offline
          J Offline
          Juan Pablo Reyes Altamirano
          wrote on last edited by
          #41

          I'm kind of against the whole "make your code more readable...at the cost of performance and efficiency". Programmers of the future who cannot understand the context of the past (and therefore the code) are of little concern. It might be that, as an engineer, my first stance is that all newcomers must be educated (a little) and eventually they should learn to educate themselves (a lot). It harkens back to the guilds...but, except for being exclusive, there wasn't very much else wrong with their educational system. So if someone wants to break OOP, they should write their own language and let everyone else be. I'm just happy I don't have to remember if that string of bytes was an integer or a floating point value (and I use the wrong mnemonic for multiplication). If you don't like inheritance, don't use it.

          R 1 Reply Last reply
          0
          • J Jeremy Falcon

            raddevus wrote:

            Anyways, what do you think about this "Primitive Obsession code smell"?

            It seems like the book author is someone trying to sound smarter than they are. Just because someone writes a book doesn't make them a genius. Now, I do agree that primitive obsession is bad, but so is struct obsession. A struct won't inherently prevent a coder from mistaking milliseconds for seconds (to borrow from this thread's example). But, what it does do is offer more complexity in an application that may otherwise not be needed. A lot of these "new" ideas are just rehashed old ideas from JavaScript. I'm dead serious. It's just people looking for something to do rather than go outside. In JavaScript, some folks love to use an object as a parameter for everything. It's the loose and fast version of a struct in C#. It's just as ridiculous to expect an object as a single param in every last routine. The problem is, the obsession or abuse of any one concept. Average coders take one little thing and run with it because it's the new shiny doodad. Abusing structs is no better. It's just change for change's sake while pretending to be smart. It's about balance.

            raddevus wrote:

            Step 4 Is Immutability

            To the point of the book, to make each struct read only is a good idea. But, to the point of "prefer composition over inheritance", both Java and C# were literally designed with an OOP paradigm in mind. Move to a functional language if you want to start acting functional. In regard to immutability, you can use a sealed class in Java and C# as well. The irony is, all this struct talk is reminding me of C. People always said C sucked because it doesn't support classes. And yet, here we are. People just following the hype train because people looking to change something for no real gain and refuse to go outside. And I say this as a dude who loves functional programming, C# wasn't designed that way.

            Jeremy Falcon

            C Offline
            C Offline
            Chris Baker 2021
            wrote on last edited by
            #42

            Is "prefer composition over inheritance" functional? I'm not sure that it is. I think it's simply another OO approach to code re-use. Personally, I'm not against a certain level of inheritence, but I much prefer composing objects for functionality. I'm not sure if I'm missing something but what has a sealed class to do with immutability. A class is immutable if you can't change it's data, a sealed class means it can't be inherited from. I agree on the C# funtion point, it annoys me how everything needds to now be functional, I chose C# for it's OO properties, when I want to do funtional programming I'll use F#. (it'll be a pretty cold day in hell for that to happen though :laugh: )

            J 1 Reply Last reply
            0
            • S Steve Naidamast

              It seems like the sample the author provided is overkill for the passing of 3 simple variables. What is the purpose of any of this, I have no idea, except to make programming more confusing to the developer. What is wrong with passing a well-named variable as a primitive, especially with the hardware we work with today? In any event, I use Structs\Structures to pass data and Classes to execute methods. However, unless there was a specific reason to pass certain data in a Struct\Structure (ie: such as the need to pass all of the data, which makes up a particular Struct\Structure, passing such data as individual variables makes a lot more sense then wasting time on creating Structs\Structures to do so...

              Steve Naidamast Sr. Software Engineer Black Falcon Software, Inc. blackfalconsoftware@outlook.com

              R Offline
              R Offline
              raddevus
              wrote on last edited by
              #43

              To be fair, this was the beginning of the example, but the main thing you get is the compiler can check the type and warn you that you are using the wrong type. This also means the code is quite a bit more explicit about what it wants so a future dev who may have thought, "hmm....wonder why orig-dev wanted a double when a float would do" would be guided away from such a thought since there is a specific type. That's all I got. :)

              H 1 Reply Last reply
              0
              • J John Chadwell

                I once worked with a programmer 28 years ago who was approaching retirement. We worked on an accounts receivable/payable system together. He did all of the backend calculations in exactly the same format as step 1. If I remember correctly even his function names were single letters of the alphabet. I think I would have done at least step 2. I thought it was the simplest code you could possibly write. Back then there was no intellisense so we just documented our code thoroughly! I don't see any value in step 3 or 4. Seems like unnecessary layers of code.

                R Offline
                R Offline
                raddevus
                wrote on last edited by
                #44

                John Chadwell wrote:

                I don't see any value in step 3 or 4. Seems like unnecessary layers of code.

                You have much experience also and most likely that means you have developer discipline (do things right the first time so you don't shoot yourself in the foot later). Developer discipline doesn't seem like it is being taught in modern times -- probably influenced by dynamic languages like JavaScript which also encourage people to "type" code (not design it and write it). So, for this modern world i believe the movement is to "put the discipline in the code" so those who come after are "forced" to use it the way we have designed it. In the past, we would've read the legacy code and kept the parts that seem right. Also, this is just the latest shiny. :rolleyes:

                1 Reply Last reply
                0
                • L Leonardo Pessoa

                  Just curious where did you manage to get that book. Everywhere I search for it says it is pre-order to be delivered by the end of next month.

                  - Leonardo

                  R Offline
                  R Offline
                  raddevus
                  wrote on last edited by
                  #45

                  Leonardo Pessoa wrote:

                  Just curious where did you manage to get that book.

                  I'm a card-carrying member of oreilly.com -- ebooks from hundreds of publishers (manning, no starch, ms press, O'Reilly, Wiley, Addison-Wesley, -- to many to name) with 70,000 books available. Most of the time the ebook releases before the book even releases and it is available on oreilly.com You can try it for 10 days at this link (Create Your Trial: O'Reilly[^]) Disclaimer: I have no connection with oreilly and that is not an affiliate link. The access to all 70,000 books and X,XXX number of videos is unlimited. It's quite amazing. FYI - I've been a member of Oreilly since 2002 (when it only cost $10/month). It finally went to $19.95 / month and when they converted my account to their new system they let me grandfather into the old price $19.95 / month, but I know it is quite a bit more expensive now. Something like $39.95 / month or so.

                  1 Reply Last reply
                  0
                  • J Jeremy Falcon

                    raddevus wrote:

                    Oh, wait, Windows 3.1 Ini files[^] used that same format.

                    Ha ha ha ha. That's so true. In fact, one of the reasons I haven't really decided to learn Rust yet is it's _too_ opinionated.

                    Jeremy Falcon

                    N Offline
                    N Offline
                    Nelek
                    wrote on last edited by
                    #46

                    Jeremy Falcon wrote:

                    one of the reasons I haven't really decided to learn Rust yet is it's too opinionated.

                    But it is recommended by the big players... how can you say that?

                    M.D.V. ;) If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about? Help me to understand what I'm saying, and I'll explain it better to you Rating helpful answers is nice, but saying thanks can be even nicer.

                    J 1 Reply Last reply
                    0
                    • R Rick York

                      Quote:

                      This is also why old timers (who had to have a disciplined mindset so they didn't cause themselves problems) see a lot of the new stuff as just fluff.

                      I resemble that remark.

                      "They have a consciousness, they have a life, they have a soul! Damn you! Let the rabbits wear glasses! Save our brothers! Can I get an amen?"

                      N Offline
                      N Offline
                      Nelek
                      wrote on last edited by
                      #47

                      Additionally, not only old timers, people like me or d2k that have worked / work with limited resources (PLCs, Embedded...) can be counted in too

                      M.D.V. ;) If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about? Help me to understand what I'm saying, and I'll explain it better to you Rating helpful answers is nice, but saying thanks can be even nicer.

                      1 Reply Last reply
                      0
                      • J Juan Pablo Reyes Altamirano

                        I'm kind of against the whole "make your code more readable...at the cost of performance and efficiency". Programmers of the future who cannot understand the context of the past (and therefore the code) are of little concern. It might be that, as an engineer, my first stance is that all newcomers must be educated (a little) and eventually they should learn to educate themselves (a lot). It harkens back to the guilds...but, except for being exclusive, there wasn't very much else wrong with their educational system. So if someone wants to break OOP, they should write their own language and let everyone else be. I'm just happy I don't have to remember if that string of bytes was an integer or a floating point value (and I use the wrong mnemonic for multiplication). If you don't like inheritance, don't use it.

                        R Offline
                        R Offline
                        raddevus
                        wrote on last edited by
                        #48

                        I agree with your answer. Here's a reply I said to someone else that is about developer discipline related to this topic:

                        from Quote:[^]

                        You have much experience also and most likely that means you have developer discipline (do things right the first time so you don't shoot yourself in the foot later). Developer discipline doesn't seem like it is being taught in modern times -- probably influenced by dynamic languages like JavaScript which also encourage people to "type" code (not design it and write it). So, for this modern world i believe the movement is to "put the discipline in the code" so those who come after are "forced" to use it the way we have designed it. In the past, we would've read the legacy code and kept the parts that seem right.

                        Just as you said,

                        Juan Pablo Reyes Altamirano wrote:

                        my first stance is that all newcomers must be educated (a little) and eventually they should learn to educate themselves (a lot).

                        Unfortunately, there seem to be people moving into Software Development that just think they can start typing and produce a program.

                        N 1 Reply Last reply
                        0
                        • C charlieg

                          "I prefer a plain double, named well" I agree. Working in embedded systems where units are very important, I try to always include units at the end of the variable name. It causes a mental check when you start misusing the variable. But I also like a little more rigidity to avoid really stupid errors. I'm thinking of the Mars Climate Orbiter that lawn darted due to a units conversion issue. Errors like this boggle my mind. Every engineering system should be in metric. Period. If you want to convert something to English - that's a presentation issue, but I digress. This conversation is an excellent read.

                          Charlie Gilley “They who can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety.” BF, 1759 Has never been more appropriate.

                          N Offline
                          N Offline
                          Nelek
                          wrote on last edited by
                          #49

                          charlieg wrote:

                          Every engineering system should be in metric. Period. If you want to convert something to English - that's a presentation issue,

                          totally agree with that. And I add... Little vs Big Endian and similars. --> I have spent some time when looking for errors until I got used to make the check of inverting the significancy of the bytes when starting to work with two different systems I hadn't configured myself. Signed vs unsigned values (most significant bit as the sign) --> You get to 32646, 32647 and then you see -1, -2, -3... PLC String vs PC String --> PLC needs 2 bytes more "total length" and "used bytes" of current content (1st letter is String[2] position), having to transform to Array of Bytes to communicate ... there are a lot of "funny" error sources out there

                          M.D.V. ;) If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about? Help me to understand what I'm saying, and I'll explain it better to you Rating helpful answers is nice, but saying thanks can be even nicer.

                          1 Reply Last reply
                          0
                          • R raddevus

                            I agree with your answer. Here's a reply I said to someone else that is about developer discipline related to this topic:

                            from Quote:[^]

                            You have much experience also and most likely that means you have developer discipline (do things right the first time so you don't shoot yourself in the foot later). Developer discipline doesn't seem like it is being taught in modern times -- probably influenced by dynamic languages like JavaScript which also encourage people to "type" code (not design it and write it). So, for this modern world i believe the movement is to "put the discipline in the code" so those who come after are "forced" to use it the way we have designed it. In the past, we would've read the legacy code and kept the parts that seem right.

                            Just as you said,

                            Juan Pablo Reyes Altamirano wrote:

                            my first stance is that all newcomers must be educated (a little) and eventually they should learn to educate themselves (a lot).

                            Unfortunately, there seem to be people moving into Software Development that just think they can start typing and produce a program.

                            N Offline
                            N Offline
                            Nelek
                            wrote on last edited by
                            #50

                            raddevus wrote:

                            probably influenced by dynamic languages like JavaScript which also encourage people to "type" code (not design it and write it).

                            I can't even remember how many of my sequential programs were born on a DIN A2 paper where I draw everything with pencil, moving coins to simulate the value of the states and then playing with the possible permutations of the transistions. Specially when timing / synchronisation of different systems were needed.

                            M.D.V. ;) If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about? Help me to understand what I'm saying, and I'll explain it better to you Rating helpful answers is nice, but saying thanks can be even nicer.

                            1 Reply Last reply
                            0
                            • C Chris Baker 2021

                              Is "prefer composition over inheritance" functional? I'm not sure that it is. I think it's simply another OO approach to code re-use. Personally, I'm not against a certain level of inheritence, but I much prefer composing objects for functionality. I'm not sure if I'm missing something but what has a sealed class to do with immutability. A class is immutable if you can't change it's data, a sealed class means it can't be inherited from. I agree on the C# funtion point, it annoys me how everything needds to now be functional, I chose C# for it's OO properties, when I want to do funtional programming I'll use F#. (it'll be a pretty cold day in hell for that to happen though :laugh: )

                              J Offline
                              J Offline
                              Jeremy Falcon
                              wrote on last edited by
                              #51

                              Chris Baker 2021 wrote:

                              Is "prefer composition over inheritance" functional?

                              In functional programming that concept is talked about a lot. I mean a lot. Mainly because in purely functional programming you don't have inheritance. So, when I speak of composition, I'm specifically referring to functional composition. [Function composition (computer science) - Wikipedia](https://en.wikipedia.org/wiki/Function\_composition\_(computer\_science)) There's also object composition in OOP-land. Not really sure which one came first though...

                              Jeremy Falcon

                              K 1 Reply Last reply
                              0
                              • N Nelek

                                Jeremy Falcon wrote:

                                one of the reasons I haven't really decided to learn Rust yet is it's too opinionated.

                                But it is recommended by the big players... how can you say that?

                                M.D.V. ;) If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about? Help me to understand what I'm saying, and I'll explain it better to you Rating helpful answers is nice, but saying thanks can be even nicer.

                                J Offline
                                J Offline
                                Jeremy Falcon
                                wrote on last edited by
                                #52

                                Because I have a brain? :~:~

                                Jeremy Falcon

                                N 1 Reply Last reply
                                0
                                • J Jeremy Falcon

                                  Chris Baker 2021 wrote:

                                  Is "prefer composition over inheritance" functional?

                                  In functional programming that concept is talked about a lot. I mean a lot. Mainly because in purely functional programming you don't have inheritance. So, when I speak of composition, I'm specifically referring to functional composition. [Function composition (computer science) - Wikipedia](https://en.wikipedia.org/wiki/Function\_composition\_(computer\_science)) There's also object composition in OOP-land. Not really sure which one came first though...

                                  Jeremy Falcon

                                  K Offline
                                  K Offline
                                  k5054
                                  wrote on last edited by
                                  #53

                                  Jeremy Falcon wrote:

                                  Not really sure which one came first though

                                  I'm reasonably sure functional composition came first. I think Lisp predates the OO paradigm by quite a bit. And if I remember correctly, in the early days, Lisp was purely functional.

                                  Keep Calm and Carry On

                                  J 1 Reply Last reply
                                  0
                                  • K k5054

                                    Jeremy Falcon wrote:

                                    Not really sure which one came first though

                                    I'm reasonably sure functional composition came first. I think Lisp predates the OO paradigm by quite a bit. And if I remember correctly, in the early days, Lisp was purely functional.

                                    Keep Calm and Carry On

                                    J Offline
                                    J Offline
                                    Jeremy Falcon
                                    wrote on last edited by
                                    #54

                                    Thanks for that. That's what I thought too but wasn't sure.

                                    Jeremy Falcon

                                    1 Reply Last reply
                                    0
                                    • J Jeremy Falcon

                                      Because I have a brain? :~:~

                                      Jeremy Falcon

                                      N Offline
                                      N Offline
                                      Nelek
                                      wrote on last edited by
                                      #55

                                      Jeremy Falcon wrote:

                                      Because I have a brain and I know how to use it for that rare thing called critical thinking ? :~ :~

                                      FTFY (Sorry, I forgot the /s at the end of my previous comment)

                                      M.D.V. ;) If something has a solution... Why do we have to worry about?. If it has no solution... For what reason do we have to worry about? Help me to understand what I'm saying, and I'll explain it better to you Rating helpful answers is nice, but saying thanks can be even nicer.

                                      1 Reply Last reply
                                      0
                                      • J Jeremy Falcon

                                        Jon McKee wrote:

                                        Here's some pseudo-code:

                                        Got it. I didn't think of it in the context of replacing overloads. Just calling it that because if I where to code up your first two calls I'd at least have two strong (primitive-based) types that would differentiate the signature. I've been in JavaScript too long where that's not really done. :-O

                                        Jon McKee wrote:

                                        This effectively turns your function into a pure function that returns an impure Reader with that environment tuple as input and the result as output

                                        That one I gotta look into man. My understanding of pure functions is that all inputs are deterministic. So, not following how shifting parameter order changes that, since non-deterministic input is still going into the routine. Will check out the link though. Btw, thanks for knowing what you're talking about. Makes these conversations much better.

                                        Jeremy Falcon

                                        J Offline
                                        J Offline
                                        Jon McKee
                                        wrote on last edited by
                                        #56

                                        Jeremy Falcon wrote:

                                        Btw, thanks for knowing what you're talking about. Makes these conversations much better.

                                        Haha, thanks, but I don't think I deserve that quite yet. I'm still learning from people like Bartosz Milewski and Mark Seemann.

                                        Jeremy Falcon wrote:

                                        That one I gotta look into man. My understanding of pure functions is that all inputs are deterministic. So, not following how shifting parameter order changes that, since non-deterministic input is still going into the routine. Will check out the link though.

                                        This is an interesting topic that really broke my brain when I first ran into it. So, functions of more than one input have a lot of equivalent representations. For example, string -> int -> string can be seen as a function taking a string and returning a function of int -> string, or as a function of two inputs (the tuple (string, int)) that returns a string. The important part with regards to purity is binding order, or in other words "what is provided when". You can only act upon what is provided, so if arguments that are (potentially) impure are not provided yet, the function is still pure. For example:

                                        public bool saveToDatabase(Database db) => val => { db.save(val) };
                                        public bool saveToDatabase(Value val) => db => { db.save(val) };

                                        The first function is impure, the second function is pure. Why? They both take a Database and Value and return a Bool. Both are lazy (i.e. they only evaluate when all arguments are supplied). Well, because purity is a logical result of inputs and outputs. In the first example, if I apply the Database parameter, get the result function, then drop the database tables, then apply the Value, the operation fails. The partially applied function is impure. The database object that was already bound (partially-applied) was side-effected by the tables dropping. In the second example, no matter what I do after applying the Value, I can't create a situation where the Database is invalid AFTER applying it. The returned function itself is impure since we're side-effecting a database, but the original function is not, because there is no way to change the Database -> Bool that's returned. I might be off on some stuff, always learning, but that's my understanding of

                                        1 Reply Last reply
                                        0
                                        • R raddevus

                                          Just started reading this (just released) book, The C# Type System (no starch press)[^] and the first chapter is kind of blowing my mind. Step 1 Author starts out with the following example and says, "You must use better named variables so dev users know what they mean."

                                          Displacement(double t, double v, double s)
                                          {
                                          var x = v * s * Math.Cos(t);
                                          var y = v * s * Math.Sin(t) - 0.5 * 9.81 * Math.Pow(s, 2);
                                          return (x, y);
                                          }

                                          Yes, that makes sense. Step 2 Then he says, "Oh, you can add meaning with this new idea of named arguments so users don't have to remember order that they should be passed in."

                                          var result = Displacement(angle: .523, speed: 65, elapsedTime: 4);

                                          Ok, yes, that is good advice with the modern capabilities. Step 3 May Blow Your Mind He mentions that the code is still confusing because all three arguments are the same primitive type (double) and this leads into...

                                          From the book:

                                          Primitive Obsession code smell, which describes any code that has an overreliance on primitive types—that is, those types that are built into the language, such as int, double, and string.

                                          The solution is... Wrap All the Primitive Types In Structs 🤯🤯🤯🤯🤯

                                          public struct Angle
                                          {
                                          public double Size {get; set;}
                                          }
                                          public struct Speed
                                          {
                                          public double Amount {get; set;}
                                          }

                                          The Paradigm Has Shifted Now, when the user attempts to call the Displacement method the compiler will know that the argument type is wrong. Now, there's no way to pass the wrong value into the method, because the compiler will know the type. Wow, that is a very different paradigm!! Step 4 Is Immutability Now, make each struct immutable

                                          C Offline
                                          C Offline
                                          ChristianLavigne
                                          wrote on last edited by
                                          #57

                                          I would not say it's a new concept, DDD introduced the concept of value objects a while back. Strong typing a value is how many implement value objects in C#. The logical continuation for this concept should be: 1- Add validation, what is the specific range of value that are acceptable to your function. In your example, should you accept a speed of 62123.25? 2- Add units, is it always the same unit, or should you convert from different units? 3- Displacement, Angle, Speed are very vague, are we talking about vehicles on a public road? or a spacecraft? Maybe we should use VehicleSpeed instead? 4- Maybe VehicleSpeed should derive from a base Speed class so you don't repeat units and conversions all the time? But you could add validation of acceptable speed value for a vehicle? And we're back to the good old OOP. Should you calculate the Displacement in the VehicleSpeed class? I don't think so, this should be composition, but the encapsulation of the speed value, it's units and validation into a class is definitely desirable. It is a question of perspective. We tend to work with good enough, but if you want accuracy, I would debate that those are the things you NEED to do. The reasons why most of us don't go the Value Object route are: That's a lot of work. It takes time, we're in a hurry, it makes code base bigger, some would say more complex (I disagree). Is Primitive Obsession a code smell? I say YES! But are we willing and able to do everything that is required to REALLY fix it?

                                          Christian

                                          R 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups