Well, "good practice" and "bad practice" are tossed around a lot these days - "Disable assertions in release builds", "Don't disable assertions in release builds", "Don't use goto.", we've got all sorts of guidelines above and beyond simply making your program work. So I ask of you, what coding practices do you violate all the time, and more importantly, why? Do you disagree with the establishment? Do you just not care? Why should everyone else do the same?

cross links:

What's your favorite abandoned rule?

Rule you know you should follow but don't

link|improve this question
1  
Note that the reason for closing this requires an EXACT duplicate, which this isn't. Similar, yes. But it's not an exact duplicate of those questions. – Jason Baker Dec 9 '08 at 3:24
show 17 more comments
feedback

migrated from stackoverflow.com Jun 22 '11 at 17:50

This question came from our site for professional and enthusiast programmers.

closed as not constructive by ChrisF Feb 18 at 13:15

This question is not a good fit to our Q&A format. We expect answers to generally involve facts, references, or specific expertise; this question will likely solicit opinion, debate, arguments, polling, or extended discussion. See the FAQ for guidance on how to improve it.

42 Answers

1 2
up vote 87 down vote accepted

I reinvent the wheel. Every Time.

why?
Because I like to know 'how stuff works'.

I do look at how other people solves the same problem. But in the end, I rewrite the code myself and try to learn something new along the way.

Exceptions:
  Never roll your own crypto!
  You can't tackle i18n on your own.

link|improve this answer
2  
This goes along with what Joel stresses. Find the dependencies and eliminate them. If it's a core business function, do it yourself. And probably a few other quotes I'm forgetting. – Kibbee Dec 8 '08 at 21:07
5  
+1 for me-too. I find it horrifying when I see people telling others to use a 100KB javascript framework for a one-liner just because they can't be bothered learning to say "give me all links with this class name" in JS themselves. – Ant P. Dec 8 '08 at 21:16
7  
Often true but this runs the risk of assuming you know everything and others know nothing. This has led to people rewriting things unnecessarily on projects I've worked on. It's a double-edged sword. – Jeff Yates Dec 8 '08 at 22:14
1  
ffpf: amen. A perfect example is security and cryptography. The same developer who says, "Write everything yourself!" will also say, "Never roll your own crypto!" – Lucas Oman Dec 9 '08 at 14:21
3  
That i18n exception is soo true... – Alix Axel Jul 7 '10 at 13:21
show 6 more comments
feedback

I break the "One exit point from a function" rule to enable the use of "Guard Clauses" Example:

   String doSomething(String param1, Object param2) {
      if (isEmpty(param1)) return "";
      if (param2 == null) return "";

      // rest of method
      return result;
    }

Most of the time I would throw and exception if the arguments are illegal, but some of the time a return statement is fine...

link|improve this answer
4  
It's not really an official bad practice. It was but not anymore, maybe it depends of the language. – Daok Dec 8 '08 at 21:10
15  
That is more like a 'best practice' if you ask me :) – Jacco Dec 8 '08 at 21:11
6  
I like these for argument validation at the top of a function. If I see one way down in the middle somewhere it makes me nervous. – Joel Coehoorn Dec 8 '08 at 21:33
show 11 more comments
feedback

I use tables for layout in HTML.

link|improve this answer
3  
Guilty. I find them easier to maintain and manipulate, and I can (almost) always make them work in all major browsers with little tweaking. – Michael Itzoe Feb 19 '09 at 13:43
3  
It's not really a case of "making them work" it's a usability issue and not symantecally correct. Tables should only be used to display tabular data and nothing else. Try running your site through a screen reader and see if your web page reads well? – Sheff Feb 19 '09 at 14:17
2  
use blueprintcss it'll make a tableless layout easier for you. – DMin Jun 22 '11 at 20:17
show 1 more comment
feedback

Start coding before a "design" is completed.

Working code is a lot easier to judge and review than a bunch of box-and-line diagrams drawn by someone who is too important to write code anymore.

