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. General Programming
  3. C#
  4. Code Readability Poll

Code Readability Poll

Scheduled Pinned Locked Moved C#
csharpjavavisual-studiotutorial
29 Posts 10 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.
  • L Luc Pattyn

    Hi, IMO readability is very important; it helps in getting correct code that is easily maintained. Code generated and performance tend to be equal or better when you improve readability.

    LimitedAtonement wrote:

    Insets insets = obj as Insets; if (ReferenceEquals(insets, null)) return false; return ((top == insets.top) && (left == insets.left) && (bottom == insets.bottom) && (right == insets.right));

    I seldom use "is", often "as", hardly ever ReferenceEquals, hence:

    Insets insets=obj as Insets;
    return insets!=null && insets.top==top && insets.left=left && insets.bottom==bottom && insets.right==right;

    LimitedAtonement wrote:

    foreach (Point a in _gr_pts) { if (prev == Point.Empty || prev == a) { prev = a; continue; } g.DrawArc(_ap_pen, prev, a); prev = a; }

    isn't that just:

    foreach (Point a in _gr_pts) {
    if (prev!=Point.Empty && prev!=a) g.DrawArc(_ap_pen, prev, a);
    prev=a;
    }

    You may have noted: - I skip most irrelevant spaces - I use "East Coast brackets", i.e. they open without a new line - I use parentheses even when not needed to make sure about operator precedence but only if you could be mistaken. - I don't use negative if conditions, unless there is no else, or the negative block is much much shorter than the positive block (as in if (!OK) {throw} else {lots of code}) :)

    Luc Pattyn


    I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


    Local announcement (Antwerp region): Lange Wapper? Neen!


    E Offline
    E Offline
    Ennis Ray Lynch Jr
    wrote on last edited by
    #20

    East Coast Brackets, I like the term. I usually just call it Java-style but yours is more fun.

    Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. A man said to the universe: "Sir I exist!" "However," replied the universe, "The fact has not created in me A sense of obligation." --Stephen Crane

    L P 2 Replies Last reply
    0
    • N N a v a n e e t h

      LimitedAtonement wrote:

      I use ReferenceEquals, not `=='

      You don't get any advantage of doing this. Objects are by default compared by reference. Your first sharpified code looks good. IMO, readability of code is subjective. I'd write something like

      Insets insets = obj as Insets;
      return insets == null ? false : ((top == insets.top) && (left == insets.left)
      && (bottom == insets.bottom) && (right == insets.right));

      Navaneeth How to use google | Ask smart questions

      D Offline
      D Offline
      DaveyM69
      wrote on last edited by
      #21

      The only use I've found for ReferenceEquals is null checking in classes that overload operators == and !=.

      Dave
      Generic BackgroundWorker - My latest article!
      BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
      Why are you using VB6? Do you hate yourself? (Christian Graus)

      L 1 Reply Last reply
      0
      • P PIEBALDconsult

        N a v a n e e t h wrote:

        Martin Fowler

        But is he the only one who says that? I prefer to make my own decisions rather than follow the word of one author.

        G Offline
        G Offline
        Gideon Engelberth
        wrote on last edited by
        #22

        I've not read enough books (or this one by Fowler) to know if other people say it, but I would personally prefer to use multiple return points. The reality is that in some cases, such as when you have cleanup code that must run and a try-finally isn't appropriate, you may need to have only one return point. Other than that, there is little to no mental benefit to doing it either way. When I read this,

        bool bReturn;
        if (condition)
        {
        //do stuff
        bReturn = true;
        }
        else
        {
        //do stuff
        if (other condition)
        {
        // yet more stuff
        bReturn = false;
        }
        else
        {
        //blah blah blah
        bReturn = true;
        }
        }
        return bReturn;

        I still have to trace through the same amount of code to know what the function will return each case, whether I use single or multiple returns. Allowing multiple returns makes it obvious when some condition will stop execution of the method immediately. If I must have a single return, these conditions end up causing if-else statements that I have to trace to the end of the method before realizing that, "Hey, this condition stops the method." This will also usually end up leading to deeper nesting, which is more difficult to read.

        P 1 Reply Last reply
        0
        • E Ennis Ray Lynch Jr

          East Coast Brackets, I like the term. I usually just call it Java-style but yours is more fun.

          Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. A man said to the universe: "Sir I exist!" "However," replied the universe, "The fact has not created in me A sense of obligation." --Stephen Crane

          L Offline
          L Offline
          Luc Pattyn
          wrote on last edited by
          #23

          :thumbsup: I never associated my bracket placement with Java, and I remember having had similar east/west discussions when being an active Java developer. I checked a few Java books and found both styles in use. I've got the East Coast name long time ago, can't remember where from; and Google seems to have forgotten all about it too. But I continue to use and apply it. :)

          Luc Pattyn


          I only read code that is properly indented, and rendered in a non-proportional font; hint: use PRE tags in forum messages


          Local announcement (Antwerp region): Lange Wapper? Neen!


          1 Reply Last reply
          0
          • D DaveyM69

            The only use I've found for ReferenceEquals is null checking in classes that overload operators == and !=.

            Dave
            Generic BackgroundWorker - My latest article!
            BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
            Why are you using VB6? Do you hate yourself? (Christian Graus)

            L Offline
            L Offline
            LimitedAtonement
            wrote on last edited by
            #24

            Dave, But why would a class overload the == operator and not handle null itself? Do you see this often? I also thought this, but reconsidered recently. The reason I was using ReferenceEquals is because I don't want to have to check to see if it has an overload, then check to see if it returns properly with null. In Christ, Aaron Laws

            D 1 Reply Last reply
            0
            • L LimitedAtonement

              Dear Sirs, I just came across some code and changed it. I'm implementing the java Gridbag layout manager to a panel in C#, and in the Insets.Equals(object) code, the following could be found:

              if (obj instanceof Insets) {
              Insets insets = (Insets)obj;
              return ((top == insets.top) && (left == insets.left) &&
              (bottom == insets.bottom) && (right == insets.right));
              }
              return false;

              So I sharpified it:

              if (obj is Insets)
              {
              Insets insets = obj as Insets;
              return ((top == insets.top) && (left == insets.left) && (bottom == insets.bottom) && (right == insets.right));
              }
              return false;

              Then, almost compulsively, I modified it thus:

              Insets insets = obj as Insets;
              if (ReferenceEquals(insets, null)) return false;
              return ((top == insets.top) && (left == insets.left) && (bottom == insets.bottom) && (right == insets.right));

              I do this kind of thing ALL the time. I would like some comments on readability and efficiency. I guess to characterize the modification, I would say that I make it read more sequentially, without having to skip code (casting your eyes over code because in certain cases it would not be executed). Also, I'm crazy about conserving lines. I suppose that's because I'm not paid per line ;) . I always use the same-line `if' if I can, and if not, I resort to the no-brace 'if'. Which sometimes means...oh yeah, let me show a line I wrote the other day. Here's what I first wrote:

              foreach (Point a in _gr_pts)
              {
              if (prev == Point.Empty || prev == a)
              {
              prev = a;
              continue;
              }
              g.DrawArc(_ap_pen, prev, a);
              prev = a;
              }

              Then, I changed it to:

              foreach (Point a in _gr_pts)
              {
              if (prev == Point.Empty || prev == a)
              {
              prev =a;
              continue;
              }
              //Crazy, I know.
              g.DrawLine(_ap_pen, prev, prev = a);
              }

              I tried for a while to figure out how to get the braces out of the if statement...oh yeah, I just realized that this is possible: (I'm writing free-hand, so there may be typos...)

              foreach (Point a in _gr_pts)
              if (prev == Point.Empty || prev == a)
              {
              prev = a;
              continue;
              }
              else g.DrawLine(_ap_pen, prev, prev = a);

              I know some people swear by ALWAYS using braces in if, else, do, while, for, foreach statements, (and if I remember correctly, Visual studio has some option about including those compulsively) and I am a littl

              OriginalGriffO Offline
              OriginalGriffO Offline
              OriginalGriff
              wrote on last edited by
              #25

              I agree with the previous responses: readability is the important bit, and line spacing can seriously improve this - that is one reason why the "how to get an answer" bit at the top of the page stresses to use "code block" or <pre> tags to preserve formating. Three points: 1) Whatever the company style is, that is the one you use. Making it all look the same is the easiest way to make it all readable - because if the company style makes it all harder to read, then everyone will complain, and the company style will get changed. If everyone codes to a personal style, then everything gets muddled and harder to cope with. 2) My personal preference is always to use braces for a loop of conditional statement. That way, it is much harder to get it wrong when adding a second staement to a single line conditional. This is a lot easier nowadays, with VS etc auto indenting etc., but it is still easier to see what is going on. (It is similar to the reason why C++ accepts "if(A = B)" while C# wont - avoidance of potential problems.) 3) I also indent braces to match the statements in the functional block - I consider them to be a single indented statement in effect. I really hate the open brace at the end of an if statement, with it's matching brace indented. It looks clumsy and makes it difficult yo find matching braces by eye. But, if that is the company style, then I use it. They write the cheques...

              No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones

              "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
              "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

              P 1 Reply Last reply
              0
              • L LimitedAtonement

                Dave, But why would a class overload the == operator and not handle null itself? Do you see this often? I also thought this, but reconsidered recently. The reason I was using ReferenceEquals is because I don't want to have to check to see if it has an overload, then check to see if it returns properly with null. In Christ, Aaron Laws

                D Offline
                D Offline
                DaveyM69
                wrote on last edited by
                #26

                I meant within the class itself. Consider this int wrapper class (I've just written it out quickly so is very rough!) and compare the two different == operator overloads...

                public class MyIntWrapperClass : IEquatable<MyIntWrapperClass>
                {
                private int _Value;
                public MyIntWrapperClass(int value)
                {
                _Value = value;
                }

                // This method will throw a null reference exception if either parameter is null
                /\* public static bool operator ==(MyIntWrapperClass a, MyIntWrapperClass b)
                {
                    return a.\_Value == b.\_Value;
                }\*/
                
                // This method works if either is null. If both are null, returns true.
                public static bool operator ==(MyIntWrapperClass a, MyIntWrapperClass b)
                {
                    bool result = false;
                    if (!ReferenceEquals(a, null))
                    {
                        if (!ReferenceEquals(b, null))
                            result = a.\_Value == b.\_Value; // neither are null so compare \_Value
                        else
                            result = false; // b is null but a isn't
                    }
                    else
                        result = ReferenceEquals(b, null); // true if both are null
                    return result;
                }
                public static bool operator !=(MyIntWrapperClass a, MyIntWrapperClass b)
                {
                    return !(a == b);
                }
                public int Value
                {
                    get { return \_Value; }
                }
                public override bool Equals(object obj)
                {
                    return Equals(obj as MyIntWrapperClass);
                }
                public bool Equals(MyIntWrapperClass other)
                {
                    // using == overload
                    return this == other;
                }
                public override int GetHashCode()
                {
                    return \_Value; ;
                }
                public override string ToString()
                {
                    return \_Value.ToString();
                }
                

                }

                Dave
                Generic BackgroundWorker - My latest article!
                BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                Why are you using VB6? Do you hate yourself? (Christian Graus)

                modified on Wednesday, October 7, 2009 5:24 PM

                1 Reply Last reply
                0
                • E Ennis Ray Lynch Jr

                  East Coast Brackets, I like the term. I usually just call it Java-style but yours is more fun.

                  Need custom software developed? I do custom programming based primarily on MS tools with an emphasis on C# development and consulting. A man said to the universe: "Sir I exist!" "However," replied the universe, "The fact has not created in me A sense of obligation." --Stephen Crane

                  P Offline
                  P Offline
                  PIEBALDconsult
                  wrote on last edited by
                  #27

                  They're why I left Boston for California. :cool: (Not really.)

                  1 Reply Last reply
                  0
                  • OriginalGriffO OriginalGriff

                    I agree with the previous responses: readability is the important bit, and line spacing can seriously improve this - that is one reason why the "how to get an answer" bit at the top of the page stresses to use "code block" or <pre> tags to preserve formating. Three points: 1) Whatever the company style is, that is the one you use. Making it all look the same is the easiest way to make it all readable - because if the company style makes it all harder to read, then everyone will complain, and the company style will get changed. If everyone codes to a personal style, then everything gets muddled and harder to cope with. 2) My personal preference is always to use braces for a loop of conditional statement. That way, it is much harder to get it wrong when adding a second staement to a single line conditional. This is a lot easier nowadays, with VS etc auto indenting etc., but it is still easier to see what is going on. (It is similar to the reason why C++ accepts "if(A = B)" while C# wont - avoidance of potential problems.) 3) I also indent braces to match the statements in the functional block - I consider them to be a single indented statement in effect. I really hate the open brace at the end of an if statement, with it's matching brace indented. It looks clumsy and makes it difficult yo find matching braces by eye. But, if that is the company style, then I use it. They write the cheques...

                    No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced. This message is made of fully recyclable Zeros and Ones

                    P Offline
                    P Offline
                    PIEBALDconsult
                    wrote on last edited by
                    #28

                    Hear hear!

                    OriginalGriff wrote:

                    I consider them to be a single indented statement in effect

                    They are one statement -- a compound statement. At least that's how it is in C/C++, it seems the C# guys didn't like that concept for some reason.

                    1 Reply Last reply
                    0
                    • G Gideon Engelberth

                      I've not read enough books (or this one by Fowler) to know if other people say it, but I would personally prefer to use multiple return points. The reality is that in some cases, such as when you have cleanup code that must run and a try-finally isn't appropriate, you may need to have only one return point. Other than that, there is little to no mental benefit to doing it either way. When I read this,

                      bool bReturn;
                      if (condition)
                      {
                      //do stuff
                      bReturn = true;
                      }
                      else
                      {
                      //do stuff
                      if (other condition)
                      {
                      // yet more stuff
                      bReturn = false;
                      }
                      else
                      {
                      //blah blah blah
                      bReturn = true;
                      }
                      }
                      return bReturn;

                      I still have to trace through the same amount of code to know what the function will return each case, whether I use single or multiple returns. Allowing multiple returns makes it obvious when some condition will stop execution of the method immediately. If I must have a single return, these conditions end up causing if-else statements that I have to trace to the end of the method before realizing that, "Hey, this condition stops the method." This will also usually end up leading to deeper nesting, which is more difficult to read.

                      P Offline
                      P Offline
                      PIEBALDconsult
                      wrote on last edited by
                      #29

                      Yes, that example may well be a good place for multiple returns, but it may also simply be a bad piece of code too. My concern about having multiple returns is that it's too close to:

                      // do stuff

                      if ( exp ) goto end ;

                      // more stuff

                      end:
                      return whatever ;

                      In my opinion, multiple-return should be as _un_common as goto (that goes for continue and break (in loops*) as well). Multiple-return, continue, break, and goto are the right tool for some jobs, but they shouldn't be the developer's first choice. * Break and goto are required in switch statements X| .

                      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