r/learnprogramming • • Jul 12 '13

What are some bad coding habits you would recommend a beginner avoid getting into?

Whether they're stylistic habits or program design habits. I'm learning java and want to be sure to write my code as efficiently as possible to avoid lengthy code and poor design choices.

250 Upvotes

215 comments sorted by

View all comments

Show parent comment

31

u/arimnaes Jul 12 '13

As a corollary to this - comments are just one solution to the problem of hard-to-understand code, so the more general advice would be "write code that's easy to understand." This encompasses several points, including but not limited to:

  • Write code that is as close to English (or other spoken language) as possible. Give methods, parameters, and variables clear and descriptive names. Conciseness is also nice to have, but usually err on the side of long and descriptive rather than concise and ambiguous.
  • Don't perform clever tricks to shorten your code like folding ++ operators into unrelated statements and performing assignments inside conditionals - you almost never get an actual performance increase and it will make your code much harder to understand.
  • In imperative languages (Java, C, C++, C#, etc.), keep the execution flow of your code as linear as possible. Mostly, this means avoiding goto statements. They are almost never the right solution when structuring your code.
  • Use line breaks to separate logically distinct groups of statements. If a group of statements gets very large, consider putting it into its own method with a descriptive name. When your methods are well-named and mostly consist of calls to other methods, they are very easy to follow.

Comments are a subject on which there are as many opinions as there are programmers, but my opinion is that they should only be used as a last resort. Writing your code in such a way that it speaks for itself is always superior. Unlike code, comments can lie - they can and do get out of date as the code around them changes, and a misleading comment is worse than no comment at all.

9

u/[deleted] Jul 12 '13

I've been programming in C# for at least 2 years now and I didn't know it had goto O_O

4

u/istroll Jul 12 '13

To add to this. Comment why you did something, not necessarily what you did. I can see what you did, I want to know why you did it that way if it is unusual or if you found out some tricky issue that needed handling.

1

u/Dankleton Jul 12 '13

Agreed. I'd express it as "comments should say what code can't"

If you thought of 3 ways to achieve the same thing, write a comment about the two that you didn't use and why the way you chose was best. If you're using an unusual technique which is documented somewhere else, reference it.