And the sooner you write something, the sooner you can re-write it to be the way you should have written it in the first place (and no, an up-front "design" does not eliminate the need for this).

link|improve this answer
3  
+1 Depending on what you are designing/developing, coding can be the best way to design. I often find myself writing a unit test just to experiment with different API designs. The unit test is the first client, and you discover awkward constructs other ways of designing would not reveal. – Bent André Solheim Dec 8 '08 at 22:44
1  
It's ok if you call it prototyping or de-risking. – JeffV Dec 10 '08 at 1:14
show 3 more comments
feedback
if (c==0)

instead of:

if (0==c)

Just because the second one looks really goofy to me. Modern compilers warn you anyways...

link|improve this answer
1  
What's wrong with the first one? It reads better. Are you coding in C, where the compiler won't warn you if you mistype as C=0 – Anthony Dec 8 '08 at 22:53
5  
Not bad practice. – TraumaPony Dec 9 '08 at 1:37
2  
The second is usually preferred because you will usually get an error, not just a warning, if you try to assign to an rvalue. – Kris Kumler Dec 9 '08 at 4:52
10  
treat warnings as errors instead. Yoda Conditionals are hard to subvocalize, therefore create more cognitive load on the reader. – Pavel Radzivilovsky Jul 7 '10 at 13:38
show 3 more comments
feedback

I do Unit Test after the whole section of code work. I do not do them before, not even in the same time. Once it works, I do unit test... and some time, I just do not have the time to Unit Test everything...

link|improve this answer
show 3 more comments
feedback

I hack. Occasionally when needs must and time-frames are short you have to add in cute tricks as opposed to completely restructuring a massive swathe of the system.

We had race conditions appear in a certain critical part of the application and to remove those "properly" we would have needed to modify a large amount of APIs and we needed to release a version to test for the next day. The answer? A globally available lock.

Yes, it's bad practise, yes its a hack but yes we also met our schedule. The globally available lock is heavily commented and scheduled for a tidy later on.

Hacks ain't always bad.

link|improve this answer
3  
And even when they are bad, there is such a thing as acceptable evil. Getting Things Done is more important than perfection. – Erik Forbes Dec 8 '08 at 21:15
1  
Amen to Getting Things Done. I'd love to be able to write pure, perfect code -- but clients don't ever want to pay for it, nor do they want to wait for it. As long as most of the code is good, the occasional hack (well-documented, as described) is an acceptable evil. – John Rudy Dec 8 '08 at 22:28
show 2 more comments
feedback

I can't leave messy code alone. Even if it works perfectly and even if i should be doing more productive work.

Turning spaces into tabs, fixing brace positions, adding spaces between code lines where i feel it fits. Sometimes i waste way to much time doing just this.

link|improve this answer
3  
Hey, that's me! – presario Sep 23 '09 at 10:33
show 2 more comments
feedback

I (ab)use Perl one-liners:

my $cdata = {map {shift @$_, {map {$_ => 1} @$_}} map {[split /[:,]/, $_]} split ';', delete $config->{Entry}};

I know that it makes my code unmaintainable by other developers, but I love the intellectual challenge off doing the most work in a single line.

link|improve this answer
14  
Securing our own job are we? =D – Nailer Dec 8 '08 at 21:28
3  
This is precisely the sort of code that turns people (myself included) away from the Perl language - too many Perl programmers are more interested in proving themselves than making something understandable. I can't count the number of Perl 'tutorials' that feature code like this. =( – Erik Forbes Dec 8 '08 at 22:22
1  
Gotta say, the intellectual challenge of writing one-liners in Perl isn't really that great, it's usually a matter of writing readable code, then copy/pasting it onto a one-liner with some variable renaming. The real intellectual is the one who rewrites this later using 3-5 readable lines. – Adam Bellaire Dec 9 '08 at 14:27
1  
I must say your spot on with regards to bad practice. If I had to maintain your code I would rather have a bullet through my head. This is the reason I don't do perl. – martiert Jul 7 '10 at 13:42
show 13 more comments
feedback

