views:

5067

answers:

99

I'm a new programmer in college and was wondering if there are any bad habits to watch out for early on. Anything that you wish you knew to avoid when starting. Thanks.

+40  A: 

Not writing unit tests.

CodeToGlory
Arg! When I saw this question I thought "not writing unit tests" and then I looked and it was the first answer.
Zifre
I wish somebody was there to tell me in school several years ago..some how this aspect is totally lost in our schools and universities.
CodeToGlory
Even though vital for high-quality software, this practice generally clashes with real-world pressures and deadlines. In open source, totally - but good luck convincing business people that you have been doing something other that "create". A lot of us "just do it", on our own time, but that can get old if you are not billing by the hour, eh?
Andrei Taranchenko
In answer to the pressure not to do anything other than "create", in many cases writing tests helps you with that creation task. TDD is the obvious example, though you don't have to go full-blown TDD for testing to help you write your code. Before I started writing proper unit tests I still found myself writing code to test my classes, I just didn't keep that code.
thomasrutter
@CodeToGlory: +1 Agree. Designing the software and emiting the code is so much easier when you have an example of how it would be used.
TokenMacGuy
In practice, the higher cost of code failure the more one should adopt unit tests. Code for the space shuttle should be well tested.
Velika
Best answer yet!
Toran Billups
+19  A: 

Don't get hooked on just one programming language, learn what that language is good for and what its not. Learn to use the right tool for the job.

Decio Lira
I disagree. If you can become fluent in one language, especially a general-purpose one (Python, C, Java, etc.), you can do just about anything.
Tony
One language is just a tool you need to know how and where to use. You cannot work in Python if you are in a team proyect that doesn't use it, or if you are fixing code already done in another language. Not always one language can solve all your problems. For example if PHP or ASP.NET or JSP is not installed in the server that your client is using and paying, you just have to use the language that is already there. Simple as that!
backslash17
Agreed, you don´t wanna have just a hammer in your toolbox.
Decio Lira
+10  A: 

Don't duplicate behavior by copy and paste code.

Theo Lenndorff
+15  A: 

Think 100x longer about the code before you write it. Don't just start spewing spaghetti

Chad Grant
Are you serious? 2.5 weeks of thinking for every hour of programming? You'd only be able write code for about 1 week every other year. Now that's productivity.
tvanfosson
I disagree with this. If your code starts becoming spaghetti, then you need to refactor and move on. Some of the coolest things I've worked on, started as a mess of methods just to prove it could be done but then was refactored into a robust extensible thing...
JoshBerke
I am traditionally tasked a project long before I start it and I think about how I will implement it and the new features weeks before I actually do which results in cleaner code and increase in productivity. Sorry you don't agree. It's more of a statement about newbies anyways and so many NOT thinking before coding. But I am probably unusual and OCD about code.
Chad Grant
+1 - So many problems seem obvious and avoidable when given some proper thought. You could save a day of refactoring (and a day of writing the original) if you just think for 20 mins before 'coding from the hip.'
SnOrfus
+1. The 100x is an obvious hyperbole. It's much better to think about the problem and the solution before diving right in.
Min
codes are read more frequently than they are written. So spend more time before you write a code as that one line might become a legacy code down the line in your project, when you are long gone.
zeroin23
+140  A: 

Copy and paste programming is probably one of the worst habits that one can develop while starting to learn programming. Learning how to program is best achieved by writing code and understanding other people's code. If you copy/paste code without understanding what's going on, you are doing yourself more harm than good.

