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. Coding Standards

Coding Standards

Scheduled Pinned Locked Moved The Lounge
helpquestionworkspace
51 Posts 27 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.
  • W wout de zeeuw

    Ideally, every coding standard rule will have a rationale as to what benefit the rule brings. Variables should be defined as close to their first use as possible in general. If they are re-used several times, I always redeclare them every time in a new {} block within the method to not accidentally re-use a value from the previous block. Those comments are silly, you are exaggerating there, right? If not, the comments are such that you could possibly generate them with a tool (think of e.g. GhostDoc). It would even be a nice exercise to write such a tool! :) Edit: code comment should mostly explain why something is being done, not what is being done, because the what is mostly self explanatory, or can be found out using debugging. The why is very hard to find out.

    Wout

    M Offline
    M Offline
    Matt U
    wrote on last edited by
    #19

    I'm not joking in the least about the commenting standards. If it were allowed, I would paste an untouched, large block of code, or even share a file, just to put it out there.

    djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

    1 Reply Last reply
    0
    • M Matt U

      Coding standards with my employer are strange based on everything I've ever known, everything I've ever read, everything I've ever been told. They are set in their ways and I don't think anything could change their mind on these internal standards. Here are a few: 1. Excessive commenting -- practically every operation in code has a preceding comment. No matter how descriptive the code is, and no matter how simple the operation may be, there is a comment such as the following:

      /// /// This is an addition method.
      ///
      private int Add(int a, int b)
      {
      // Add the two numbers and return the result
      return a + b;
      }

      private void Process(MyFileObj myFile)
      {
      // Make sure the parameter is not 'null'
      if (myFile != null)
      {
      // Strip all the bad data from the object
      myFile.StripBadData();

          // Add the file to the collection
          \_myFileCollection.Add(myFile);
      }
      

      }

      2. Variable declaration -- this may not be so bad, so please correct me if I'm wrong. But I've never seen it done this way. According to their standards, all variables in a method must be initially declared at the top of the method, before anything else is done:

      private MyClass MyMethod()
      {
      int count = 0;
      MyClass someObj = null;

      // Iterate over the file collection
      foreach (MyFileObj file in \_myFileCollection)
      {
          // Make sure the file's name is not longer than 20 characters
          if(file.Name.Length <= 20)
          {
              // Copy the file to a new location
              file.CopyTo(@"C:\\SomePath\\" + file.Name);
      
              // Increment the counter
              count++;
          }
      }
      
      // A lot of other code
      // ...
      
      // Setup the class that will be returned
      someObj = new MyClass();
      someObj.FileCount = count;
      
      // Return the class that has the data we need
      return someObj;
      

      }

      The "MyClass someObj" isn't referenced until the very end of the method. Why should it be declared at the very top of the method? Maybe I'm missing something? I've never declared objects until the time I need them. These are just a few examples. There are some other things I don't really agree with, but I can't change any of them.

      djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

      R Offline
      R Offline
      Ravi Bhavnani
      wrote on last edited by
      #20

      I find both these standards odd. I've been using RCG (Ravi's Commenting Guidelines™) for 20 years and they have served me and my teammates well.  The guidelines are simple:

      1. Strip out all code within blocks (except block delimiters - i.e. if, do, for, while and switch code boundaries).
      2. The remaining code and comments should clearly represent the method's psuedocode.  If it doesn't, you need to add comments.

      The coding standard about declaring all local variables at the start of a method is complete nonsense, IMHO.  To maximize readability, local variables should be declared on first use within the block to which they're scoped. This would cause me to rewrite your example method thusly:

      /// /// Performs a file copy (a better comment is required here).
      ///
      /// The result of the operation.
      private MyClass MyMethod()
      {
      // For each file whose name is less than 21 chars...
      int count = 0;
      foreach (MyFileObj file in _myFileCollection) {
      if (file.Name.Length <= 20) {
      // Copy it to the new location
      file.CopyTo(@"C:\SomePath\" + file.Name);
      count++;
      }
      }

      // A lot of other code
      // ...
      
      // Return result
      MyClass someObj = new MyClass();
      someObj.FileCount = count;
      return someObj;
      

      }

      /ravi

      My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

      M 1 Reply Last reply
      0
      • R Ravi Bhavnani

        I find both these standards odd. I've been using RCG (Ravi's Commenting Guidelines™) for 20 years and they have served me and my teammates well.  The guidelines are simple:

        1. Strip out all code within blocks (except block delimiters - i.e. if, do, for, while and switch code boundaries).
        2. The remaining code and comments should clearly represent the method's psuedocode.  If it doesn't, you need to add comments.

        The coding standard about declaring all local variables at the start of a method is complete nonsense, IMHO.  To maximize readability, local variables should be declared on first use within the block to which they're scoped. This would cause me to rewrite your example method thusly:

        /// /// Performs a file copy (a better comment is required here).
        ///
        /// The result of the operation.
        private MyClass MyMethod()
        {
        // For each file whose name is less than 21 chars...
        int count = 0;
        foreach (MyFileObj file in _myFileCollection) {
        if (file.Name.Length <= 20) {
        // Copy it to the new location
        file.CopyTo(@"C:\SomePath\" + file.Name);
        count++;
        }
        }

        // A lot of other code
        // ...
        
        // Return result
        MyClass someObj = new MyClass();
        someObj.FileCount = count;
        return someObj;
        

        }

        /ravi

        My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

        M Offline
        M Offline
        Matt U
        wrote on last edited by
        #21

        That's an interesting concept, and I may try and adapt that style of commenting. It's simple to understand and I believe it may work nicely. Even if they don't want to change it, I may adapt it for my personal coding standards. Thanks for the input, Ravi. :)

        djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

        1 Reply Last reply
        0
        • M Matt U

          Coding standards with my employer are strange based on everything I've ever known, everything I've ever read, everything I've ever been told. They are set in their ways and I don't think anything could change their mind on these internal standards. Here are a few: 1. Excessive commenting -- practically every operation in code has a preceding comment. No matter how descriptive the code is, and no matter how simple the operation may be, there is a comment such as the following:

          /// /// This is an addition method.
          ///
          private int Add(int a, int b)
          {
          // Add the two numbers and return the result
          return a + b;
          }

          private void Process(MyFileObj myFile)
          {
          // Make sure the parameter is not 'null'
          if (myFile != null)
          {
          // Strip all the bad data from the object
          myFile.StripBadData();

              // Add the file to the collection
              \_myFileCollection.Add(myFile);
          }
          

          }

          2. Variable declaration -- this may not be so bad, so please correct me if I'm wrong. But I've never seen it done this way. According to their standards, all variables in a method must be initially declared at the top of the method, before anything else is done:

          private MyClass MyMethod()
          {
          int count = 0;
          MyClass someObj = null;

          // Iterate over the file collection
          foreach (MyFileObj file in \_myFileCollection)
          {
              // Make sure the file's name is not longer than 20 characters
              if(file.Name.Length <= 20)
              {
                  // Copy the file to a new location
                  file.CopyTo(@"C:\\SomePath\\" + file.Name);
          
                  // Increment the counter
                  count++;
              }
          }
          
          // A lot of other code
          // ...
          
          // Setup the class that will be returned
          someObj = new MyClass();
          someObj.FileCount = count;
          
          // Return the class that has the data we need
          return someObj;
          

          }

          The "MyClass someObj" isn't referenced until the very end of the method. Why should it be declared at the very top of the method? Maybe I'm missing something? I've never declared objects until the time I need them. These are just a few examples. There are some other things I don't really agree with, but I can't change any of them.

          djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

          D Offline
          D Offline
          Dennis E White
          wrote on last edited by
          #22

          When Code Complete was first published there was actually a chapter dedicated to this. The idea was that you would design your code with comments. It would go something along these lines... step 1 was to write comments of how the code would work.

          // an add method to add two integers
          // add the two integers and return the result

          You could in theory then have a review meeting of just those comments. This in turn causes you to get a better understanding of what you are trying achieve. step 2 was to add the code

          // an add method to add two integers
          -(int)add: (int)a b:(int)b
          {
          // add the two integers and return the result
          return a+b;
          }

          More importantly is that if you did step 1 properly then in theory someone else could do step 2 just by implementing your comments. we did something similar at my first programming job out of college (20++ years ago) and it helped in slowing things down to get you thinking before writing. I don't follow it to the same detail today but I do find at times when I am working on something a bit complex to follow similar steps. think of it like a mental dump of what you are thinking at the time you write the code. we have all asked the question when reading someone else's code.

          What were they thinking when they wrote this piece of code?

          I would take the time to learn more of how and where these standards started. there is generally a wisdom or history behind things like this and knowing that can help more than the actual standard itself.

          you want something inspirational??

          M 1 Reply Last reply
          0
          • D Dennis E White

            When Code Complete was first published there was actually a chapter dedicated to this. The idea was that you would design your code with comments. It would go something along these lines... step 1 was to write comments of how the code would work.

            // an add method to add two integers
            // add the two integers and return the result

            You could in theory then have a review meeting of just those comments. This in turn causes you to get a better understanding of what you are trying achieve. step 2 was to add the code

            // an add method to add two integers
            -(int)add: (int)a b:(int)b
            {
            // add the two integers and return the result
            return a+b;
            }

            More importantly is that if you did step 1 properly then in theory someone else could do step 2 just by implementing your comments. we did something similar at my first programming job out of college (20++ years ago) and it helped in slowing things down to get you thinking before writing. I don't follow it to the same detail today but I do find at times when I am working on something a bit complex to follow similar steps. think of it like a mental dump of what you are thinking at the time you write the code. we have all asked the question when reading someone else's code.

            What were they thinking when they wrote this piece of code?

            I would take the time to learn more of how and where these standards started. there is generally a wisdom or history behind things like this and knowing that can help more than the actual standard itself.

            you want something inspirational??

            M Offline
            M Offline
            Matt U
            wrote on last edited by
            #23

            Very informative. I appreciate it. As previously stated, my manager has extensive experience with multiple languages. And I'm almost certain it came from quite a long while ago. Also, they have a lot of contractors (myself included) come through here. So I'm thinking the extensive commenting style may be in place to more or less protect future contractors and such from becoming easily confused. Who knows, I could be wrong.

            djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

            1 Reply Last reply
            0
            • G Gregory Gadow

              I am the programming department of my company, and I still adhere to point 2 almost religiously. It goes with the idea of self-documenting code: if I come to a piece I'd written some time earlier and need to remember the type and initialized value for PersonId, I know where to look. I can look at the top of the code block much faster than I can pull up and use a search tool. As for point 1, I find that commenting "obvious" code is useful: what may be obvious today, when writing it, will not be so obvious when I have to revise the code four years later. My personal standard, though, is to make comments meaningful.

              M Offline
              M Offline
              Member 10088171
              wrote on last edited by
              #24

              The problem with comments is that they are often not changed in sync with code updates. Another one is that meaningful comment today is often meaningless tomorrow. I am trying my best creating meaningful comments and this is an art and continuous learning. Similarly I like important declarations at the top but I declare "utility" variables at the point of use.

              J 1 Reply Last reply
              0
              • M Matt U

                Coding standards with my employer are strange based on everything I've ever known, everything I've ever read, everything I've ever been told. They are set in their ways and I don't think anything could change their mind on these internal standards. Here are a few: 1. Excessive commenting -- practically every operation in code has a preceding comment. No matter how descriptive the code is, and no matter how simple the operation may be, there is a comment such as the following:

                /// /// This is an addition method.
                ///
                private int Add(int a, int b)
                {
                // Add the two numbers and return the result
                return a + b;
                }

                private void Process(MyFileObj myFile)
                {
                // Make sure the parameter is not 'null'
                if (myFile != null)
                {
                // Strip all the bad data from the object
                myFile.StripBadData();

                    // Add the file to the collection
                    \_myFileCollection.Add(myFile);
                }
                

                }

                2. Variable declaration -- this may not be so bad, so please correct me if I'm wrong. But I've never seen it done this way. According to their standards, all variables in a method must be initially declared at the top of the method, before anything else is done:

                private MyClass MyMethod()
                {
                int count = 0;
                MyClass someObj = null;

                // Iterate over the file collection
                foreach (MyFileObj file in \_myFileCollection)
                {
                    // Make sure the file's name is not longer than 20 characters
                    if(file.Name.Length <= 20)
                    {
                        // Copy the file to a new location
                        file.CopyTo(@"C:\\SomePath\\" + file.Name);
                
                        // Increment the counter
                        count++;
                    }
                }
                
                // A lot of other code
                // ...
                
                // Setup the class that will be returned
                someObj = new MyClass();
                someObj.FileCount = count;
                
                // Return the class that has the data we need
                return someObj;
                

                }

                The "MyClass someObj" isn't referenced until the very end of the method. Why should it be declared at the very top of the method? Maybe I'm missing something? I've never declared objects until the time I need them. These are just a few examples. There are some other things I don't really agree with, but I can't change any of them.

                djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

                J Offline
                J Offline
                jschell
                wrote on last edited by
                #25

                Matt U. wrote:

                These are just a few examples.

                The examples you gave are excessive. The declaration of variables at the top is actually a hold over from C programming.

                M 1 Reply Last reply
                0
                • A Argonia

                  Declaring all variables at the begining of the method is an old c++(i am not sure if it comes from c) standard closely connected with the variable block of sight. In c# i dont believe there is such thing. Today i was sooo close of declaring such variable

                  bool bResultBecauseMyBossDoesntLikeMoreThanOneReturnInTheMethods = false;

                  next time ask your boss if you need to put a comment to the line

                  i++;

                  Sometimes i wonder... why does they want us to comment everything like the next "programmer", who will manage this will be a monkey.

                  Microsoft ... the only place where VARIANT_TRUE != true

                  J Offline
                  J Offline
                  jschell
                  wrote on last edited by
                  #26

                  Argonia wrote:

                  Declaring all variables at the begining of the method is an old c++(i am not sure if it comes from c)

                  It is from C.

                  J 1 Reply Last reply
                  0
                  • M Member 10088171

                    The problem with comments is that they are often not changed in sync with code updates. Another one is that meaningful comment today is often meaningless tomorrow. I am trying my best creating meaningful comments and this is an art and continuous learning. Similarly I like important declarations at the top but I declare "utility" variables at the point of use.

                    J Offline
                    J Offline
                    jschell
                    wrote on last edited by
                    #27

                    Member 10088171 wrote:

                    The problem with comments is that they are often not changed in sync with code updates. Another one is that meaningful comment today is often meaningless tomorrow. I am trying my best creating meaningful comments and this is an art and continuous learning

                    The problem with that entire statement however is it means that either code reviews are not occurring at all or that they are not being taken seriously. If code reviews are done correctly then an incorrect comment should not show up.

                    M 1 Reply Last reply
                    0
                    • J jschell

                      Member 10088171 wrote:

                      The problem with comments is that they are often not changed in sync with code updates. Another one is that meaningful comment today is often meaningless tomorrow. I am trying my best creating meaningful comments and this is an art and continuous learning

                      The problem with that entire statement however is it means that either code reviews are not occurring at all or that they are not being taken seriously. If code reviews are done correctly then an incorrect comment should not show up.

                      M Offline
                      M Offline
                      Member 10088171
                      wrote on last edited by
                      #28

                      There are no good uniform standards for commenting code (no intelliSense either) and despite best efforts issues with code comments are missed even by best reviewers. One of the more practical approach is using asserts and exceptions instead of comments. When meaningful comments are necessary I also add time stamp showing comment/code updates.

                      J 1 Reply Last reply
                      0
                      • J jschell

                        Matt U. wrote:

                        These are just a few examples.

                        The examples you gave are excessive. The declaration of variables at the top is actually a hold over from C programming.

                        M Offline
                        M Offline
                        Matt U
                        wrote on last edited by
                        #29

                        But C# is not C. Is it necessary? I've learned throughout the life of this thread that it doesn't matter. It isn't necessarily good or bad. But does it benefit in any manner when coding in C#?

                        djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

                        D J 2 Replies Last reply
                        0
                        • M Matt U

                          But C# is not C. Is it necessary? I've learned throughout the life of this thread that it doesn't matter. It isn't necessarily good or bad. But does it benefit in any manner when coding in C#?

                          djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

                          D Offline
                          D Offline
                          Dennis E White
                          wrote on last edited by
                          #30

                          Matt U. wrote:

                          But does it benefit in any manner when coding in C#?

                          whether it benefits in any manner is only a question that can be answered by those who created the coding the standards you are speaking of. from a language perspective though it makes where the variables are defined if you referring to code performance getting improved.

                          you want something inspirational??

                          1 Reply Last reply
                          0
                          • M Matt U

                            Coding standards with my employer are strange based on everything I've ever known, everything I've ever read, everything I've ever been told. They are set in their ways and I don't think anything could change their mind on these internal standards. Here are a few: 1. Excessive commenting -- practically every operation in code has a preceding comment. No matter how descriptive the code is, and no matter how simple the operation may be, there is a comment such as the following:

                            /// /// This is an addition method.
                            ///
                            private int Add(int a, int b)
                            {
                            // Add the two numbers and return the result
                            return a + b;
                            }

                            private void Process(MyFileObj myFile)
                            {
                            // Make sure the parameter is not 'null'
                            if (myFile != null)
                            {
                            // Strip all the bad data from the object
                            myFile.StripBadData();

                                // Add the file to the collection
                                \_myFileCollection.Add(myFile);
                            }
                            

                            }

                            2. Variable declaration -- this may not be so bad, so please correct me if I'm wrong. But I've never seen it done this way. According to their standards, all variables in a method must be initially declared at the top of the method, before anything else is done:

                            private MyClass MyMethod()
                            {
                            int count = 0;
                            MyClass someObj = null;

                            // Iterate over the file collection
                            foreach (MyFileObj file in \_myFileCollection)
                            {
                                // Make sure the file's name is not longer than 20 characters
                                if(file.Name.Length <= 20)
                                {
                                    // Copy the file to a new location
                                    file.CopyTo(@"C:\\SomePath\\" + file.Name);
                            
                                    // Increment the counter
                                    count++;
                                }
                            }
                            
                            // A lot of other code
                            // ...
                            
                            // Setup the class that will be returned
                            someObj = new MyClass();
                            someObj.FileCount = count;
                            
                            // Return the class that has the data we need
                            return someObj;
                            

                            }

                            The "MyClass someObj" isn't referenced until the very end of the method. Why should it be declared at the very top of the method? Maybe I'm missing something? I've never declared objects until the time I need them. These are just a few examples. There are some other things I don't really agree with, but I can't change any of them.

                            djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

                            L Offline
                            L Offline
                            Lost User
                            wrote on last edited by
                            #31

                            Just to play devil's advocate a little, it is not necessarily the standard about commenting that is at fault, but the standard of commenting.

                            private void Process(MyFileObj myFile)
                            {
                            // myFile may be null if the user selected a folder rather than a file
                            if (myFile != null)
                            {
                            // some files contain control characters, etc. so strip 'em out
                            myFile.StripBadData();

                                // Add the file to the collection of files to be processed by the thingummy
                                \_myFileCollection.Add(myFile);
                            }
                            

                            }

                            Certainly if someone really wrote code with names like 'myFileCollection' they'll need comments ;) Oh, and the thing you missed completely was a method comment which should have explained what 'process my file' means in business terms - as processMyfile is too generic in all but the smallest of applications.

                            MVVM # - I did it My Way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                            S 1 Reply Last reply
                            0
                            • Richard DeemingR Richard Deeming

                              Matt U. wrote:

                              foreach (MyFileObj file in _myFileCollection)

                              Whoops - you didn't declare the MyFile file variable at the top of the method! ;P

                              Matt U. wrote:

                              // Setup the class that will be returned someObj = new MyClass(); someObj.FileCount = count;

                              Now how is anyone supposed to understand that code with the single comment you've provided? Surely it should be:

                              // Setup the class that will be returned
                              someObj = new MyClass(); // Create a new instance of the MyClass class and store it in the someObj variable.
                              someObj.FileCount = count; // Store the value of the count variable in the FileCount property on the instance of the MyClass class stored in the someObj variable.

                              There, isn't that better? :rolleyes:


                              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                              J Offline
                              J Offline
                              Jonathan C Dickinson
                              wrote on last edited by
                              #32

                              Richard Deeming wrote:

                              Whoops - you didn't declare the MyFile file variable at the top of the method! ;-P

                              Tsk. Tsk. In that case it's obvious then that foreach isn't allowed.

                              IEnumerator enumerator;
                              MyFileObj file;
                              
                              using (enumerator = \_myFileCollection.GetEnumerator())
                              {
                                  while (enumerator.MoveNext())
                                  {
                                      file = enumerator.Current;
                                  }
                              }
                              

                              He who asks a question is a fool for five minutes. He who does not ask a question remains a fool forever. [Chinese Proverb] Jonathan C Dickinson (C# Software Engineer)

                              Richard DeemingR 1 Reply Last reply
                              0
                              • M Matt U

                                Coding standards with my employer are strange based on everything I've ever known, everything I've ever read, everything I've ever been told. They are set in their ways and I don't think anything could change their mind on these internal standards. Here are a few: 1. Excessive commenting -- practically every operation in code has a preceding comment. No matter how descriptive the code is, and no matter how simple the operation may be, there is a comment such as the following:

                                /// /// This is an addition method.
                                ///
                                private int Add(int a, int b)
                                {
                                // Add the two numbers and return the result
                                return a + b;
                                }

                                private void Process(MyFileObj myFile)
                                {
                                // Make sure the parameter is not 'null'
                                if (myFile != null)
                                {
                                // Strip all the bad data from the object
                                myFile.StripBadData();

                                    // Add the file to the collection
                                    \_myFileCollection.Add(myFile);
                                }
                                

                                }

                                2. Variable declaration -- this may not be so bad, so please correct me if I'm wrong. But I've never seen it done this way. According to their standards, all variables in a method must be initially declared at the top of the method, before anything else is done:

                                private MyClass MyMethod()
                                {
                                int count = 0;
                                MyClass someObj = null;

                                // Iterate over the file collection
                                foreach (MyFileObj file in \_myFileCollection)
                                {
                                    // Make sure the file's name is not longer than 20 characters
                                    if(file.Name.Length <= 20)
                                    {
                                        // Copy the file to a new location
                                        file.CopyTo(@"C:\\SomePath\\" + file.Name);
                                
                                        // Increment the counter
                                        count++;
                                    }
                                }
                                
                                // A lot of other code
                                // ...
                                
                                // Setup the class that will be returned
                                someObj = new MyClass();
                                someObj.FileCount = count;
                                
                                // Return the class that has the data we need
                                return someObj;
                                

                                }

                                The "MyClass someObj" isn't referenced until the very end of the method. Why should it be declared at the very top of the method? Maybe I'm missing something? I've never declared objects until the time I need them. These are just a few examples. There are some other things I don't really agree with, but I can't change any of them.

                                djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

                                S Offline
                                S Offline
                                Stefan_Lang
                                wrote on last edited by
                                #33

                                I see very little - if any - benefit in declaring all local variables at the start of a method. To the contrary, it's bound to cause problems: 1. Variables that are being used much later may not have to be allocated at all, depending on the flow of control. You may end up spending resources and processing time for the initialization (and release) of data you never need! This is specifically true if you make a sanity check on the method arguments (which you alwys should) and go for a premature return. 2. When you maintain the code, it's often useful to see how a local variable has been initialized. This gets harder when the variables are grouped a long way up, and you can't see at a glance whether it's being changed between the declaration and the spot you're about to edit. 3. You shouldn't keep a hold on resources that you no longer need: the only way to reliably and maintainably (is that a word?) free up the resources required by a variable is declaring it within a code block. I even sometimes use a code block as a means to denote a specific variable's lifetime! You (or your manager) might consider this just as a'nice to have' feature, but it quickly becomes a necessity when you program concurrent threads using locks. There's no way in hell you're going to keep your locks over an entire method! P.S.: 4. How do you do exceptions? I suspect your manager has never implemented a catch block, did he? :doh: 5. Why do you think C++11 has been changed to end the lifetime of for loop counters at the end of the loop?

                                GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                                1 Reply Last reply
                                0
                                • L Lost User

                                  Just to play devil's advocate a little, it is not necessarily the standard about commenting that is at fault, but the standard of commenting.

                                  private void Process(MyFileObj myFile)
                                  {
                                  // myFile may be null if the user selected a folder rather than a file
                                  if (myFile != null)
                                  {
                                  // some files contain control characters, etc. so strip 'em out
                                  myFile.StripBadData();

                                      // Add the file to the collection of files to be processed by the thingummy
                                      \_myFileCollection.Add(myFile);
                                  }
                                  

                                  }

                                  Certainly if someone really wrote code with names like 'myFileCollection' they'll need comments ;) Oh, and the thing you missed completely was a method comment which should have explained what 'process my file' means in business terms - as processMyfile is too generic in all but the smallest of applications.

                                  MVVM # - I did it My Way ___________________________________________ Man, you're a god. - walterhevedeich 26/05/2011 .\\axxx (That's an 'M')

                                  S Offline
                                  S Offline
                                  Stefan_Lang
                                  wrote on last edited by
                                  #34

                                  A very good point indeed. You might even extend that to the trivial example of commenting a statement like

                                  i++;

                                  For one you may want to comment on why you chose to use post-increment rather than the more efficient preincrement. ;) Or, better yet, you might comment on why you need to increment this variable at this precise moment - or what it is counting anyway! ;P

                                  GOTOs are a bit like wire coat hangers: they tend to breed in the darkness, such that where there once were few, eventually there are many, and the program's architecture collapses beneath them. (Fran Poretto)

                                  1 Reply Last reply
                                  0
                                  • J Jonathan C Dickinson

                                    Richard Deeming wrote:

                                    Whoops - you didn't declare the MyFile file variable at the top of the method! ;-P

                                    Tsk. Tsk. In that case it's obvious then that foreach isn't allowed.

                                    IEnumerator enumerator;
                                    MyFileObj file;
                                    
                                    using (enumerator = \_myFileCollection.GetEnumerator())
                                    {
                                        while (enumerator.MoveNext())
                                        {
                                            file = enumerator.Current;
                                        }
                                    }
                                    

                                    He who asks a question is a fool for five minutes. He who does not ask a question remains a fool forever. [Chinese Proverb] Jonathan C Dickinson (C# Software Engineer)

                                    Richard DeemingR Offline
                                    Richard DeemingR Offline
                                    Richard Deeming
                                    wrote on last edited by
                                    #35

                                    Well, I'm going to have to dock you points for not commenting every line of that code. Without the comments, how is anyone supposed to understand it? :rolleyes:


                                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                    "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                                    1 Reply Last reply
                                    0
                                    • J jschell

                                      Argonia wrote:

                                      Declaring all variables at the begining of the method is an old c++(i am not sure if it comes from c)

                                      It is from C.

                                      J Offline
                                      J Offline
                                      John Nurick
                                      wrote on last edited by
                                      #36

                                      jschell wrote:

                                      It is from C.

                                      It's in Pascal, which AFAIK predates C. Which isn't to say that both didn't pick it up from some other language.

                                      L J 2 Replies Last reply
                                      0
                                      • M Matt U

                                        Coding standards with my employer are strange based on everything I've ever known, everything I've ever read, everything I've ever been told. They are set in their ways and I don't think anything could change their mind on these internal standards. Here are a few: 1. Excessive commenting -- practically every operation in code has a preceding comment. No matter how descriptive the code is, and no matter how simple the operation may be, there is a comment such as the following:

                                        /// /// This is an addition method.
                                        ///
                                        private int Add(int a, int b)
                                        {
                                        // Add the two numbers and return the result
                                        return a + b;
                                        }

                                        private void Process(MyFileObj myFile)
                                        {
                                        // Make sure the parameter is not 'null'
                                        if (myFile != null)
                                        {
                                        // Strip all the bad data from the object
                                        myFile.StripBadData();

                                            // Add the file to the collection
                                            \_myFileCollection.Add(myFile);
                                        }
                                        

                                        }

                                        2. Variable declaration -- this may not be so bad, so please correct me if I'm wrong. But I've never seen it done this way. According to their standards, all variables in a method must be initially declared at the top of the method, before anything else is done:

                                        private MyClass MyMethod()
                                        {
                                        int count = 0;
                                        MyClass someObj = null;

                                        // Iterate over the file collection
                                        foreach (MyFileObj file in \_myFileCollection)
                                        {
                                            // Make sure the file's name is not longer than 20 characters
                                            if(file.Name.Length <= 20)
                                            {
                                                // Copy the file to a new location
                                                file.CopyTo(@"C:\\SomePath\\" + file.Name);
                                        
                                                // Increment the counter
                                                count++;
                                            }
                                        }
                                        
                                        // A lot of other code
                                        // ...
                                        
                                        // Setup the class that will be returned
                                        someObj = new MyClass();
                                        someObj.FileCount = count;
                                        
                                        // Return the class that has the data we need
                                        return someObj;
                                        

                                        }

                                        The "MyClass someObj" isn't referenced until the very end of the method. Why should it be declared at the very top of the method? Maybe I'm missing something? I've never declared objects until the time I need them. These are just a few examples. There are some other things I don't really agree with, but I can't change any of them.

                                        djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

                                        L Offline
                                        L Offline
                                        Lost User
                                        wrote on last edited by
                                        #37

                                        I too am on a project (about a million SLOC) that forces outdated coding rules that stem from the 1970's. The project has been ongoing for almost 17 years. I have tried to change the rules to reflect more modern thinking but the tech lead won't change claiming that consistency trumps everything including common sense, and that "the customer wants it that way" even though the customer developers don't follow their own rules. One thing that was not mentioned about function-top declarations - it wastes processor time and stack space (for those of us who develop embedded systems with constraints on such things). Why should a class object be unnecessarily declared and created at function top and destroyed upon function termination when it is only used in the very rare case of an error? Following are justifications for function-top declaration and initialization used by our project, and my responses to them. Justification: Uninitialized access errors are easy to catch, either by a good compiler, by proper testing, or by a memory access testing tool. Response: Meaningless. A good compiler, proper testing, or a memory access tool will catch uninitialized access errors regardless of where the variable is declared. Furthermore, declaring and initializing a variable close to where it is first used reduces the likelihood of an uninitialized access error. Justification: Default initialization often does not incur a large performance penalty. Response: Maybe for simple bool or int types. But unnecessary creation and initialization of class objects, and the associated destruction of said objects, when multiplied by thousands of functions in the system, can begin to impact performance and memory usage. Justification: Placing all declarations at the top of the block makes them easy to find. Response: Placing declarations close to first use makes them easier to find! This may have been true back in the 1970’s when programming was done with punched cards, but today, any editor can find a variable in seconds. Justification: In some cases, variables must be initialized within a sub-block (e.g. a variable given different values in each branch of an if/else construct), in which case the variable must be declared before initialization. Response: The phrase “variable must be declared before initialization” implies that the variable must be declared earlier in the code, which may or may not be true, depending on the context. It is obvious that the deve

                                        1 Reply Last reply
                                        0
                                        • M Matt U

                                          Coding standards with my employer are strange based on everything I've ever known, everything I've ever read, everything I've ever been told. They are set in their ways and I don't think anything could change their mind on these internal standards. Here are a few: 1. Excessive commenting -- practically every operation in code has a preceding comment. No matter how descriptive the code is, and no matter how simple the operation may be, there is a comment such as the following:

                                          /// /// This is an addition method.
                                          ///
                                          private int Add(int a, int b)
                                          {
                                          // Add the two numbers and return the result
                                          return a + b;
                                          }

                                          private void Process(MyFileObj myFile)
                                          {
                                          // Make sure the parameter is not 'null'
                                          if (myFile != null)
                                          {
                                          // Strip all the bad data from the object
                                          myFile.StripBadData();

                                              // Add the file to the collection
                                              \_myFileCollection.Add(myFile);
                                          }
                                          

                                          }

                                          2. Variable declaration -- this may not be so bad, so please correct me if I'm wrong. But I've never seen it done this way. According to their standards, all variables in a method must be initially declared at the top of the method, before anything else is done:

                                          private MyClass MyMethod()
                                          {
                                          int count = 0;
                                          MyClass someObj = null;

                                          // Iterate over the file collection
                                          foreach (MyFileObj file in \_myFileCollection)
                                          {
                                              // Make sure the file's name is not longer than 20 characters
                                              if(file.Name.Length <= 20)
                                              {
                                                  // Copy the file to a new location
                                                  file.CopyTo(@"C:\\SomePath\\" + file.Name);
                                          
                                                  // Increment the counter
                                                  count++;
                                              }
                                          }
                                          
                                          // A lot of other code
                                          // ...
                                          
                                          // Setup the class that will be returned
                                          someObj = new MyClass();
                                          someObj.FileCount = count;
                                          
                                          // Return the class that has the data we need
                                          return someObj;
                                          

                                          }

                                          The "MyClass someObj" isn't referenced until the very end of the method. Why should it be declared at the very top of the method? Maybe I'm missing something? I've never declared objects until the time I need them. These are just a few examples. There are some other things I don't really agree with, but I can't change any of them.

                                          djj55: Nice but may have a permission problem Pete O'Hanlon: He has my permission to run it.

                                          A Offline
                                          A Offline
                                          agolddog
                                          wrote on last edited by
                                          #38

                                          With respect to your first point, this is not good. I can tell you what the code is doing by reading it. Why is it doing that is the question the documentation should answer. The hardest part about good documentation is what I've called the "philosophical documentation." In other words, describe what you think the code is doing, and why you took this approach. Try to let a future developer (yourself included) get into your mindset when building this code. About the variable declaration, it depends. If it is truly just declaring method-scope variables, that's probably not so bad. If, however, the variables you declare require some potentially costly construction, then it's smarter to delay that until necessary. Your method might exit before hitting that constructor in some code path and save that cost, for example. I agree there is something to be said for the idea of 'closeness'. I feel like it makes the developer continually think about scope, but it's probably not such a huge deal.

                                          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