In all creative human endeavor, there seems to be a cycle of three phases:

  • Random experimentation. (results wildly hit or miss)
  • An establishment of the "rules" (results solid, but lacking creative edge)
  • Top artists, having mastered the "rules" now know when & where to break them (maximum artistic result)
  • then, lesser artists, who have not mastered the rule, break them randomly, and the cycle begins again.

(In Rock music, those phases roughly translate to the 60s, 70s and 80s (and then the 90s)

The point of this is to say, that once you has mastered the rules, all should be followed, until the exact time when it is best to break one, and at that time, any rule could be broken.

UPDATE: I've expanded on this theory on my blog.

link|improve this answer
show 5 more comments
feedback

Guilty secret here. I regularly create Regular Expressions (no pun intended) and don't comment them. I then spend the next week trying to work out what the heck it was that I created, before adding the comments in afterwards. I always say to myself "This time is different. This time I will remember what it actually does." One of these days, I'll get out of that bad habit.

link|improve this answer
show 2 more comments
feedback

Copy and paste programming. I tell my self I will refactor it later but usually don't unless it bites me in the ass repeatedly.

link|improve this answer
1  
I do this, usually I need a method and I know I have a similar one in another program. So I get that and modify it a bit. If I spent a bit more time I could probably make it more generic and put it in a dll for use by all my progs. Never do find that time though. – PeteT Feb 19 '09 at 14:22
feedback
for(int i=0; i<20; i++) {
    someFunction("magic string literal");
}
  • java style braces
  • 1-letter loop variables
  • literals in code
  • spaces instead of tabs
link|improve this answer
7  
I think the string literal is the only thing wrong here. The brace style is debatable, but I like 1-letter loop variables, and I strongly encourage spaces instead of tabs. – Bill the Lizard Dec 8 '08 at 21:03
1  
Yeah - brace style is a matter of, um, style. =) – Erik Forbes Dec 8 '08 at 21:14
5  
The convention of using 'i' as a loop counter is so universal, I think it's a bad practice not to do so. – Alan Moore Dec 8 '08 at 23:15
3  
Wait, Java-style braces are a bad practice? I write that way, what's wrong with it? – jhocking Jun 22 '11 at 18:39
show 7 more comments
feedback

Whenever I am allowed to, I use nonstandard indentation and brace style in curly languages. I believe that almost any style is OK, as long as some care is taken to point out the different statements' relation.

  • For me, every statement ends with a semicolon, including after closing braces.

  • For me, an if statement has four arguments: a condition, a clause, and optionally the else keyword followed by an else clause (in my opinion, the else keyword is superfluous, by the way). These four statements are aligned to the same column:

    if (condition)
       { some;
         instructions; };
    

    or

    if (condition)
       { some;
         instructions; }
       else
       { something;
         different; };
    
  • If I believe that some code needs more space between lines, I add blank lines.

edit: Please note that this formatting is very consistent: all parts of the same syntactic level are indented the same. Note the symmetry between (condition) and else. Please, also take a look at the Wikipedia article about Indent to see some other styles that are used.

edit: Another advantage is that in this style, I can consistently format longer compound statements, like for example what nrich presented:

my $cdata = { map { shift @$_, 
                          {map {$_ => 1} @$_} }
                  map {[split /[:,]/, $_]}
                      split ';', delete $config->{Entry} };

See? No need to get scared.

link|improve this answer
2  
It's a bit odd admittedly, but I don't see anything that makes this unreadable. Although, it might end up being a pain to maintain. – Jason Baker Dec 9 '08 at 3:26
1  
By the way, if you think that this is bad practice, you should UPVOTE it in the light of the question. – Svante Dec 9 '08 at 4:19
show 5 more comments
feedback

Well, the best case is, to do it all wrong once.

Nothing beats own experience.