Ayman Hourieh
Yeah, even when I'm just copying someones code example, I"ll still type it out by hand to learn it more thoroughly.
CookieOfFortune
Agree - I once heard this called "cookie cutter code". It seems good until you need to change it. Then you've got multiple copies to change, and if you miss one you're created a bug. Moral - DRY (don't repeat yourself).
Mike Dunlavey
Sounds right to me. Looking at other people's code is good, and can give you a head start. But if you want to tinker with a little demo application of someone's, you can copy and paste it, but then start changing things so you get a good understanding of how it works. Don't just add to the code, try changing what's already there.
MBCook
There's two aspects to this -- copy/pasting other people's code, and copy/pasting your own code. Both are bad. If you find yourself copy/pasting your own code in the same program, you're doing something wrong. Refactor it.
Andrew Coleson
jdt141
@Andrew: 90% of the time, it's bad. But when doing things like initialization, or creating a new class, sometimes copy and paste is the way to go.
Andrei Krotkov
Most of the time when I copy and paste my own code it isn't business logic, but just the cruft that is necessary when coding in that language, like Andrei says, the code for declaring a new class is a decent example.
thomasrutter
I think cut and paste is good though ... it's a low budget refactor ;)
Chad Grant
@Deviant: Copy and paste coding is the exact opposite of refactoring. Refactoring is Cut, Paste, Delete Programming
TokenMacGuy
I can't +1 this, I've managed to learn a lot by copy/pasting code and modifying it slightly. True, you don't learn it right away, but I've found that by copypasting code that works, testing to see if it does what I want, and then going back and looking at how what I wanted to do was accomplished, I can learn how to use oject or learn new concepts.
Sukasa
Hey, copying and pasting is fine, as long as you post a big GUID marker on everything you copy and paste! http://www.codinghorror.com/blog/archives/001257.html
mquander
-1, I learned more using copy and paste than in HighSchooL
e-satis
Copy-and-paste, trial-and-error learning is a great way to learn about a reality almost, but not quite like our own. Unless you enjoy fixing subtle errors caused by misunderstanding stemming from "empirical" learning, don't bother---go pick up a book.
Derrick Turk
+19  A: 

Comments. Comment everything you do. You will thank yourself later, and so will your teammates. Besides, it makes documentation writing easier/unnecessary.

Joey Baker
Better to write code that doesn't need comments to be understood.
tvanfosson
just don't comment, you have to learn what to comment and how.if I see another // increases by 1i++I swear to God...
Decio Lira
my opinion is that properly written properly unit tested code will need 1 comment for every 20 lines; you're just adding a second set of code to maintain -- that's not compiled and is only vaguely coupled to what the actual code is doing
jcollum
Comments Lie. If your comments are explaining the how, then they are not good comments. Instead of explaining the code in comment form, refactor it so that it is more understandable. The comments should ONLY express the WHY, as in 'why would anyone want to do this?' or 'why did you use this algorithm instead of that' or 'why does this even work at all?'
TokenMacGuy
I upvoted you. I think comments are imperative for team environments, especially in circumstances where others will likely touch your code during maintenance.At work, I'm currently in the processes of debugging horribly written code by an engineer who was fired. My efforts would be greatly reduced had he written comments that briefly explained what the code is supposed to do.
hypoxide
90% of the time you find yourself writing a comment to explain what some function does or what some variable is for, it means you picked a poor name for that function or variable. Name things so as to make their role obvious.
glenra
+1 This was a question about beginners who are going to write crap code no matter whether they comment or not. Better off at least knowing what they were trying to do than to trudge through it trying to figure it out.
SnOrfus
I write a comment for every method/function describing in brief what it does and what it returns, good for documentation afterwards, otherwise it probably averages a single comment every 10 to 20 lines.
thomasrutter
90% of the time I spend debugging other peoples code is spent cursing the ones who thought their code clear enough to not write any comments. Far too often they were wrong.
David Sykes
I think a corollary for this would be to keep comments either up to date or delete them. There's nothing worse than an out-of-date comment: It wastes your time and it makes you distrust the rest of the comments in the code.
cdmckay
+16  A: 

Don't get too stuck into the computer mode of thought. It does you little good to brilliantly solve the wrong problem with elegant code.

Customers are smart people, but they don't speak our language. And they pay our salaries. We need to come to them and learn to translate their requirements.

jrcs3
+11  A: 

This should set a bad example, while this is more positive (and serious).

msiemeri
+1 for the first link - what a hoot
Preet Sangha
+28  A: 

learn these by heart so you know when you are repeating them http://en.wikipedia.org/wiki/Anti-pattern

Chad Grant
+1 I regularly look back over these just to refresh.
Lucas B
+9  A: 

Have a look at programming anti-patterns.

Guffa
+2  A: 

Not analysing anything before programming

eKek0
+7  A: 

If half-year later you'll think that you are "guru" in C++ (or java or any other language or technology) then it'll be you great mistake. Your should always know a little more than other but you should think that you still don't know anything. It's a key to success in programming. Learn, learn and learn again.

Roman
That's right. Consider Norvigs "Learn Programming in 10 years": http://norvig.com/21-days.html
msiemeri
+47  A: 

Don't optimise prematurely.

Donald Knuth made the following statement on optimization: "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."

Rob Kam
I like that 97% qualification, because most of the time people just say "don't optimise prematurely" and leave it at that. A seasoned programmer knows what is worth optimising and what isn't, and most code isn't.
thomasrutter
I actually think this is some of the worst advice that gets passed around. Most developers these days seem to confuse programming efficiently with premature optimization. If you're Knuth or one of his colleagues, this is great advice. Otherwise, it's often used as an excuse for sloppy programming.
Travis
Travis has an excellent point. There are order-of-magnitude differences between algorithms you'll see students write in an intro programming course - e.g., unneeded triple nested loops, recursion without caching, etc. A colleague looking for CS grad student help at a major university (with a good CS department) gave candidates some simple tests - he had people writing O(n^3) algorithms for problems that were O(n log(n)). You don't want this kind of poor design to be excused because you "shouldn't optimize prematurely."
Mike Kantor
Yes, you do. O(n^3) doesn't matter if n=5. It really depends on the combination of algorithm, input and available resources. And that is hard to predict, which is just Knuth's point. See also http://stackoverflow.com/questions/474714/what-optimizations-should-be-done-early .
sleske
I think all of you in the comments are misinterpreting. Converting an n^3 algorithm to an nlogn algorithm is not "optimization", its basic. Premature Optimization is converting an algorithm of 8nlogn+2n+17 algorithm into an algorithm of 7nlogn+n+9, wasting time and usually introducing bugs in the process, while the program performs 100 times faster then it needs to be anyway.
Neko
Neko makes a good point. There is a difference between designing for efficiency and optimizing for efficiency. Good design should always be done, but optimizations are only useful when your code has been shown to not be fast/small/whatever enough.
Joren
Premature optimization means optimizing something that doesn't even *work* yet. See also: http://stackoverflow.com/questions/58640/great-programming-quotes/1649033#1649033 Once the thing you're creating *works*, it's a good time to optimize.
Kyralessa
+69  A: 

Using poorly named variables.

hypoxide
Also, it's better to use a bad naming convention and stick with it than it is to not use a naming convention. If you don't like your naming convention, refactor - or just use a new one next time.
Dean
Don't abbreviate. In the age of autocompletion there's no need to write unreadable code just to save a few characters.
JC
So true. Good naming is really, really important.
Joren
+17  A: 

Refactor. Don't be afraid to re-do it. With proper design and good test coverage, this shouldn't be a problem. If it is, figure out why - you'll learn more from mistakes than successes.

[Edit] Er, don't be afraid to refactor I guess is how it should start :)

chris
A good way to approach this issue is the Brooks observation "Build one to throw away, you will anyway" even down to the function level. First attack the problem as quickly as you know what the problem is. You may go through a few iterations of getting a solution. Once you have a function that solves the problem correctly, immediately rewrite it so that it is elegant while the knowledge is still fresh in your mind. The alternative is to have to MAINTAIN it in its scrambled up state months or years later, which usually results in the whole thing being deleted and rewritten.
TokenMacGuy
+6  A: 

If you must optimize, don't be penny-wise-pound-foolish.

I've seen people sweat over which optimization level to use on the compiler, or whether ++i is faster than i++, on code full of function calls (i.e. p.c. never there) to multiple abstraction layers, sapping magnitudes of performance, while saving neither cycles nor dev. hours.

Mike Dunlavey
I remember an urban legend about a team that optimized the wait loop of an old school program. The program still spent the same amount of time in that loop.
jrcs3
*chuckle* That's terrible.
Erik Forbes
@jrcs3: I love it.
Mike Dunlavey
There should be a programming Darwin award.
Erik Forbes
+48  A: 

Not handling errors. Failing to check return codes, assert conditions or swallowing exceptions. Even in cases where it's "impossible", or "no one will ever use it again".

Rob
*Especially* in cases where it's "impossible"...
sleske
The problem with beginner programmers is that they still think "impossible" has the real-world meaning of "won't happen", while in practice "impossible" in programming means "will happen only after releasing the product and/or demo-ing it"
Neko
+5  A: 

Don't create solutions that are too elaborately coded and overly feature-rich - Keep it Short and Simple

Rob Kam
I agree. Who wouldn't? But I've seen 2 approaches to the same problem, both considered "clean and simple" by their builders - one was 10 times bigger.
Mike Dunlavey
A: 

If existing classes or functions don't have quite the behavior you're looking for, modify them to include it. Don't rewrite new classes/fucntions yourself. Duplication is very bad.

When your code turns to spaghetti, spend some time rewriting it to make more sense.

Comment liberally.

Use sensible names for classes, methods, functions, variables, tables, etc. Use a standard naming convention for each (camelCase, underscores, whatever... just think about it and stick to it).

Bob Ralian
+2  A: 

In OO languages, not knowing about high cohesion, low coupling. Or not caring about it (which means not constantly measuring).

Steven Devijver
+40  A: 

Not adhering to YAGNI is a big mistake. (YAGNI = you ain't gonna need it). Build what you need, not what you think you might need.

It helps when retaining a focus on the important things and the bigger picture.

Even at an API level, the intent of some functionality can be obfuscated by having multiple redundant additional methods or method overloads. Noise in a code base is annoying to work with. E.g. if you only need to load something in memory, don't provide an overload to load it from a file path "just because" you might need it in future.

This is especially the case when it comes to bugs. Unit testing finds a lot of bugs, but some will lay hidden until the functionality is actually used by someone. If you have code that is not being run, the bugs won't get found so quickly. Furthermore, when the bugs are discovered, that code might be ancient and the person who wrote it may not remember it, let alone be at the company any more.

Mark Simpson
Agree. Don't start by writing the "library" code. Start the project by writing the main() method, inventing nice names for the things you will need, as you write. Once you have written the main() method, just implement all the functions and objects it used and your application will be finished!
joeytwiddle
True, but misses an important aspect: generalising well can save you time/code and open up opportunities/create functionality. Usually it's worth the time spent.
sje397
It can be good, but trying to anticipate future use cases via speculating is very hit and miss. Unless there's a concrete case for it or it would be prohibitively expensive to crowbar in the generality, I err on the side of caution.
Mark Simpson
+9  A: 

Don't assume anything - ask when you don't know, and comment your code when you do.

Adam McKee
+1 - Too many people try to pretend that they know more than they really do and end up writing or speaking garbage. If I ask a question, simple or not, now I _know_ that I'm smarter than when I woke up (and I find that people love sharing knowledge, and generally don't care that I 'didn't know')
SnOrfus
A: 

Pick a style of indentation that makes sense (if your professors are giving you lots of code samples, the easiest may be to just use whatever they use) and use it. When I try to help people in my classes I'm amazed by how some of them are totally unable to indent their code in an organized way. (I would say it usually means their thought process is equally disorganized.)

Learn other languages. If your classes are all in C++ or Java, go online and mess around with Python or Lisp or Prolog. It's fun!

MatrixFrog
+3  A: 

One question i have always asked myself when doing code reviews and the like is, * Is this the result of being lazy, are there areas that could be improved ?*

By that i mean could the person have done better but skipped that bit because they

  • Is documentations missing
  • Could naming of variables, methods, classes be improved to be clearer ?
  • Is it readable ?
  • Are there tests covering all the possible code paths.
  • Are input parameters tested for validness.
  • Are there too many really really long - many screen methods ?
  • Are there any helpers - often they cant be bothered to extract.

Many times there are many vital things missing, the completed polished product will not have these.

mP
+4  A: 
  1. Procrastination.

  2. Arrogant.

Sake
So true. And these two often work together. Arrogance can lead to procrastination because by procrastinating, you don't have to face difficulty.
Tony
+23  A: 

Writing monolithic routines is one of the worst things you can do.

Try to write small, dumb code. Its harder to write code that looks like something anyone could write - that takes real skill.

Fortyrunner
If the routine doesn't fit on a printed page (or is browsable in your editor without using scrollbars or PgUp/PgDn, depending on your hardware setup) it should be refactored.
peSHIr
+1  A: 

Not paying attention to details.

Programming is all about details, yet it amazes me how many times I come across code where the programmer just did a sloppy job. Cut and paste jobs, duplicate code everywhere, and inconsistency across the code base are inexcusable.

It really comes down to refactoring. You wouldn't expect any other professional to just walk away when they finally got something "working". I'd hope the surgeon would pull his gloves out of me and stitch me back up when he/she's done operating.

One side note...If Visual Studio gives you a warning, treat it as an error and fix it! Don't leave that variable there if its not used. You know who you are.

Aaron Daniels
+50  A: 

A mistake programmers often make at the beginning, is to try to write the Whole Program, then compile it and run it. They will be bombarded with 100 compile errors, and even when compiled their program probably won't do the right thing.

The way beginners should start a project, is to make a small part of the program, compile and test it, and once it is working, move on to write the next part. Continuously re-running and testing your application, while you add or change only small pieces of code, is a great way to isolate any new problems in the recently changed code.

joeytwiddle
I always have that problem. It's really a problem of me being too lazy to write Makefiles, so I never compile the code.
Zifre
I suffered this problem and learned to write little tests as I coded, but now I write unit tests.
thomasrutter
I disagree with this, doesn't quite work for me. I like to code bigger parts at once, because that way I can keep all the program inside my head while coding. Then I switch to test/debug mode, which really is a bit different.
J S
Velika
This is sometimes referred to as "Agile programming" and I also like it. I usually Work in hourly to daily increments and try to get one step forward towards the goal - add a module here, add a module there, for each one doing a short test to see its working OK. Trying to locate bugs in a large system is something u wanna avoid as much as possible...
Neko
I'm a BIG fan of this. Hammer out the subsystem, throw in some unit tests, move on to the next subsystem. If it needs to be refactored because the big picture changes then at least you have something that *works* that you can fall back on if you go off the road somewhere down the line.
Repo Man
+4  A: 

Using all kinds of weird control structures to avoid one little goto. Everyone knows that spaghetti code is a bad thing, but one goto does not make spaghetti code. Everyone seems to believe that goto causes cancer and should be removed from the language. Way too often I see code that would be much easier to read and understand if it used one little if(something) goto somewhere; instead of things like do {... if(something) break; ... } while(0);.

Zifre
Everyone thinks one goto won't be harmful, but.... : http://www.xkcd.com/292/
kenj0418
+10  A: 

Putting off writing documentation until the last minute. This is one that bites me no matter how much I try to avoid it.

Jason Baker
+71  A: 

Not using source control.

There are a few instances where it is feasable to skip the source control. If you can count the number of characters in the source file on one hand, It's probably ok to skip the source control. Otherwise, you need it.

TokenMacGuy
Can always do manual source control.
Joshua
@Joshua: Please elaborate. Can't hardly imagine doing anything myself when git is available.
TokenMacGuy
+1 but I'd add "correctly" after "Not using source control" The book Pragmatic Version Control really opened my eyes to some things that I'd been missing out on.
SnOrfus
Manual source control sounds a bit like making your own dogfood: It's easier and less messy to just buy it from the shop.
thomasrutter
Actually, manual source control sounds like making your own dogfood from old car tires, and then wonder why the dog gets sick.
sleske
More importantly, how would 'manual' source control even work? does that mean you just back-up to a zip-file? How do you go about tracking the changes? By the time you make a two line perl script to add timestamps to the tarballs, you've already worked harder than just using git!
TokenMacGuy
I found that this was a particularly common trait among my classmates when I was in school. Adopting source control for class projects would have saved them lots of heartache. There were constantly people who were freaking out right before a project was due because they'd introduced some bug, and didn't know how to get back to a known good state. It's a pity that more CS programs don't teach version control in their intro classes as a basic programming tool.
Scotty Allen
I'm sorry, I don't agree that you skip source control in your example. Now you have a crucial (albeit short) file which you have to remember to include, you must manually type it out, you can't automatically provide to your build script, other devs have to read the docs or work it out... its just a no no. you should be able to build from source control. what are you saving by not including it?
Colin Pickard
@Colin Pickard: If you need to include a file in another file, I strongly doubt that the entire system is still fewer than five tokens. There's a build script? sounds large enough. To be clear, I do not mean that some files of a project of any size may be left out of source control, Only single, stand alone solutions to an entire problem domain that happen to be trivial solutions are even within consideration of skipping source control
TokenMacGuy
+1  A: 

Jumping straight into writing code without thinking about what you're trying to achieve and how you're gonna do it usually leads to inconsistent code that needs to be re-written again and again.

Also, don't get too attached to a particular paradigm. There are many ways to approach a certain task and one of the most important things you can learn is to choose the right tool for the job. Don't be afraid to step outside your box.

jrcalzada
+2  A: 

Believing (without question) what you've been told, or "common wisdom".

What others tell you may be true, but often it is just an attractive idea that started somewhere and keeps traveling, like a virus.

Your brain is yours. Use it. Think for yourself.

Mike Dunlavey
+2  A: 
  • Always document your code
  • Use correct tab spacing
  • Name you variables and classes something of meaning
Jason
+5  A: 

While it's true that thinking about a problem before approaching it is very important, if you're not a seasoned programmer, sometimes you just need to start writing code. You can't foresee everything, and going over concepts in your head only gets you so far.

If you're anything like me, you'll find out that the code evolves and validates in your mind as you write it. Sometimes something that made sense on paper will turn out to be a terrible idea as soon as you write a function implementing it.

If you don't want to risk breaking existing code, start a Test project and try out the ideas and concepts for solutions there. It's sort of like TDD, but for people who like to experiment first, and then plan.

Kronikarz
+1 for test projects. If in doubt, try it out!
Umber Ferrule
+15  A: 

Quick list (in no particular order, but make sure you read about Occam's Razor)

1)stressing out is the worst thing you can possibly do, read up on the neuroscience here: Stress makes programmers dumber and the original series The Programmers' Stone

2)just keep doing and learning iteratively. Don't get too discouraged early on. Make time to look for prepackaged solutions that you can easily understand (try not to reinvent whenever possible).

3)don't blindly copy (cut & paste) "Copy and paste programming is probably one of the worst habits that one can develop while starting to learn programming. Learning how to program is best achieved by writing code and understanding other people's code. If you copy/paste code without understanding what's going on, you are doing yourself more harm than good." (from tvanfossen

