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. Code Neatness

Code Neatness

Scheduled Pinned Locked Moved The Lounge
c++question
82 Posts 42 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.
  • C chaiguy1337

    Timothy W. Okrey wrote:

    I never expected to find that if you declare a variable within a code block such as an if or a switch that the variable would go out of scope later on.

    Well this is simply a case of being uneducated about the rules of the language you were using. I could argue that I never expected: int main( void ) { MakeAwesomeProgram(); } ...to not create the world's awesomest program, but chances are it's not going to. The rules of scope declaration are quite sound: a variable is only good in the scope it's defined in. In fact, you can even use a rarely-seen technique for defining arbitrary blocks of scope solely for this purpose: { int i = 5; ... } { int i = 10; // different 'i' ... }

    “Time and space can be a bitch.” –Gushie, Quantum Leap {o,o}.oO( Want a great RSS reader? Try FeedBeast! ) |)””’) -”-”-

    T Offline
    T Offline
    Timothy W Okrey
    wrote on last edited by
    #58

    I think perhaps you missed my point. My point was to try and present an argument for code standardization for the sake of continued support and readability. The issue of where to define variables is not of primary concern for me. In my experience (note the qualifier), programmers have an easier time picking up on a project when the variables are delcared in one spot (at the beginning). I also believe that there are a lot of lazy programming styles out there where people don't think through their code before they write it. Functions should be small and highly compartmentalized. I realize that this is not always possible, but it should be a design consideration. If you can manage to create compartmentalized code well, then your varaible declarations will mostly occur near their first usage anyways, thus rendering the JIT/beginning argument moot.

    'With hurricanes, tornados, fires out of control,mud slides, flooding, severe thunderstorms tearing up the country! from one end to another, and with the threat of bird flu and terrorist attacks, are we sure this is a good time to take God out of the Pledge of Allegiance?' - Jay Leno

    1 Reply Last reply
    0
    • M Michael Haines

      I used to be "top of the block" declarer, that is, until I started to do more code review/maintenance. Now I wish the declares were all JIT. The REAL messy code problem is: Long code lines requiring horizontal scrolling. MH

      N Offline
      N Offline
      nalorin
      wrote on last edited by
      #59

      mhaines@1amadeus.com wrote:

      Long code lines requiring horizontal scrolling. MH

      It's a lot better than having "dynamically wrapped" lines, and having to look at all of the "lines" of that dynamically wrapped line of code to figure out which ones are part of that line, and which ones are completely new lines altogether. That being said, lines with 80+ characters and more than one semicolon in them (i.e. more than one 'line' in a line) are the fail! - for() loops included! :wtf:

      "Silently laughing at silly people is much more satisfying in the long run than rolling around with them in a dusty street, trying to knock out all their teeth. If nothing else, it's better on the clothes." - Belgarath (David Eddings)

      1 Reply Last reply
      0
      • C Chris Maunder

        Code readability (and set standards) is fundamental to developing consistent, maintainable code. Picking a good, comprehensive standard way of coding means less chance of errors appearing because different parts of the code will be doing things in a similar fashion so there's less chance of conflict. Having one standard of writing code means that when you are browsing code it will all look the same so errors through incorrect implementation will be easier and faster to spot. It's not where you declare your variables that matters. It's how readable and maintainable your code is. Personally I prefer to declare my variables as close to their first use as possible. Other like them all sitting, huddled, at the top of their functions, too scared to mingle with the rest of the crowd. It's kind of like the kitchen of the function.

        cheers, Chris Maunder

        CodeProject.com : C++ MVP

        N Offline
        N Offline
        nalorin
        wrote on last edited by
        #60

        Chris Maunder wrote:

        Code readability (and set standards) is fundamental to developing consistent, maintainable code.

        But then again, there's always the option of coding to add job security.[^] :laugh:

        "Silently laughing at silly people is much more satisfying in the long run than rolling around with them in a dusty street, trying to knock out all their teeth. If nothing else, it's better on the clothes." - Belgarath (David Eddings)

        D 1 Reply Last reply
        0
        • S Shog9 0

          Ri Qen-Sin wrote:

          so was I right when I said so?

          No. C required you to declare variables at the beginning of a function, because C (and C++) allocate all local variables when the stack frame is being constructed, and it simplified the compiler. C++ doesn't require this. Making me scan back through your code looking for a variable declaration isn't being neat. It's just being rude. I actually had to explain this to a new consultant last week, when he tried to argue that throwing a dozen variable declarations at the top of a rather large function increased efficiency by avoiding allocations in a loop. Good grief. Do people not know how to generate assembler output from their compilers anymore? :suss:

          N Offline
          N Offline
          nalorin
          wrote on last edited by
          #61

          Shog9 wrote:

          Do people not know how to generate assembler output from their compilers anymore?

          Perhaps I need to look this up :P

          Shog9 wrote:

          Making me scan back through your code looking for a variable declaration isn't being neat. It's just being rude.

          I think the degree of neat/rudeness depends on the coder's personal taste. I, personally, prefer (in most cases) variables declared/initialized at the beginning of their scope. This way, I can see all the information about all the variables in the scope. I find it much easier to debug this way, since I can immediately rule out the declaration and initialization of my variables as the cause of a problem, and seems to help me prevent conditional initializations of variables like: int x; if (sloppy_joes == good) x = 47; If the 2 lines above are sandwiched between 50 lines of code on either side, I've often forgotten in the past that x may not always get initialized, and will think "x is declared here... and is initialized to 47 there. What the heck is wrong?!" If initialization/declaration are placed at the beginning, I think more like: "x is declared here, initialized on the next line, and used down there." I can't help but agree that code is just more readable with variable declarations (in most cases) placed at the top of the variable's scope - but that's just my take on the subject.

          "Silently laughing at silly people is much more satisfying in the long run than rolling around with them in a dusty street, trying to knock out all their teeth. If nothing else, it's better on the clothes." - Belgarath (David Eddings)

          S R 2 Replies Last reply
          0
          • R Ri Qen Sin

            So somewhere on the internet, I pointed out to a newbie that his code was pretty messy and that he should start by consolidating some of his variable declarations to the beginning of the program (which was consisted of only a main(…) function/method/entry point and a lot of improperly formatted code). In walks another forum member and criticizes me for my comment saying that "it's a feature of the C++ language to be able to declare variables anywhere you need it." I was obviously pissed at that comment showing his utter disregard for code neatness and readability (and likely a malicious attack on my intelligence). I'm trying to seek agreement… so was I right when I said so?

            So the creationist says: Everything must have a designer. God designed everything. I say: Why is God the only exception? Why not make the "designs" (like man) exceptions and make God a creation of man?

            A Offline
            A Offline
            avoidingwork2
            wrote on last edited by
            #62

            Short Version: Accepting change and trying to work with it broadens you abilities. Long Version: I started coding with all my variables declared at the top. The were grouped by type and then sorted alphabetically. Luckily we used brief and had macros that would sort out a highlighted section of code for us. The language required pre-declaration so there was no use arguing about where we declared our variables only that is was organized the same throughout the department. I then started developing in C++ and noticed that I had a hard time reading code where the variables were declared JIT. I didn't like it, although there wasn't anything wrong with the code, it was just different for me to work with. Finding declarations required a new process and I wasn't happy about about changing. Now several languages, programming shops, and standards later I find I can't be so ridged in my ways, change is a part of the job. Nowadays I find that I am doing both depending on the variable needs. I have noticed that JIT declaration is a little easier to refactor code, but at the same time when I have to pre-declare my variables I find that I still group them. Some habits are hard to break. And that is the crux of this whole thread. It's a habit how you lay your code out. There is no right way or wrong way. The main thing to remember is to not be candidate for the code obfuscation contest. Remember, you can take 20 lines of code and compress it down to 2 but the next time you read it you wont know what you were trying to do. :) Sorry for letting this ramble on so long.

            1 Reply Last reply
            0
            • N nalorin

              Shog9 wrote:

              Do people not know how to generate assembler output from their compilers anymore?

              Perhaps I need to look this up :P

              Shog9 wrote:

              Making me scan back through your code looking for a variable declaration isn't being neat. It's just being rude.

              I think the degree of neat/rudeness depends on the coder's personal taste. I, personally, prefer (in most cases) variables declared/initialized at the beginning of their scope. This way, I can see all the information about all the variables in the scope. I find it much easier to debug this way, since I can immediately rule out the declaration and initialization of my variables as the cause of a problem, and seems to help me prevent conditional initializations of variables like: int x; if (sloppy_joes == good) x = 47; If the 2 lines above are sandwiched between 50 lines of code on either side, I've often forgotten in the past that x may not always get initialized, and will think "x is declared here... and is initialized to 47 there. What the heck is wrong?!" If initialization/declaration are placed at the beginning, I think more like: "x is declared here, initialized on the next line, and used down there." I can't help but agree that code is just more readable with variable declarations (in most cases) placed at the top of the variable's scope - but that's just my take on the subject.

              "Silently laughing at silly people is much more satisfying in the long run than rolling around with them in a dusty street, trying to knock out all their teeth. If nothing else, it's better on the clothes." - Belgarath (David Eddings)

              S Offline
              S Offline
              Shog9 0
              wrote on last edited by
              #63

              nalorin wrote:

              I, personally, prefer (in most cases) variables declared/initialized at the beginning of their scope.

              Generally, i do as well. But if a variable is used only in a loop, it should be declared and initialized (ideally both of these together) within that loop, same for variables that are only used within a conditional block, etc. I prefer that the scope is limited to as small a chunk of code as possible; ideally, i can read the variables used and the operations they're used in without having to scroll or turn the page. And frankly, when i'm unable to limit scope, i'll still err on the side of declaring variables where they're used rather than immediately after the scope begins. Yes, this can introduce errors if variables are re-used, but IMHO that's just an argument in favor of limiting variable re-use.

              1 Reply Last reply
              0
              • A AmazingMo

                Ravi Bhavnani wrote:

                as long as you don't declare inside a loop Why not?

                Because every time around the loop the stack will be adjusted for the "new" variable, and then re-adjusted as the variable goes "out of scope". Try it a million times or so and see what happens. Seriously, most compilers will hoist the variable declaration out of the loop scope, but do you want to take the risk that the particular compiler that you're using will? Apropos the OP's question. You started programming in C, didn't you... Do you still use Hungarian notation? Some times it's better to just let go. ;-) You could try using more blocks if you absolutely must have declarations at the opening paren. Cheers, P.

                T Offline
                T Offline
                TheGreatAndPowerfulOz
                wrote on last edited by
                #64

                AmazingMo wrote:

                Because every time around the loop the stack will be adjusted for the "new" variable, and then re-adjusted as the variable goes "out of scope". Try it a million times or so and see what happens.

                wrong. most modern compilers figure out the maximum stack allocation at function entry and allocate that stack space all at once. the reason for not delcaring a non-primitive inside a loop is the constructor overhead.

                Silence is the voice of complicity. Strange women lying in ponds distributing swords is no basis for a system of government. -- monty python Might I suggest that the universe was always the size of the cosmos. It is just that at one point the cosmos was the size of a marble. -- Colin Angus Mackay

                1 Reply Last reply
                0
                • N nalorin

                  Chris Maunder wrote:

                  Code readability (and set standards) is fundamental to developing consistent, maintainable code.

                  But then again, there's always the option of coding to add job security.[^] :laugh:

                  "Silently laughing at silly people is much more satisfying in the long run than rolling around with them in a dusty street, trying to knock out all their teeth. If nothing else, it's better on the clothes." - Belgarath (David Eddings)

                  D Offline
                  D Offline
                  Dan Neely
                  wrote on last edited by
                  #65

                  Choosing The Best Overload Operator : In C++, overload +,-,*,/ to do things totally unrelated to addition, subtraction etc. After all, if the Stroustroup can use the shift operator to do I/O, why should you not be equally creative? If you overload +, make sure you do it in a way that i = i + 5; has a totally different meaning from i += 5; Here is an example of elevating overloading operator obfuscation to a high art. Overload the '!' operator for a class, but have the overload have nothing to do with inverting or negating. Make it return an integer. Then, in order to get a logical value for it, you must use '! !'. However, this inverts the logic, so [drum roll] you must use '! ! !'. Don't confuse ! operator, which returns a boolean 0 or 1, with the ~ bitwise logical negation operator. I think I'm missing something here, how exactly is the ! operator supposed to be implemented to get the desired result from !!!?

                  Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

                  N 1 Reply Last reply
                  0
                  • R Ri Qen Sin

                    So somewhere on the internet, I pointed out to a newbie that his code was pretty messy and that he should start by consolidating some of his variable declarations to the beginning of the program (which was consisted of only a main(…) function/method/entry point and a lot of improperly formatted code). In walks another forum member and criticizes me for my comment saying that "it's a feature of the C++ language to be able to declare variables anywhere you need it." I was obviously pissed at that comment showing his utter disregard for code neatness and readability (and likely a malicious attack on my intelligence). I'm trying to seek agreement… so was I right when I said so?

                    So the creationist says: Everything must have a designer. God designed everything. I say: Why is God the only exception? Why not make the "designs" (like man) exceptions and make God a creation of man?

                    S Offline
                    S Offline
                    Sogar Gofin
                    wrote on last edited by
                    #66

                    I've been perpetually seeking the "cleanest" way to code. Here are my thoughts: In C, one doesn't need to consider subtle features like constructor/destructor behavior, operator overloading, inheritance, generic programming, C++ exceptions, and the like. In C++, these possibilities may associate extra functionality (e.g resource aquisition is initialization, RAII) with the declaration of an object, and also with the departure from the object's scope. Say you declare an object variable inside a function or method whose usage is sometimes skipped over. Say also that the object's constructors are designed to acquire some system resource (e.g. a lock, not uncommon in multi-threading ). If you've declared the object at the top of your routine, you'd be unnecessarily acquiring that resource (e.g if the shared data the lock protects isn't referenced ). This can manifest as unnecessary delay or resource starvation. This justifies declaring some object-types close to their usage. As for basic types: since it's already justified for some objects, you may as well do it with basic types to keep standards consistent and code modular. This also makes it easier to break a big routine into sub-routines. Not to mention, you never know if a future code refactor may turn a basic type into an object. As I've experienced, you may need to change your doubles into special fixed-point objects to run better on particular machines ... like the UltraSPARC T1000 ... C++ is subtle. IMO, the compiler ought to be explicit about how much of this it automatically handles. See: http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization[^] - Charles Rojo Software Engineer

                    Rojo

                    modified on Monday, March 10, 2008 11:42 PM

                    1 Reply Last reply
                    0
                    • E El Corazon

                      Ri Qen-Sin wrote:

                      I'm trying to seek agreement… so was I right when I said so?

                      yes, and no. If your code loops or branches, it matters where you declare your variables. For instance declaring all your variables up front pulls a lot of space off the stack or heap, creates overhead, and if you branch or exit early, you have created unnecessary overhead. If your code branches with an if or a switch, you never want to incur the overhead associated with unused branches. on the other side, declaring a variable inside of a loop means that this variable will be allocated and deallocated often. By moving the declaration outside of the loop, your cost is significantly less performance wise. BUT! The rule above still applies. You do not have to move it to the front of the function, though you can if you don't branch or exit early.

                      _________________________ Asu no koto o ieba, tenjo de nezumi ga warau. Talk about things of tomorrow and the mice in the ceiling laugh. (Japanese Proverb)

                      T Offline
                      T Offline
                      TheGreatAndPowerfulOz
                      wrote on last edited by
                      #67

                      El Corazon wrote:

                      For instance declaring all your variables up front pulls a lot of space off the stack

                      false. modern compilers all calculate the max stack need for all variables declared within a method's scope and allocate the stack space. The stack does *not* grow and shrink during a method's lifetime (even if that method has embedded sub-scopes), except as a result of other methods called from within that method.

                      El Corazon wrote:

                      declaring a variable inside of a loop means that this variable will be allocated and deallocated often

                      this is only true for non-primitive variables.

                      Silence is the voice of complicity. Strange women lying in ponds distributing swords is no basis for a system of government. -- monty python Might I suggest that the universe was always the size of the cosmos. It is just that at one point the cosmos was the size of a marble. -- Colin Angus Mackay

                      1 Reply Last reply
                      0
                      • R Ri Qen Sin

                        So somewhere on the internet, I pointed out to a newbie that his code was pretty messy and that he should start by consolidating some of his variable declarations to the beginning of the program (which was consisted of only a main(…) function/method/entry point and a lot of improperly formatted code). In walks another forum member and criticizes me for my comment saying that "it's a feature of the C++ language to be able to declare variables anywhere you need it." I was obviously pissed at that comment showing his utter disregard for code neatness and readability (and likely a malicious attack on my intelligence). I'm trying to seek agreement… so was I right when I said so?

                        So the creationist says: Everything must have a designer. God designed everything. I say: Why is God the only exception? Why not make the "designs" (like man) exceptions and make God a creation of man?

                        Y Offline
                        Y Offline
                        Yortw
                        wrote on last edited by
                        #68

                        Hi, Here's my two cents ;) I used to think this was just a personal choice (unless company coding standards said so), until I tried debugging code with the (class-level) declares scattered all over the document... it made me dizzy watching the code window leap all over the place, and it seemed slower. I've gone back to declaring everything at the top. In fact, in C# I even have a region I place all my class level declarations in. In specific methods, I generally only declare variables at the top of the method if I'm going to use them in side various branch statements, if they're only used inside a single branch then I declare them there. The comment about declaring them late to prevent unneccesary construction, would at least in some languages, only apply to variables that were set to a new value during construction, rather than simply declared, and is more about performance of the code rather than readability or maintainability. As for the comments about long lines of code... I used to care about this too, until I realised some of our other company developers still have a single monitor at 1024x768... at which point, in C# with various docked windows, 15 characters is too long. Basically, you never know how big someone's text window is, so I just write what I consider 'reasonable' for the paritcular line, and if someone complains, they can reformat it. Oh, but my code lines are usually shorter than my sentences :)

                        R T 2 Replies Last reply
                        0
                        • R Ri Qen Sin

                          So somewhere on the internet, I pointed out to a newbie that his code was pretty messy and that he should start by consolidating some of his variable declarations to the beginning of the program (which was consisted of only a main(…) function/method/entry point and a lot of improperly formatted code). In walks another forum member and criticizes me for my comment saying that "it's a feature of the C++ language to be able to declare variables anywhere you need it." I was obviously pissed at that comment showing his utter disregard for code neatness and readability (and likely a malicious attack on my intelligence). I'm trying to seek agreement… so was I right when I said so?

                          So the creationist says: Everything must have a designer. God designed everything. I say: Why is God the only exception? Why not make the "designs" (like man) exceptions and make God a creation of man?

                          S Offline
                          S Offline
                          Stick
                          wrote on last edited by
                          #69

                          Nope, you were wrong as far as standard best practice goes (see Code Complete as an authoritative example). While in C this is the standard practice, in C++ it is considered the standard practice to code your var declarations/definitions at the point of first use. If you think about it, this makes sense for an OOP language. The idea is that in C++, you want good encapsulation and easier maintainability. Problem is that few who claim they are coding in C++ are doing little more than compiling C with a C++ compiler. However, the bottom line is that as the programmer, you get to do it any way you find best. Probably a better way of "teaching" is just to post an example of how you would do it, and let the other person take what they can from it. Patrick

                          1 Reply Last reply
                          0
                          • D Dan Neely

                            Choosing The Best Overload Operator : In C++, overload +,-,*,/ to do things totally unrelated to addition, subtraction etc. After all, if the Stroustroup can use the shift operator to do I/O, why should you not be equally creative? If you overload +, make sure you do it in a way that i = i + 5; has a totally different meaning from i += 5; Here is an example of elevating overloading operator obfuscation to a high art. Overload the '!' operator for a class, but have the overload have nothing to do with inverting or negating. Make it return an integer. Then, in order to get a logical value for it, you must use '! !'. However, this inverts the logic, so [drum roll] you must use '! ! !'. Don't confuse ! operator, which returns a boolean 0 or 1, with the ~ bitwise logical negation operator. I think I'm missing something here, how exactly is the ! operator supposed to be implemented to get the desired result from !!!?

                            Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

                            N Offline
                            N Offline
                            nalorin
                            wrote on last edited by
                            #70

                            dan neely wrote:

                            I think I'm missing something here, how exactly is the ! operator supposed to be implemented to get the desired result from !!!?

                            Thus proving it's effectiveness... (i.e. I don't know either - haven't had a chance to read the whole document unfortunately :^) )

                            "Silently laughing at silly people is much more satisfying in the long run than rolling around with them in a dusty street, trying to knock out all their teeth. If nothing else, it's better on the clothes." - Belgarath (David Eddings)

                            1 Reply Last reply
                            0
                            • N nalorin

                              Shog9 wrote:

                              Do people not know how to generate assembler output from their compilers anymore?

                              Perhaps I need to look this up :P

                              Shog9 wrote:

                              Making me scan back through your code looking for a variable declaration isn't being neat. It's just being rude.

                              I think the degree of neat/rudeness depends on the coder's personal taste. I, personally, prefer (in most cases) variables declared/initialized at the beginning of their scope. This way, I can see all the information about all the variables in the scope. I find it much easier to debug this way, since I can immediately rule out the declaration and initialization of my variables as the cause of a problem, and seems to help me prevent conditional initializations of variables like: int x; if (sloppy_joes == good) x = 47; If the 2 lines above are sandwiched between 50 lines of code on either side, I've often forgotten in the past that x may not always get initialized, and will think "x is declared here... and is initialized to 47 there. What the heck is wrong?!" If initialization/declaration are placed at the beginning, I think more like: "x is declared here, initialized on the next line, and used down there." I can't help but agree that code is just more readable with variable declarations (in most cases) placed at the top of the variable's scope - but that's just my take on the subject.

                              "Silently laughing at silly people is much more satisfying in the long run than rolling around with them in a dusty street, trying to knock out all their teeth. If nothing else, it's better on the clothes." - Belgarath (David Eddings)

                              R Offline
                              R Offline
                              Ri Qen Sin
                              wrote on last edited by
                              #71

                              See? You actually understand me! :)

                              So the creationist says: Everything must have a designer. God designed everything. I say: Why is God the only exception? Why not make the "designs" (like man) exceptions and make God a creation of man?

                              1 Reply Last reply
                              0
                              • T T Mac Oz

                                Mark Salsbery wrote:

                                I'm referring to taking advantage of the scoping of variables within functions in C++.

                                I think Ri addresses this (italics added by me):

                                Ri Qen-Sin wrote:

                                my style is to declare it as close to the beginning as possible while keeping all the local variables deifnitions in the most local scope.

                                So, if I'm interpreting this correctly, Ri groups the declaration of (new) variables used within a block at the beginning of that block, taking advantage of block scoping. On the other hand, Ri's orginal advice:

                                Ri Qen-Sin wrote:

                                start by consolidating some of his variable declarations to the beginning of the program

                                in isolation sounds like a very simplistic/outdated approach but might well make sense in the context of the code he was commenting on in the first place:

                                Ri Qen-Sin wrote:

                                which was consisted of only a main(…) function/method/entry point and a lot of improperly formatted code

                                Ri, I think this should be a valuable lesson for you: By all means, recommend that scrappy looking code be cleaned up & formatted but never give coding style advice in a public forum! Leave that up to the individual or you open yourself up for a world of pain...X| At the very least, if you must give code style advice, be certain to qualify it with "it's my personal preference to..." :)

                                T-Mac-Oz

                                R Offline
                                R Offline
                                Ri Qen Sin
                                wrote on last edited by
                                #72

                                Exactly!!! That is what I meant. Mayme my choice of diction is pretty bad since everyone seems to assume that I am suggesting that all variables (no matter the scope) should be declared globally or something ridiculous like that. ~_~

                                1 Reply Last reply
                                0
                                • Y Yortw

                                  Hi, Here's my two cents ;) I used to think this was just a personal choice (unless company coding standards said so), until I tried debugging code with the (class-level) declares scattered all over the document... it made me dizzy watching the code window leap all over the place, and it seemed slower. I've gone back to declaring everything at the top. In fact, in C# I even have a region I place all my class level declarations in. In specific methods, I generally only declare variables at the top of the method if I'm going to use them in side various branch statements, if they're only used inside a single branch then I declare them there. The comment about declaring them late to prevent unneccesary construction, would at least in some languages, only apply to variables that were set to a new value during construction, rather than simply declared, and is more about performance of the code rather than readability or maintainability. As for the comments about long lines of code... I used to care about this too, until I realised some of our other company developers still have a single monitor at 1024x768... at which point, in C# with various docked windows, 15 characters is too long. Basically, you never know how big someone's text window is, so I just write what I consider 'reasonable' for the paritcular line, and if someone complains, they can reformat it. Oh, but my code lines are usually shorter than my sentences :)

                                  R Offline
                                  R Offline
                                  Ri Qen Sin
                                  wrote on last edited by
                                  #73

                                  I don't know who 1'ed you for that, but you got my 5 cents. :)

                                  So the creationist says: Everything must have a designer. God designed everything. I say: Why is God the only exception? Why not make the "designs" (like man) exceptions and make God a creation of man?

                                  1 Reply Last reply
                                  0
                                  • L Lowell Boggs

                                    Declaring variables at the top of a function or program is bad idea. Consider the following:

                                    void function()
                                    {
                                    int i;

                                      // use 'i' for purpose 1
                                      ...
                                      // use 'i' for purpose 2
                                      ...
                                      // use 'i' for purpose 3
                                      ...
                                    
                                      if(i == 14)
                                      {
                                        // crash the program
                                      }
                                    

                                    }

                                    At the bottom of the function, 'i' is the accidental work product of the last place that it was used. Suppose this function is 200 lines long? Is the user supposed to hand examine every single place a variable is modified in order to understand what its value is currently being used for? Instead, declare variables as close to the point that they are actually used and make sure that they go out of scope as quickly after that as possible to reduce confusion to later maintainers. Confusion is the root of all evil in s/w. Lowell used.

                                    Y Offline
                                    Y Offline
                                    Yortw
                                    wrote on last edited by
                                    #74

                                    Can I suggest, humbly, that; 1. Having a function 200 lines long is not neat code anyway. 2. Re-using a variable for multiple purposes inside the same function is bad for neatness anyway... you should name your variables with meaningful names and only use them for their intended purpose. Perhaps you might occasionally create a temporary primitive type to perform some work on before assining it to a well named var, but then it should be named temp and no one should rely on it's value outside of the 4-5 lines that perform the initial operations... any code in the same block that wants to re-use it should reset it to a default value intead of relying on whatever it was last set to.

                                    1 Reply Last reply
                                    0
                                    • E El Corazon

                                      mhaines@1amadeus.com wrote:

                                      I am already using two monitors, so I am talking about REALLY long lines!

                                      so use two 30" monitors.... come on, use it as an excuse... you know you want them!

                                      _________________________ Asu no koto o ieba, tenjo de nezumi ga warau. Talk about things of tomorrow and the mice in the ceiling laugh. (Japanese Proverb)

                                      T Offline
                                      T Offline
                                      Tim Yen
                                      wrote on last edited by
                                      #75

                                      I really hope your joking. I use two monitors but a line of code that goes over one screens width is waaaaaay too long

                                      1 Reply Last reply
                                      0
                                      • R Ri Qen Sin

                                        So somewhere on the internet, I pointed out to a newbie that his code was pretty messy and that he should start by consolidating some of his variable declarations to the beginning of the program (which was consisted of only a main(…) function/method/entry point and a lot of improperly formatted code). In walks another forum member and criticizes me for my comment saying that "it's a feature of the C++ language to be able to declare variables anywhere you need it." I was obviously pissed at that comment showing his utter disregard for code neatness and readability (and likely a malicious attack on my intelligence). I'm trying to seek agreement… so was I right when I said so?

                                        So the creationist says: Everything must have a designer. God designed everything. I say: Why is God the only exception? Why not make the "designs" (like man) exceptions and make God a creation of man?

                                        T Offline
                                        T Offline
                                        Tim Yen
                                        wrote on last edited by
                                        #76

                                        I'm surprised in a talk about code neatness short methods don't come into the mix. I personally have a metric of no method longer than a screen. It's easier to give it "Functional" coherence if its short, which makes it easier to understand for me. Usually a method with two blocks does not have functional coherence, so I split it into two methods. The book "Code Complete" argued that long methods didn't matter as far as bugs were concerned but it sure makes it harder for readability for me. I always give each variable as little scope as possible, it's easier to read for me and avoids variables accidentally retaining state between multiple blocks (which i avoid see above) and then let the compiler optimize the variable allocation. All in all I have a "break it down to its smallest blocks" mentality

                                        1 Reply Last reply
                                        0
                                        • Y Yortw

                                          Hi, Here's my two cents ;) I used to think this was just a personal choice (unless company coding standards said so), until I tried debugging code with the (class-level) declares scattered all over the document... it made me dizzy watching the code window leap all over the place, and it seemed slower. I've gone back to declaring everything at the top. In fact, in C# I even have a region I place all my class level declarations in. In specific methods, I generally only declare variables at the top of the method if I'm going to use them in side various branch statements, if they're only used inside a single branch then I declare them there. The comment about declaring them late to prevent unneccesary construction, would at least in some languages, only apply to variables that were set to a new value during construction, rather than simply declared, and is more about performance of the code rather than readability or maintainability. As for the comments about long lines of code... I used to care about this too, until I realised some of our other company developers still have a single monitor at 1024x768... at which point, in C# with various docked windows, 15 characters is too long. Basically, you never know how big someone's text window is, so I just write what I consider 'reasonable' for the paritcular line, and if someone complains, they can reformat it. Oh, but my code lines are usually shorter than my sentences :)

                                          T Offline
                                          T Offline
                                          Tim Yen
                                          wrote on last edited by
                                          #77

                                          I agree in C# private and public class level declarations should go in regions at the top. I split public and private into two regions and I avoid public member variables. I also avoid classes longer than 1000 lines too if i can.

                                          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