What do you think is the best programming style?

8    31 May 2015 10:14 by u/V-sync

For languages with curly braces I use something like kernel style which looks like

int main(int argc, char **argv)
{
        switch (argc) {
        case 1:
                if (argv[0][0] == 7) {
                        thing();
                } else {
                        other_thing();
                }
        }
}

What's your favorite style and why do you like it?

12 comments

4

I don't have a favorite style, but I favor and encourage copious amounts of comments. As someone who has poured through thousands of lines of code, sometimes that little short comment makes all the difference!

2

Comments are a good thing. However too many of them make the code less readable. There is no need for a comment explaining what each line does, the code does that; the comment is to explain why.

2

I agree, there obviously needs to be a balance. Many times I've had to figure out what the coder was trying to accomplish with a particular piece of code and the code had little to no comments making it a lot of trial and error and frustration.

I've also worked with code where there was more documentation on a particular application than there were lines of code for the application. And that was just ridiculous.

So somewhere between none and too much. But I prefer more than less. That way your code can always be updated by someone else. If someone can't figure out a section due to missing comments, then your code will not last very long.

1

I like the JavaDoc approach of commenting code. (Please don't hurt me)

2

Whatever the convention of the language/codebase is. If everybody else on the project is using GNU-style brackets, new code will be more understandable if it's written like that.

Having said that, there is a special rung of hell reserved for programmers that don't write XML end tags on new lines like this (it makes adding new attributes so much easier):

<element
    attr1="foo"
    attr2="bar"
/>
1

Whatever I can automate with clang-format or autopep8. Style is mostly a distraction when it's inconsistent. With modern editors and autoformatters that can do a better job than I can, I can focus on meaningful edits.

1

I'm a big "C Style" fan, which I would describe as exactly what you have posted. It took me a very long time to get used to the "JS" style of

function a(int argc) {
      ...
}

But its growing on me... Now personally I much prefer variables in a camel case style with a description of the type so instead of

int argv;

it would be

int nArgv;

However that makes little sense in a loosely typed language which is why I am now starting to lean towards the GoLang approach of public variables starting with an upper case such as and private being lower then mix-in the type:

var ( 
   string sPhone
   int nAge
)
1

For C I stick to K&R but put function names on their own line apart from the return type.