4)Always set enough time aside for testing each piece of code that your write or connect to ("unit testing") codetoglory

5)look for common pitfalls in logic (antipatterns from deviant)

6)use appropriate named variables, whether long or short hypoxide

7)great one, don't optimize code before you have to, unless you know for sure the inner most loop call and the code isn't IO/memory limited originally from rob-kam.

8)catch error states. Die gracefully when you need to, pass back an error state otherwise

9)OCCAM's RAZOR

(my personal far out web design top 10 designed them thinking about web content, but all are applicable to coding)

Mark Essel
+3  A: 
  • Functions & methods should only do one thing!

  • Avoid writing functions that are bigger than needed by breaking them into smaller pieces - look for duplicate code and place this in a helper function.

  • Try to break up functions & methods with more than a few dozen lines into smaller functions - this will greatly increase readability and make maintenance and testing easier.

Booji Boy
+1  A: 

If you run into something not working the way you expect, it is possible that it is the framework's fault, but not in your (or my) case, check, double check, and triple check your code, then sleep on it and then check your code again... see it was your code and not the framework :)

Gabe Anzelini
+2  A: 

Be careful about charging ahead in your own direction when five minutes talking to somebody might save you a day of effort. It's usually worth just asking somebody.

David Plumpton
+1  A: 