link|improve this answer
1  
Just don't do it in a bomb factory, because you'll only have one chance. – Cristián Romo Dec 22 '08 at 17:43
show 1 more comment
feedback

I commit changes to source control that combine complex logic changes along with unrelated, wide-sweeping stylistic changes that don't modify the affected code's behavior. As I'm making changes to existing (legacy) code, I find myself peeking at neighboring functions, etc. and can't help but thinking that I should just tweak that code while I'm there--perhaps making it more consistent, perhaps making it easier to read/follow.

This is a less than great idea, but I continue to find myself doing it, perhaps almost compulsively. It has ended up causing pain for me, particularly when I've needed to get peers to review the overall changes or when I've needed to submit the changes for approval. Either the reviewers curse me for causing them to pore over unnecessarily large diffs, or the change actually gets rejected by a fearful manager/reviewer who fears that it's too risky. After these changes get checked in, it also causes confusion to anyone perusing source control history--perhaps making it easy for them to miss the interesting change amidst the Grand Re-tabification.

When in doubt, don't do as I do. Check the changes in separately :)

link|improve this answer
1  
I edit multiple things at a time, but because I use git for everything, I can still commit (and test!) the changes separately. FTW. – Xiong Chiamiov Jun 3 '10 at 22:40
show 3 more comments
feedback

In all of my complex UIs in Flex, .Net and Java Swing, I always use a central Universe object which is a Singleton. It's an easy way to get at all pieces of the application.

link|improve this answer
2  
That is a fun name, but I bet that practice is going to come back and bite you...singletons are most often misused. – Matthew Rodatus Jun 22 '11 at 18:39
1  
@Yar Even if it's mockable, it's still less flexible than regular, instantiable classes. If you ever need to go to a sessionless service model, you'll need to use some sort of injection anyway (a provider for the authentication verification). I find it simpler and more maintainable to make the dependency injection as visible as possible, rather than buried inside a singleton. – Matthew Rodatus Jul 5 '11 at 11:19
1  
@Yar Often there is a static service locator, but there doesn't need to be. There are better ways of wiring up dependencies. With dependency injection, you can just construct the dependencies of a layer at the layer above and pass them into the constructor and so forth for all the layers. Then you also use those same constructors to pass in mock implementations for tests. That is a cleaner abstraction, since the dependencies are parameters (which can be changed per instance) rather than a global reference buried deep inside the code. – Matthew Rodatus Jul 13 '11 at 10:52
1  
@Yar Dependency injection also makes maintenance easier. If you ever need to change that Universe object, you're going to have to change all reference sites. At which point you will want to shoot yourself. I'm working on a maintenance team, and the app we're working on has objects like that. Even though we added a public static setter (so we can mock them), they are making maintenance and scalability more difficult. – Matthew Rodatus Jul 13 '11 at 10:53
1  
@Yar You could make the service locator a class that you instantiate and pass down into relevant classes. It could implement different interfaces (ISomethingLocator, ISomethingElseLocator) so that the relevant classes aren't dependent on all the factory methods. This approach allows late OR early binding and avoids ugly constructors with many parameters. Another approach is to have a default constructor in each relevant class that instantiates the dependencies, providing them to another constructor with all of the dependencies parameterized (which would be used for unit tests). – Matthew Rodatus Jul 13 '11 at 14:12
show 7 more comments
feedback

I use goto to emulate a labeled break in c++.

link|improve this answer
feedback

First Code, then think.

And I don't refactor/rename/restructure often enough

link|improve this answer
feedback

I use tables for layout sometimes in HTML, I can't ever seem to get css layouts to work right. But I'm a programmer, not a fancy pants designer. :)

And I constantly forget to use stringbuilder in C# instead of +=

link|improve this answer
feedback

I like brace-less if-statements. I know it is bad but I love the simplicity of:

