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. The Lounge
  3. Expression bodies vs Good Old Fashioned Functions

Expression bodies vs Good Old Fashioned Functions

Scheduled Pinned Locked Moved The Lounge
visual-studio
27 Posts 20 Posters 0 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.
  • T trønderen

    Chris Maunder wrote:

    This makes me feel old because it reminds me of when we used to cram our code into as small a space as possible to handle 25 line screens.

    I do appreciate fitting an entire function/method on the screen, especially when I didn't write the code myself (or I wrote it so long ago that I no longer remember my line of thought), and need to read the code forwards and backwards and from both sides to understand the logic. With the 60+ line editor windows of today, you'd think that was a modes request. But with the modern style of always putting braces on separate lines, always put braces around even a simple assignment if it is e.g. an if clause (so the minimum number of lines for an if statement is 4). Some people even insist on always putting blank lines before and after any 'structured' statement (such as if/else, loops etc.), making 5 (or even 6, depending on context) the minimum line count for a simple 'if' ... Then you certainly won't be able to fit any large fraction of real-life methods in a 60 line editor window, or the hardcopy equivalent: One printed page. If you also forbid end-of-line comments, requiring comment to have their own lines (this has been the case in the majority of projects I have worked on, you frequently see 60 line windows "crammed with code" (according to the coding standard, but really containing no more than 5-8 statements. When I write code independent of such spacing requirements, I succeed in fitting maybe half of the function bodies below 60 lines. Then I e.g. put the opening brace at the end of the first line, and I accept un-braced single assignments as if/else clauses, following the condition or the 'else' keyword on the same line. A short (typical: half line) comment is written from col 70 of the line to which it applies, or col 90 if many source lines are long - I want the option to 'semi-ignore' the comments; when I know the code, comments should be there, but no clutter up the actual code statements. If I want people to review code written this style, I may print it double spaced (today, when most code reviews are made on-screen, I can just replace every newline with two newlines), to give other developers something in that 'airy' style that they want. No one ever remarks anything about blank lines around all statements, not just structured ones. That makes every statement clearly defined. It is considered making the code 'easier to read' (just like children's books usually has signifi

    M Offline
    M Offline
    Marc Clifton
    wrote on last edited by
    #9

    trønderen wrote:

    But with the modern style of always putting braces on separate lines, always put braces around even a simple assignment if it is e.g. an if clause (so the minimum number of lines for an if statement is 4). Some people even insist on always putting blank lines before and after any 'structured' statement (such as if/else, loops etc.),

    Yup. It's a code style I enforce with everyone I work with. It makes stuff a lot more readable. If seen crap like this: some very long long of code if (foo == null) return; another very long line of code And I've completely missed the return, not to mention that there should always be a single point of return. Code should be readable and organized, and blank lines is the best way to do that given the tools we have. Now, personally, I don't think higher level functions should ever even have code in them except to call lower level functions. But trying to enforce that behavior on people (including myself often enough) is asking too much. My 2c!

    Latest Articles:
    Your one-stop guide for API and web-client Form, XHR, Blob, and Drag & Drop File/Data Uploading

    S 1 Reply Last reply
    0
    • M Marc Clifton

      trønderen wrote:

      But with the modern style of always putting braces on separate lines, always put braces around even a simple assignment if it is e.g. an if clause (so the minimum number of lines for an if statement is 4). Some people even insist on always putting blank lines before and after any 'structured' statement (such as if/else, loops etc.),

      Yup. It's a code style I enforce with everyone I work with. It makes stuff a lot more readable. If seen crap like this: some very long long of code if (foo == null) return; another very long line of code And I've completely missed the return, not to mention that there should always be a single point of return. Code should be readable and organized, and blank lines is the best way to do that given the tools we have. Now, personally, I don't think higher level functions should ever even have code in them except to call lower level functions. But trying to enforce that behavior on people (including myself often enough) is asking too much. My 2c!

      Latest Articles:
      Your one-stop guide for API and web-client Form, XHR, Blob, and Drag & Drop File/Data Uploading

      S Offline
      S Offline
      Slacker007
      wrote on last edited by
      #10

      Marc Clifton wrote:

      there should always be a single point of return

      that is debatable, IMHO. I like to fail fast. fail early. which is ReSharper's default setting. return now and not 25 lines of code later. Another dev I work with likes to have one return statement for everything, just like you. I also like to reduce nesting If statements. Some devs love 50,000 nested If statements. No thank you.

      T P J 3 Replies Last reply
      0
      • G Gary R Wheeler

        A lot of the recent changes in the C# language seem to be syntactic sugar. It's nice when writing code, but it's another bit of shorthand my poor old brain has to translate to the long form before I understand what the code is doing.

        Software Zen: delete this;

        S Offline
        S Offline
        Slacker007
        wrote on last edited by
        #11

        IMHO, its all in an effort to write 25,000 lines of code in one line of code, using this magical voodoo syntax. readability? sure, if you are Satan and can read the ancient angelic scripts.

        1 Reply Last reply
        0
        • S Slacker007

          Marc Clifton wrote:

          there should always be a single point of return

          that is debatable, IMHO. I like to fail fast. fail early. which is ReSharper's default setting. return now and not 25 lines of code later. Another dev I work with likes to have one return statement for everything, just like you. I also like to reduce nesting If statements. Some devs love 50,000 nested If statements. No thank you.

          T Offline
          T Offline
          trønderen
          wrote on last edited by
          #12

          Slacker007 wrote:

          Marc Clifton wrote:there should always be a single point of return

          I can accept your principle, but honestly: I do not really see the advantage of coding 'goto returnfromfunction' rather than 'return' (obviously, there is then a 'returnfromfunction' label at the end of the function). If you do not recognize the 'return', then why would you more easily recognize 'goto returnfromfunction'? This is probably related to

          Slacker007 wrote:

          I also like to reduce nesting If statements. Some devs love 50,000 nested If statements. No thank you.

          Way back in my student days, there was an article in one of the ACM publications, it may have been Communications, but more likely SIGPlan Notices, entitled "The rightward migration of source code", discussing the consequences of without question accepting such dogmas as 'single point of return'. The consequences of 'single point of return' may depend strongly on which other coding 'rules' are enforced. I have frequently seen 'single exit point' together with 'break out of loops is forbidden'. So if you detect a fatal error at iteration 2 of a 100 iteration loop, you cannot terminate, but must set an error flag, tested in every one of the subsequent 98 iterations in a 'if (!errorterminate) ... If 'break' is forbidden, so you are not allowed to write a 'do {} while (false);' with, say, every parameter check either continues, or breaks out, then you cold cause the exit, say, on an invalid parameter, by creating such a one-iteration loop, with an exception handler. Sometimes, managers who strongly object to break statements willingly accept raise statements. Of course this makes next to zero sense. But lots of programmers who dislike explicit statements seem to fully accept exception handling to do the same thing. One obvious magic - the break or return - is forbidden, while something obscure, handled independently from each side, is fully accepted. I do not see why. Like Slacker007, I fight rightward migration. Allowing multiple return points is part of the fight.

          1 Reply Last reply
          0
          • S Slacker007

            Marc Clifton wrote:

            there should always be a single point of return

            that is debatable, IMHO. I like to fail fast. fail early. which is ReSharper's default setting. return now and not 25 lines of code later. Another dev I work with likes to have one return statement for everything, just like you. I also like to reduce nesting If statements. Some devs love 50,000 nested If statements. No thank you.

            P Offline
            P Offline
            Peter Adam
            wrote on last edited by
            #13

            Multiple returns are syntactic sugar for goto.

            1 Reply Last reply
            0
            • C Chris Maunder

              I'm browsing through the labyrinth of MSDN and I am seeing more and more use of expression bodies. eg

              public MyObject(string name, string data) =>
              (_name, _data) = (name, data);

              as opposed to

              public MyObject(string name, string data)
              {
              _name = name;
              _data= data;
              }

              This makes me feel old because it reminds me of when we used to cram our code into as small a space as possible to handle 25 line screens. Maybe this is like skinny jeans: in a year's time it'll all be over.

              cheers Chris Maunder

              D Offline
              D Offline
              dan sh
              wrote on last edited by
              #14

              I would prefer the second option. Back when I was in school, we were taught that we should not initialize variables in single line to improve readability. Somehow that has stuck until now. I do not see any gain from writing code perspective in option 1. I could have a wrong order and mess things up if arguments are of same datatype. In multiline set up I feel I am less prone to make that mistake.

              "It is easy to decipher extraterrestrial signals after deciphering Javascript and VB6 themselves.", ISanti[^]

              1 Reply Last reply
              0
              • G Gary R Wheeler

                A lot of the recent changes in the C# language seem to be syntactic sugar. It's nice when writing code, but it's another bit of shorthand my poor old brain has to translate to the long form before I understand what the code is doing.

                Software Zen: delete this;

                L Offline
                L Offline
                Leo56
                wrote on last edited by
                #15

                Agreed! And we all know too much sugar is bad for you.... :|

                1 Reply Last reply
                0
                • C Chris Maunder

                  I'm browsing through the labyrinth of MSDN and I am seeing more and more use of expression bodies. eg

                  public MyObject(string name, string data) =>
                  (_name, _data) = (name, data);

                  as opposed to

                  public MyObject(string name, string data)
                  {
                  _name = name;
                  _data= data;
                  }

                  This makes me feel old because it reminds me of when we used to cram our code into as small a space as possible to handle 25 line screens. Maybe this is like skinny jeans: in a year's time it'll all be over.

                  cheers Chris Maunder

                  M Offline
                  M Offline
                  MadGerbil
                  wrote on last edited by
                  #16

                  Two rules of programming: 1: Use a ton of free, poorly maintained libraries because they're free and solve trivial non-problems so that bugs can be introduced every time you upgrade one block in the jenga tower you've written. 2: Use interfaces, inheritance, partial classes, asynchronous programming and lambda expressions to solve trivial problems so the code cannot be read in a single pass. The worst person on your team is the guy who is always finding new and cool stuff. He's an ass. Fire him now.

                  R 2 Replies Last reply
                  0
                  • D David ONeil

                    Did you used to be active on the C++ Builder groups? I remember long ago I was working through code styles and one person had the following:

                    void someFunction() {
                    if (something) {
                    doThings();
                    }
                    }

                    The final hanging brace bothered me for a long time, but I adopted everything else because it had the greatest beauty and logical consistency of all the styles I'd seen. As I used it more and more I finally reached a day where the logic of the final hanging brace became perfectly clear, and I adopted it and never looked back! I agree with all the points you made - it is so much easier to grok the code when it has internal beauty, and doesn't take up tons of space!

                    The Science of King David's Court | Object Oriented Programming with C++

                    R Offline
                    R Offline
                    Rich Shealer
                    wrote on last edited by
                    #17

                    That is the style I use except the closing brace closes below the opening keyword. I find the lone brace usually helps me to easily find where the braced sections end easily. Though for procedures with a lot of conditions, at the end the braces tend to run together. I also only use two spaces per indent. It saves a lot of horizontal space.

                    void someFunction() {
                    if (something) {
                    DoThings();
                    }
                    else {
                    DoDifferentThing();
                    }
                    }

                    D J 2 Replies Last reply
                    0
                    • M MadGerbil

                      Two rules of programming: 1: Use a ton of free, poorly maintained libraries because they're free and solve trivial non-problems so that bugs can be introduced every time you upgrade one block in the jenga tower you've written. 2: Use interfaces, inheritance, partial classes, asynchronous programming and lambda expressions to solve trivial problems so the code cannot be read in a single pass. The worst person on your team is the guy who is always finding new and cool stuff. He's an ass. Fire him now.

                      R Offline
                      R Offline
                      rjmoses
                      wrote on last edited by
                      #18

                      I'd triple up-tick your comment if I could.

                      1 Reply Last reply
                      0
                      • M MadGerbil

                        Two rules of programming: 1: Use a ton of free, poorly maintained libraries because they're free and solve trivial non-problems so that bugs can be introduced every time you upgrade one block in the jenga tower you've written. 2: Use interfaces, inheritance, partial classes, asynchronous programming and lambda expressions to solve trivial problems so the code cannot be read in a single pass. The worst person on your team is the guy who is always finding new and cool stuff. He's an ass. Fire him now.

                        R Offline
                        R Offline
                        rjmoses
                        wrote on last edited by
                        #19

                        I have a very, very simple rule: I want to be able to read AND understand both the intent and method of a piece of code in a few minutes. Anything less than that causes confusion and errors. And I'm getting to old and cranky to waste time looking at undecipherable code.

                        1 Reply Last reply
                        0
                        • R Rich Shealer

                          That is the style I use except the closing brace closes below the opening keyword. I find the lone brace usually helps me to easily find where the braced sections end easily. Though for procedures with a lot of conditions, at the end the braces tend to run together. I also only use two spaces per indent. It saves a lot of horizontal space.

                          void someFunction() {
                          if (something) {
                          DoThings();
                          }
                          else {
                          DoDifferentThing();
                          }
                          }

                          D Offline
                          D Offline
                          David ONeil
                          wrote on last edited by
                          #20

                          If it works for you, good! I used it in the past, until the logic of all indents being at their own level became clear o me.

                          The Science of King David's Court | Object Oriented Programming with C++

                          1 Reply Last reply
                          0
                          • C Chris Maunder

                            I'm browsing through the labyrinth of MSDN and I am seeing more and more use of expression bodies. eg

                            public MyObject(string name, string data) =>
                            (_name, _data) = (name, data);

                            as opposed to

                            public MyObject(string name, string data)
                            {
                            _name = name;
                            _data= data;
                            }

                            This makes me feel old because it reminds me of when we used to cram our code into as small a space as possible to handle 25 line screens. Maybe this is like skinny jeans: in a year's time it'll all be over.

                            cheers Chris Maunder

                            E Offline
                            E Offline
                            englebart
                            wrote on last edited by
                            #21

                            Trying to evolve to TypeScript constructors? I do not see where it saves any typing in the current form. If an IDE gives you that as a default completion where you do not need to type anything, then I could see accepting it. Less clear to my old eye as well.

                            1 Reply Last reply
                            0
                            • T trønderen

                              k5054 wrote:

                              And 80 (or possibly 132) columns.

                              At work, we were developing a new company C coding standard. One of the proposals was to limit source code lines to 80 cols. Our project manager immediately declared that he would grant an unconditional exemption to that rule: We had rules for how to name #define constants that lead to identifiers exceeding 80 chars. So the 'max 80 col lines' did not make it into the standard. We retained the rules for how to name #define constants. Many times later, I have questioned whether we retained the right rules. Maybe we should have accepted 'max 80 col' and rather revised the naming rules.

                              M Offline
                              M Offline
                              Mark Whybird
                              wrote on last edited by
                              #22

                              You got some kind of issue with integerToCountFromOneToOneHundredInForLoopInIfMyValueIsTrueBranckOfMethodFooOfObjectBarInClassBas? I suppose you think it should have been called i or something, you Philistine!

                              1 Reply Last reply
                              0
                              • C Chris Maunder

                                I'm browsing through the labyrinth of MSDN and I am seeing more and more use of expression bodies. eg

                                public MyObject(string name, string data) =>
                                (_name, _data) = (name, data);

                                as opposed to

                                public MyObject(string name, string data)
                                {
                                _name = name;
                                _data= data;
                                }

                                This makes me feel old because it reminds me of when we used to cram our code into as small a space as possible to handle 25 line screens. Maybe this is like skinny jeans: in a year's time it'll all be over.

                                cheers Chris Maunder

                                R Offline
                                R Offline
                                Ryan Peden
                                wrote on last edited by
                                #23

                                I kind of like it in this case! If you're only assigning things passed in via the constructor I don't see a ton of value in spacing things out. But I think it's a matter of using expression bodies in the right place and not overdoing it. I often see Visual Studio suggesting I switch to an expression body and when I try it, the code ends up uglier. I think they're useful when they enhance readability, for example in indexers or property getters and setters:

                                public string this[int i]
                                {
                                get => types[i];
                                set => types[i] = value;
                                }

                                or

                                public string Name
                                {
                                get => locationName;
                                set => locationName = value;
                                }

                                1 Reply Last reply
                                0
                                • C Chris Maunder

                                  I'm browsing through the labyrinth of MSDN and I am seeing more and more use of expression bodies. eg

                                  public MyObject(string name, string data) =>
                                  (_name, _data) = (name, data);

                                  as opposed to

                                  public MyObject(string name, string data)
                                  {
                                  _name = name;
                                  _data= data;
                                  }

                                  This makes me feel old because it reminds me of when we used to cram our code into as small a space as possible to handle 25 line screens. Maybe this is like skinny jeans: in a year's time it'll all be over.

                                  cheers Chris Maunder

                                  M Offline
                                  M Offline
                                  Matt McGuire
                                  wrote on last edited by
                                  #24

                                  I'm hoping it not a long term trend, or the debugging tools have to get better. I can put a break on a function and inspect the variables as I step through the code, it gets a little trickier on expression bodies especially when working with large collections or arrays :( I like the cleanliness of expression bodies, but at the same time sub expressions do tend to muddy up the readability. Someone correct me if I'm mistaken, but once the code is compiled a expression body just gets translated into a function (like) code structure which is just a jump to address and then return as seen by the processer. I'll admit I've not looked into what happens too much under the hood with expression bodies in dotnet.

                                  1 Reply Last reply
                                  0
                                  • T trønderen

                                    Chris Maunder wrote:

                                    This makes me feel old because it reminds me of when we used to cram our code into as small a space as possible to handle 25 line screens.

                                    I do appreciate fitting an entire function/method on the screen, especially when I didn't write the code myself (or I wrote it so long ago that I no longer remember my line of thought), and need to read the code forwards and backwards and from both sides to understand the logic. With the 60+ line editor windows of today, you'd think that was a modes request. But with the modern style of always putting braces on separate lines, always put braces around even a simple assignment if it is e.g. an if clause (so the minimum number of lines for an if statement is 4). Some people even insist on always putting blank lines before and after any 'structured' statement (such as if/else, loops etc.), making 5 (or even 6, depending on context) the minimum line count for a simple 'if' ... Then you certainly won't be able to fit any large fraction of real-life methods in a 60 line editor window, or the hardcopy equivalent: One printed page. If you also forbid end-of-line comments, requiring comment to have their own lines (this has been the case in the majority of projects I have worked on, you frequently see 60 line windows "crammed with code" (according to the coding standard, but really containing no more than 5-8 statements. When I write code independent of such spacing requirements, I succeed in fitting maybe half of the function bodies below 60 lines. Then I e.g. put the opening brace at the end of the first line, and I accept un-braced single assignments as if/else clauses, following the condition or the 'else' keyword on the same line. A short (typical: half line) comment is written from col 70 of the line to which it applies, or col 90 if many source lines are long - I want the option to 'semi-ignore' the comments; when I know the code, comments should be there, but no clutter up the actual code statements. If I want people to review code written this style, I may print it double spaced (today, when most code reviews are made on-screen, I can just replace every newline with two newlines), to give other developers something in that 'airy' style that they want. No one ever remarks anything about blank lines around all statements, not just structured ones. That makes every statement clearly defined. It is considered making the code 'easier to read' (just like children's books usually has signifi

                                    J Offline
                                    J Offline
                                    James Lonero
                                    wrote on last edited by
                                    #25

                                    Now I have a better understanding of the reasoning behind the brace wars back in the old C days. Whether to place the opening brace on the same line as the if/for/while/switch/function or on the next line. Most were of the next line camp and preferred it to make the code look more elegant and increase the lines of code. And also, it looked good if you had a 'pretty printer' utility for your code. But, when only having 25 lines per screen, that was limiting, and you wanted you screen real estate to be populated with meaningful lines of code rather than entry and exit braces fluff.

                                    1 Reply Last reply
                                    0
                                    • R Rich Shealer

                                      That is the style I use except the closing brace closes below the opening keyword. I find the lone brace usually helps me to easily find where the braced sections end easily. Though for procedures with a lot of conditions, at the end the braces tend to run together. I also only use two spaces per indent. It saves a lot of horizontal space.

                                      void someFunction() {
                                      if (something) {
                                      DoThings();
                                      }
                                      else {
                                      DoDifferentThing();
                                      }
                                      }

                                      J Offline
                                      J Offline
                                      James Lonero
                                      wrote on last edited by
                                      #26

                                      Another offshoot of the brace wars.

                                      1 Reply Last reply
                                      0
                                      • S Slacker007

                                        Marc Clifton wrote:

                                        there should always be a single point of return

                                        that is debatable, IMHO. I like to fail fast. fail early. which is ReSharper's default setting. return now and not 25 lines of code later. Another dev I work with likes to have one return statement for everything, just like you. I also like to reduce nesting If statements. Some devs love 50,000 nested If statements. No thank you.

                                        J Offline
                                        J Offline
                                        James Lonero
                                        wrote on last edited by
                                        #27

                                        I have learned to agree with you on that. In the old days, I was taught that you write

                                        int f(MyObject obj)
                                        {
                                            int result = 0;
                                            MyObject2 obj2 = obj.FunctionA();
                                            if (obj2 != null)
                                            {
                                                MyObject3 obj3 = obj2.FunctionB();
                                                if (obj3 != null) 
                                                {
                                                    MyObject4 obj4 = obj3.FunctionC();
                                                    if (obj4 != null)
                                                    {
                                                        result = obj4.value;
                                                    }
                                                }
                                            }
                                            return result;
                                        }
                                        

                                        Now I find it easier to understand when I write

                                        int f(MyObject obj)
                                        {
                                            MyObject2 obj2 = obj.FunctionA();
                                            if (null == obj2)
                                            {
                                                return 0;
                                            }
                                        
                                            MyObject3 obj3 = obj2.FunctionB();
                                            if (null == obj3) 
                                            {
                                                return 0;
                                            }
                                        
                                            MyObject4 obj4 = obj3.FunctionC();
                                            if (obj4 != null) 
                                            {
                                                return 0;
                                            }
                                        
                                            result = obj4.value;
                                        }
                                        

                                        This is easier to understand than having the code march off the right side of the page and removes exceptions to normal processing early on without cluttering the main part of the code. Since I write software application applications, I'm normally have these types of code where

                                        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