Using the debugger (and ONLY the debugger) to fix bugs or code. It's really handy and easy to do this sometimes that you end up spending more time with the debugger than thinking about the design or logic.

nevets1219
That's unfortunately true!
+5  A: 

Shotgun programming. That's where bugs are fixed by randomly changing things here and there hoping one of them will solve the problem. Shotgun programming takes many forms:

  • If the compiler says you're missing a parenthesis, throw in a parenthesis. Anywhere. If you're especially observant, you'll read the rest of the error message and throw it in on the line the compiler mentions. Then re-compile right away.
  • Same applies for any other syntax error: quotes, semicolons, braces, etc.
  • If the program compiles but gives incorrect results, change an expression or calculation.
  • If that doesn't work, add some more parentheses or braces. Or take some away.
  • Still not working? Add some more variables. You can never have too many.

But never, never actually analyze your code. That takes too much effort. Just make changes and re-compile!

Barry Brown
A: 

Code first, think later.

Mr. Brownstone
+2  A: 

If you start a new programming task don't jump directly into the code. Great programming starts on paper (or in the UML-editor if you wish).

Think before you code - it will save you a lot of time by not having to throw away solutions that didn't work out.

Benedikt Eger
Also: don't be afraid to throw away a solution that didn't work out.
cdmckay
+1  A: 
  • copy and paste
  • ignoring error handling
  • using PHP
  • meaningless variable/function/method/class names
  • lack of comments/documentation makes it difficult to find out the intent of the program