if (param == null) throw new ArgumentNullException("param");
link|improve this answer
5  
Well, if someone changes it from single line to multiple lines without adding the block delimiters, then he is to blame for anything that happens afterwards, not the one who wrote the original one-liner. – Svante Dec 9 '08 at 14:27
show 4 more comments
feedback

oh dear...

I commit "broken" builds. For pragmatic reasons mind you...

I develop on (at least) two machines - my home machine and my work machine. When it comes for time to going home, I commit my work which goes onto our production server and check it back out when I get home and carry on. Sometimes this is in a development branch, but often not. However:

  1. we're a very small team

  2. we're not working on code that "builds" per se - it's web application development

  3. we tend to be working fairly atomically - if I'm working on a particular controller it's unlikely other members of the team are also working on it

So in practice it rarely causes a problem. It's one issue, that though we've looked at distributed version control systems (I like the look of Bazaar), we will always need to be able to push the things we're working on somewhere that we can get to them from elsewhere...

link|improve this answer
show 1 more comment
feedback

The most fundamental thing concerning stuff like "best practices" is that you should know what you're doing. If you aren't sure, stick to the "best practice". If you are sure that you fully understand the reason for one of these "best practices" and the consequences, you can vary depending on how you like or the situation requires.

Take GOTOs: The reason for them being banned is that wild GOTOs can make programs difficult to understand and get into an undefined state easily. But especially in C/C++ that lack local functions, it is usually accepted to use them in error handling and cleanup code.

Assertions in production code are a question of what you want: Do you need a correct result (say, accounting) or do you need maximum performance (say, 3D games, ...). For my part (application software, frontend and backend), I've made good experiences with letting them in the code. If the programming language and compiler support that, overflow checking, array range checking and stuff like that should also be enabled, at least during testing. I know cases where checks in production code helped finding errors that occured after years of operation without problems. Some of my customers have the company standard of even to disable compiler optimisation and leave debug code in, although both causes a huge performance "poenality", because correctness and reproducibility, also possible analysis of core dumps, is more important for them than maximum performance.

In my view, the most important task in software development is the reduction of complexity. In most cases it is OK to accept a performance downgrade if it can improve the reliability and maintainability of software.

A point where not too many compromises should be made is error handling. The very least thing you want to do is check for all relevant errors (e.g. return codes) and give out a message where exactly an error occured and with which parameters, ... This can be a lot of work (some statistics claim that error handling can make up more than 80% of a program), but you save most of the time spent there later during debugging.

link|improve this answer
show 1 more comment
feedback

I use SCREAMING_CAPS for my constants in C# (because I find it makes my source easier to read). I also use multiple returns per function where the alternative would complicate the flow of my code (I try to avoid lots of nested ifs whenever possible). Finally I'm guilty of coding before the design is fully complete, but I find this is the best way to proceed in the majority of cases, because my team runs an agile methodology and often many factors are only discovered after coding begins, so it often feeds back into the design process.

Great question by the way :)

link|improve this answer
show 1 more comment
feedback

I document asymetrically. Classes and interfaces which go public I document thoroughly and extensively. On the other hand, code I know no one will ever see I barely document at all.

link|improve this answer
feedback

I use var all over the f!#@ing place because I'm lazy as sin.

link|improve this answer
feedback

lock (this) { ... }

I know it's wrong - I worked on CLR/.NET reliability. Someone else can lock on my public object and can therefore corrupt my locking strategy. But I hate allocating a new object for synchronization. Don't tread on my object!

link|improve this answer
feedback

I often reinvent the wheel, partly becaus it's nice to know how stuff works, and partly because I'm suspicious about third party code.

link|improve this answer
feedback

I can't be the only one who makes their member variables public rather than having getters and setters with nothing in them.

link|improve this answer
feedback

When declaring variables, i need to have the variable names vertically aligned, so i can end up with something like

int                          i;
StringBuilder                sb;
VeryLongStupidClassName<Foo> baz;

And, worst of all, i do it WITH SPACES.

Evil, I know.

link|improve this answer
show 1 more comment
feedback
1 2