Why downvoted, it's not a bad answer. Quite meaningless, but so are most answers to this kind of questions? +1 compensation
erikkallen
+1  A: 
Frank V
+21  A: 
try {
    ...
}
catch( Exception ex ) { }
Gabe Moothart
This type of thing is infuriating. Just thinking about it now is making me unbalanced and insane!
Harry Lime
catch(Exception ex) { //dont crash }
Luke Lowrey
The worst is "catch( Exception e) {throw e}" which does nothing but make jr people think you wrote error handling...
sal
try { /*...*/ } catch {} // The lazy dude doesn't need to type "( Exception ex )"
jrcs3
@jrcs3 yeah, but as a bonus if you leave it in you'll get an "unused variable" warning. My current project is littered with these.
Gabe Moothart
+3  A: 

The one thing that has always been painful is failing to spend time designing the program before writing any code. I've regretted it every single time.

Feanor
A: 

No matter what approach you take to writing a program, it will likely take longer than you originally anticipate, especially when you are new to it. Learn to budget your time.

King_Jester
A: 

I agree with many of the above, but I would like to add three more; the first from "Unix Principles" that were compiled back in the early days of computing which are amazingly pertinent to today. That is create each program to

Do one thing and do it well

Look at such things as grep or awk. Many programs today try to be all things to all people and they are difficult to figure out and probably horrible to debug. This does not mean that you have to apply it to the top level application, but apply it in functions, methods etc.

The second thing is

** Do some planning on paper before starting to write code, even if you have a hot idea in your head about how you are going to write it. **

The reason for this is that you will tend to think of modifications to the basic design as you are writing the code. This means that you have to step back and re-design some of the code that you have already written. A little design brainstorming will make the whole process go better.

Pre-factor before you re-factor

The third thing is: **

Don't use a database for just a few records of a simple data structure

**

If you are using a random access record file of say 10 or 100 or even 10,000 records of some simple structure that doesn't need to cross reference another database just "roll your own" random access file or use xml and then access the data through your own code. I have had to install database programs of different types just to handle some insignificant amount of data. Databases are great for businesses that have millions of customers and a lot of tables are involved that have to access one another. But they are bloat for a few thousand or less simple records of say "Name, Address, City, State, Zip code"

A: 

Not getting an agreed requirements/specification document (or similar), signed off before writing any code.

It will kill your enthusiasm for coding rapidly when you discover that you have not hit the objective and have to re-write everything.

Gerard
+1  A: 

Things to avoid to me :

  • Not putting comments in code, this behaviour can become a dead end faster then you can imagine
  • Avoid difficulties by writting an extended code that does the same : BAD! You better learn how to do it right the first time so the next time you'll do it well the first time and you won't have to refactor it.
  • Do bread programming, explication : No indentation in code, everything is at the same level. You MUST put indentation in your code to help the comprehension, and also for other peoples who might get their hands on your code

Things I encourage :

  • Don't be affraid of learning new technics, going further than what you learn at school will difinitely pay off on your grades
  • Have a problem? Google is your friend. You can, with the good keywords, nearly solve every problem you can encountered with google.

This is my first tought on it, I might add some stuff later ;)

Hope this help you ;)

Fox
Good code doesn't need many comments. I agree on writing Javadoc / Doxygen comments for every function. But the code inside a function usually shouldn't need comments.
This is what I was talking about ;)
Fox
A: 

Realizing that as a developer, you're going to have expectations placed on you to solve problems that you have no clue of how to fix. You'll never stop learning new things.

Runner up: Model-View-Controller (MVC).

Also-- get used to having weeks and even months worth of dedicated hard work completely thrown away by your manager b/c she decided to change direction on a project just before its deadline.

Cuga
+1  A: 

Make sure that you get your code reviewed from your peers. It always helps!

amit-agrawal
+6  A: 

Writing code that's hard to read and needs lots of comments is a bad habit to avoid. Instead, you should write code that documents itself and doesn't need comments.

Here's an (artificial) example:

BAD:

if(!node.GetChildren().Size()){ // leaf node
  ProcessNode(node, false); // false means not internal node
}
else{
  ProcessNode(node, true); // internal node
}

BETTER:

bool is_leaf = node.GetChildren().Size() == 0;
if(is_leaf){
  ProcessLeaf(node);
}
else{
  ProcessInternalNode(node);
}
+5  A: 

Not programming deliberatly. Many programmers don't know what they are doing, they don't know why their code is working, and hence they don't understand when it suddenly doesn't work. Read "Pragmatic programmer" by Andy Hunt, it's full of good programming habits. This habit is from that book.

khebbie
+1  A: 

Coding first

This may sound obvious, but coding before thinking through a task/problem beforehand is still more common than you'd think. It may even be behind the lack of useful comments in code - they're harder to add later, except maybe throughversion control.

I've itched this scratch and suffered occasionally from it with logic errors that cost more time debugging since the code give results but solves the wrong problem or in the wrong way.

I'm not saying you should contemplate universal implications or have a formal definition of things, . But, a simple diagram or checklist helps provide a mental model to revisit and confirm. Mind mapping tools can help for many projects, for design as well as collaboration and documentation.

In programming exercises for beginner students, I usually recommend that they transcribe or paraphrase the homework problem text to serve as comments for their code.

This reminds me of recommendations for checklists in operating rooms because they significantly reduce surgical errors and patient mortality.

bubaker
+2  A: 
  • If you are doing something really special then it has 90% chance to be a hack. Don't over complicate simple things.
  • Use a pen and paper! Write down a short description of your original idea, then list the features one by one. Give priorities and schedules. After that you can use a UML program to design the components of your program. Only then code.
  • Read about top-down and buttom up design. Choose what's best for the language you use.
  • Don't relay on the internet as your only source of learning. Get books and read, they often elaborate more on your langauge.
  • Get to know well with the standard library of the language you're using. Don't re-do what's already done for you. It is probably done better anyway.
  • Take breaks between coding sessions, I often find that when I'm stuck doing something else helps a lot.
  • Sleep! Some coders tend to be obsessed to solve a problem when their code isn't working. While you're sleeping your brain still process thoughts and problems, just think about your problem before you fall asleep. I had sereval occasions where I woke up in the morning with the solution for a bug or a new feature that I didn't know how to implement.
  • Read about coupling, design patterns, coding standards.
  • Read blogs of programmers, you learn great things from first hand.
the_drow
A: 

Not writing unit tests for your code is a horrible habit to get into. Learn a unit testing framework for your language of choice and try out Test Driven Development for a couple of weeks you'll never go back. The tests help you design better APIs and actually change and improve your code without fear of breaking things.

Rob Spieldenner
+1  A: 

Also, trying not to blatantly repeat the many good ideas above

Avoid global variables. Write every with reuse in mind. Identify common patterns and implement them as parameterized routines.

Velika
+2  A: 

One terrible habit I still encounter in the companies I work for is the lack of will to extend their knowledge. Most programmers learn a specific technology and stay there. Don't evolve. Others think that the company should pay them to take a course to recycle their knowledge. I don't think that's the way to go. We, personally, must have a conscience that we need to continuous learn.

The bad habit is: don't ever stop learning!

Rodrigo Guerreiro
+1  A: 

Just because you have a shiny new hammer, doesn't make every problem a nail!

This is the one I perhaps the most guilty of. I add a new tool to by arsenal and then I start going looking for reasons to use it. Just because your language added a neat new feature like say, generics or anonymous types, doesn't mean you should use it everywhere! Tried and true methods are tried and true for a reason. Just because something is new, doesn't mean that way is better.

Now, if you will excuse me, I have to go recode all of my WebForm code into MVC!

Serapth
A: 

things that might help you become a better coder (and that they forgotten to teach you in school).

Dont repeat yourself
Command-query separation (CQS)
Defensive programming
S.O.L.I.D.
Code Smell
Smells to Refactorings
Patterns & Anti-Patterns
Software Craftsmanship

zeroin23
A: 

Not planning things enough.

Sometimes even a pencil and paper is one of the best programming tools. Of course, UML and other techniques can be really helpful in big projects. Writting a summary of what you're about to do also helps. Doesn't matter if it's pseudocode, or just a regular descriptions.

Conclusion, you'll develop in a quicker and more efficient way if you REALLY know and understand what you're about to do.

ozke
A: 

Programming behaviour not matching the project-class, and in general lack of project management:

  • Overengineering simple programs. People are often way to anxious to show-off what they have learned software engineering wise, and that they have read GoF. A 1000 line throwaway program is not the place to demonstrate these.
  • Throwing together large apps. The opposite of the previous. Typically very slowly growing due to steadily growing requirements, without ever rediscussing the base assumptions etc of the project. It is always just that one feature more.
  • Doing 2.0 rewrites that totally get out of hand. Always keep the scope of rewrites limited or their time to market will slip horribly. There is no Silver Bullet, also not in rewrites.
  • Mixing in fashionable technogies without direct demand from the customer(s).
Marco van de Voort
A: 

For Large Projects:

Avoid trying to 'push through' a project if you get stuck. Go do something completely unproductive. (joke?) Something else and get your mind off of the task at hand... sooner or later the answer will come to you. Breaks are sometimes the best programmers true friend.

stogdilla
+2  A: 

I don't comment enough.

I know I do it, and I keep trying to fix it, but I keep coding too quickly and forgetting to comment!

joshcomley
I don't necessarily consider this a vice if the code is otherwise good. Comments, to me, are a code smell that suggest the code is doing something in a dumb way (which may be unavoidable) or that it's not as clear as it should be.
David
+6  A: 

I over-engineer....hence this question Ways to prevent over-engineering

James
Of course, the opposite vice is to under-engineer, so that your code is not easily extensible.
Loadmaster
I struggle with this on a regular basis. YAGNI helps, but it can be tricky remembering to tell myself that. This is, I think, an _extremely_ common problem. I'm concerned that most people who succumb to it don't realize that it is a problem.
Greg D
@Greg, I am the same, there is always that little devil on your shoulder whispering...."but you might". It is definetly a problem and its something that isn't going to go away as we have so many options/ways to do things nowadays.
James
+10  A: 

For small functions, I use

  int tempval = ...

and the like. I know I shouldn't, but sometimes I can't think of a descriptive name, and ... oh well.

Steve
+58  A: 

I rewrite code I didn't write.

Tom Ritter
Ah yes good one, I do that. If I didn't write it, for some reason it looks really bad. And when I did write it, it looks really...
joshcomley
but that's not a vice, that's a great habit! It means you are constantly improving things, and to do that you must understand parts of the code that other people wrote... I firmly believe that continuously improving code is the only way to keep code rot away
mookid8000
@mookid - Or you misunderstood that the code was perfectly well written in the first place!
joshcomley
Of course if the original code was horrible (illegible, uncommented, poor algorithm, too much duplication, etc.), that's a *virtue*.
Loadmaster
@joshcomley - and of course the code you write is perfect like that? ;) in my experience, maybe one out of 1000 methods cannot be improved - the rest can and should...
mookid8000
oh, and improving other people's code has a side-effect that I should perhaps emphasize: it makes you read and understand other people's code, thus you take responsibility in maintaining it along with your team... this way, noone owns one particular piece of code, which is great for too many reasons to mention here
mookid8000
@mookid - I agree, anything can be improved! But we have to always ask: *should* it? If it ain't broke, don't fix it! It costs business time and money to *improve* code, and if it already performs its function perfectly well, it might be a waste of time to touch it.
joshcomley
@mookid - also, you're assuming any changes you make will be for the better! It is not unheard of for me that I have rewritten a whole bunch of code thinking "why on Earth did they do this!! It's rubbish!!" only to realise too late "oh s--t, *that's* why they did it... oops...". Now this is my mistake, of course, but I'm merely pointing out that not all "refactors" are for the better!
joshcomley
+21  A: 

I have a tendency to forge ahead with a poorly thought out implementation when a deadline approaches telling myself I'll go back and refactor... which, of course never, happens.

MarkPowell
+22  A: 

Definitely the lack of comments.

Also, I often find myself afraid of using "ugly" solutions, preventing me from getting work done. Of course, in itself, this isn't a bad thing, but somethings you just have to do something to keep on moving with the project.

Mikael S
You hit the nail. I have seen code with over one thousand lines of code and about two comments. Plus, this happens on a ton of code-files in the app! The fun part is that now I have to maintain the code, the original writer has left the company or NIH and the pleasantness of my performance review depends me doing a good job
Phil
I consider a comment equal or greater in value to a statement, so I am rarely guilty of this. Writing a comment first helps me to write the rest of the code in a block.
Loadmaster
+35  A: 

I'm much too easily sidetracked. I want to write a program in Clojure, but first I'm going to create a Web site where the Cheat Sheet and API reference are cross-linked and extensible. But before I do that, I want to write a proxy so I can hear last.fm while I code yet another diversion...

Carl Smotricz
Ah, the dreaded yak shaving. http://sethgodin.typepad.com/seths_blog/2005/03/dont_shave_that.html
Tenner
Is there a term for yak shaving that involves reading about yak shaving? Hmmm, I was going to do something else, but now I need to figure this out. But first I need to check Wikipedia to find out what a yak is. Is it like a cow? Speaking of cows, I can't remember the last time I had a nice steak. Steak...stakes? Stakes...vampires! Which reminds me, what is up with all this Twilight/New Moon hype? And why do werewolves *always* have to get involved? Were they always the mortal enemies of vampires or is that just Hollywood? But seriously guys: Does anyone have a razor I could borrow?
Mike Spross
Also, I have the same problem mentioned in the answer...
Mike Spross
OMG, my diversion made me read this. Got to get back to work...
frunsi
+30  A: 
try {
    myCodeHere();
    doSomethingElse();
} catch (Exception e) {
    // TODO: Handle this intelligently later.
}

If I'm having a good day I might add e.printStackTrace();.

Tenner
cntrl+1 in eclipse does it all for you. How could you resist?
Stefan Kendall
I'm guilty of this.
MadMAxJr
@Stefan: Because I primarily use NetBeans. :-)
Tenner
Yep, the default behavior should be `throw ex`. It's still incomplete TODO code, but at least it's correct code.
Loadmaster
+91  A: 

I start far too many hobby projects, and seldom manage to complete any one -- or even reach an intermediate milestone.

AndreaG
Brilliant - ditto! I figured out the only safe way to achieve completion is to start and complete the whole project in one weekend, otherwise day job gets in the way. Last weekend was my first success with http://fightsite.org :)
joshcomley
This is actually why I *don't* start many side projects - I refuse to start something unless I believe there is a reasonable chance of completing it.
Tom Ritter
I think one of the fundamental problems with hobby projects is we *never give ourselves a professional specification*. Which means there *is* no end to the project. It goes on as far as our hearts allow, which is forever. "Ooh I could add this... it could do this...". Then, before it's even finished "[Technology X] is out of date? I'd better refactor it with newer, better [Technology Y]!". Aside from the obvious facts that we can't feel pressure from ourselves, and no money is involved to hurry us on to an actual completed product...
joshcomley
This is only a vice if you start the hobby project with the intention of finishing it. I start my hobby projects with the intention of exposing myself to new techniques or technology. I don't generally need to finish the project to develop a feel for the thing I'm trying to learn.
Greg D
@Greg - I have a bit of both every time. The thought process is a little bit like this: "Ooh there should be a website/bit of software that does X... I could probably make it... I could give my friends the link, I bet they'd love it! Plus, I've been meaning to learn Technology Y for ages, this gives me a great platform to learn it!"
joshcomley
@josh - I completely agree with your mention of the lack of an end-point on personal projects. Just as I think I've completed something I'll come across some new functionality in another site which I think I should add, then a month later the same happens - it's never ending! I really need to stop looking at pretty shiny things!
Katy
ME! Today, not tomorrow but today I change!
chiggsy
Great answer. I do finish, but what ends up happening is that I have to cut "cool" features left and right and go with the most simple version of what I have in my mind. Once I get it out the door, then I start to add cool crap based on what other people have to say about the software.
rball
+1 I have a similar habit!
James
I completed one of mine! Woohoo! http://sh.am/
joshcomley
+2  A: 

When I tell myself, "Oh, I'm in a hurry so I'll write unit tests when I have some spare time", I never end up actually writing them. Which is why I've been forcing myself to write them first.

Kaleb Brasee
+28  A: 

It's always easy to be wary of anything that's Not Invented Here.

I think Rands summed this up best:

NIH ("Not Invented Here")

Term to describe behavior where an engineering team will not consider working with anyone's code except their own. It's not that the external code is good or bad, it's just foreign which means it must be reviewed, reformatted... oh, what the hell. LET'S REWRITE THE WHOLE DAMNED THING. Billions of dollars have been lost to NIH. I mean it. Billions.

Dave Webb
Very true. Often also referred to as "Reinventing The Wheel". We're all guilty. The risk is - if something goes wrong fixing it is likely to be more costly, so on our (reasonable) assumption that stuff *always* goes wrong that it must be more dangerous!
joshcomley
+37  A: 

Spending too much time on StackOverflow instead of actually developing!

GreenMatt
I´m guilty too!
Seth Illgard
StackOverflow is a social website like any other. We share, we acknowledge, we up vote, we down vote. :)
Secko
+20  A: 

Being anal and formatting other developer's code because it isn't "pretty".

ProKiner
Prettiness can lead to legibility, so this isn't necessarily a vice. Depends whether it was perfectly pretty before, but just not to your taste :)
joshcomley
Get your company to define an eclipse formatting document, and make everyone use it. Cntrl+shift+f. You should never be manually formatting code. Ever.
Stefan Kendall
@StefanKendall Other people think I'm doing some sort of magic when I wave three fingers an make it readable again. Gandalf style.
Secko
@StefanKendall: Agreed. Ctrl+E+F from Resharper keeps my manual reformatting to a minimum. But when I see a line of SQL code in a sproc that is 400 characters wide, all on one line, I can't help myself.
ProKiner
@Stefan, the beauty of Eclipse formatting docs are great, and it's even better when the authors themselves don't use them.
Steven Wright
+8  A: 

Thinking I know what the users want, without checking it often enough.

Jack
+4  A: 

I feel I do not test my code enough, or that during testing, I let certain problems through out of a desire to move on.

Some of these come back to bite me later, which can be rather embarrassing. Iterative development is nice and all, but I wonder if I've found that fine balance between doing things 'good enough' (to meet a deadline), and doing things properly (to ensure you don't get embarrassed later).

fleeb
+6  A: 

One of my vices is more the opposite of the "Re-write everything" vice. At some point, legacy code should be thrown overboard. Perhaps not too soon, but it is possible to spend too much time trying to make something that is fundamentally broken, work again.

AeroDynamik
+5  A: 

I always want to re-engineer everything I find "That can be done smarter" and "I can do better then that" till I end up with three different implementations of the same thing.

Bobby
+4  A: 

It's no wonder that young folk are queueing up to avoid IT courses and the IT industry if we are really as boring as this. Apart from Dirk Eddelbuettel's comment, none of the answers come close to my idea of a programming vice:

  • programming while drunk at the wheel of my Porsche 911;

  • programming while engaged in sexual activities with colleagues;

  • using recreational drugs to achieve the right frame of mind before starting work at about 45 minutes before heading off to the bar for the evening.

Please, colleagues, try a little harder

Sigh

Mark

High Performance Mark
No disclosure here, but seems I won't be up for canonicalization either.
chiggsy
+2  A: 

Being too insistent on having a simple interface to things, no matter how much it complicates the implementation.

dsimcha
+6  A: 

A general lack of consistency with my naming conventions.

I'm usually consistent enough when I'm focused on just one project. But my naming conventions tend to change slightly every year. So this can become annoying when I work on a project over a long period of time.

For example, did I name that database column CreatedDate or date_created? I just need to pick a convention and stick with it.

Steve Wortham
+5  A: 

Not using a source control system like Subversion or Git even for toy or one-shot programs.

Telling yourself "I'll check it in later" is just like your pointy-haired boss telling you not to worry about all the technical debt because "We'll come back and fix it" which is right up there with "The check is in the mail" and "We're from the government and we're here to help".

Kelly French
+6  A: 

I have the attention span of a goldfish if I'm not motivated. I'd rather dream about brewing beer than doing programming I have no interest in. I plan to carry this on until I ditch programming and open a brewery, where upon the day dreaming will probably flip back the other way...

fatboab
+2  A: 

Coding while intoxicated. I always regret it the next morning.

Juliet
Cue obligitatory 'ballmer peak' xkcd reference: http://xkcd.com/323/
Kirschstein
A: 

Using very short abbreviations for variable and method names, a practice I picked up from my early days as a Fortran programmer.

DaveW
+7  A: 

I actually listen to what the user says he wants. I later realise he hadn't a clue.

Galwegian
+1 A mockup tool can be a great help
Andomar
A: 

Designing as I code. Part of this practice involves moving chunks of code off to their own functions as it's all coming together... except, sometimes I never get around to that "housekeeping" step, so I end up with lengthy functions and repeated code. Eventually, in all likelihood, I end up refactoring (cough throwing it all away and rewriting it).

deborah
+4  A: 
  1. Posting subjective questions on SO.com in the hopes of getting more SO rep when I should be working.

  2. Answering othe people's subjective questions on SO.com in a slightly tongue-in-cheek, sarcastic manner, and hoping that other programmers upvote my somewhat dry ramblings, thereby generating more SO rep.

Thomi
+2  A: 

I think I see myself in so many answers here already!

My vice of late: Adding this comment: //TODO: Refactor this later and then never finding the time to return.

Hillarie
+4  A: 

I buy domains and then don't use them, and then renew them :(

Andrew G. Johnson
A: 

When I prototype

if(condition == true)
    return;

instead of

if(condition == true)
{
      return;
}

And of course I forget that I was the one who wrote it and chastise random people during code reviews.

Woot4Moo
+1  A: 

I spend a lot of time tweaking my editor, my shell, my fonts, my colours etc. I do this because when my vim-fu is rocking, then programming is a tedium free romp. I always find time to do this, and I never think it is time wasted.

So really I have 2 vices here:

  1. See above.
  2. I lack remorse about my vices.
chiggsy
+2  A: 

For small projects, jump right into coding without having a clear design in my head; which costs me time later or at some point when things starts getting messy.

A: 

Care too much about what other people think about the subject.

Marco van de Voort
+2  A: 

Writing:

if(variable == true) variable = false;
else variable = true;

Instead of:

variable = !variable;

Or:

if(condition == true) ...

Instead of:

if(condition) ...

Or:

if(condition) {
    // Do nothing
} else {
    // Do something
}
Zehntor