tags:

views:

1891

answers:

46

What do you do to write better code? Concentrate more? Read more books?

My method is reading, asking. What is your method of writing better code?

+11  A: 

Write more code. :) and hopefully you ll write better code.

Thomas Cormen (One of the Author of CLRS), says that if you want be be a good programmer you program for 2 years, if you want to be a very good programmer, you program for 10 years or you take an algorithm class:)

sounds good, practice is everything ;-)
streetparade
Definetely, reading books are cool, i love to read books but if you dont code, you forget what you read.
Mine is the opposite. Write LESS code.
Larry Lustig
@Larry Lustig: what about "write lots of little code"
Javier
Write lots of code and then get rid of as much of it as you can, even.
Mike Burton
i should be a great programmer, by that definition :P
CuriousTiger
Write code more often, writing less each time.
eyelidlessness
+2  A: 

Code Katas are a good exercise in improving how you code. You can read more about it and get some problems here

stimms
+61  A: 

Code reviews. I've learn far more by people thrashing my code rather than praising it

DroidIn.net
Sadly it is a PITA to get people to tell you when you go wrong, much less actually go over the code. My coworkers wouldn't do reviews if their lives depended upon it (and I have tried numerous times).
envalid
Code reviews go both ways, you can learn a lot from seeing how others solve problems.
Ben S
Problem with code reviews - they depend too heavily on people around you being good reviewers and have time.
abyx
Indeed. I always have a million billion tabs open in Visual Studio, while my fellow programmer just plugged in code, didn't care if it worked or not, when he was done he would move on to the next file. It seemed much more effective.
knight666
Ben - very true
DroidIn.net
How to get my code reviewed if I work alone? Can try to review somebody's code in exchange :)
valya
If you program in Java you can use JCR http://is.gd/53JTc not the "real thing" but pretty good
DroidIn.net
@envalid: 'My coworkers wouldn't do reviews if their lives depended upon it (and I have tried numerous times).' So if they didn't do the code reviews you asked for, you killed them? All of them? Where do you store the bodies?
graham.reeds
I like this answer in theory. In practice, it can be very difficult to get constructive criticism from people unless it's formalized (which code reviews really should be).
jprete
I'm a walking proof :) I agree on "formalize" part otherwise it's not a review but bashing
DroidIn.net
+25  A: 

Try to always be the worst developer in the team, and look how the others work.

That is, try to be the *best* developer you can, but also to work on teams where there are stronger developers you can learn from. ;-)
Jim Ferrans
Yeah, just being the worst is easy!
abyx
What a great tip. Truly perspective changing.
Alex
+6  A: 

Over the years of school, I have written better code by reading books, reading up on coding standards, learning how to make my code more efficient and cleaner with peer reviews. I have had alot of experience with people giving me feedback on how I can reuse my code, and that was the best thing for me.

Anthony Forloney
+3  A: 

Lots of iterations.

zoul
+12  A: 

Read code from others, always questioning why did they write that way.

Try to find the simplest way to do things, remove everything that does not solve your specific problem.

Write tests, they provide a safety net when rewriting code.

mouviciel
+4  A: 

Work with people who are better than you, and have them review your code. If you're the best coder on your team you'll probably have a much harder time getting better than if you have mentors to learn from.

tloach
+2  A: 

Writing more code is definitely important. Code review by some peer is also very helpful. Knowing how the language works helps in understanding how the language actually works can help in creating more efficient/better code.

Ansh
+5  A: 
  1. Read the Standard libraries. STL, Java.util Packages
  2. Practise programming. Join a group or appear at programming contests.
  3. Read more about best practises, design patterns.
  4. Learn more than one language.
  5. Read code from senior programmers.
Geek
+1  A: 

Once you accept that "compiles and somehow works" is not good enough, you will automatically strive to improve you skills. It also helps to read blogs like "The daily WTF" because you surely don't want to be featured there.

Now that you have the motivation to write good code, read good books, read good code, read good blogs and websites. While coding, ask yourself: Will I understand that, 2 years from now? Will someone else?

ammoQ
+2  A: 

Looking at open source code gives you insights into bad and good code. Using a few open source libs and not having the fear of looking at what's going on.

It will help you, and it will frighten you. :)

Marcus Lindblom
+2  A: 

Learning lots of different programming languages and environments. The world looks different from Python's, Java's, or C's perspective, and all the different views complement each other. Mastering just one language gets you only so far.

Joonas Pulakka
+3  A: 

I always assume there is a better way to write the code I have written. If I ever discover a better way to write the code, I refactor it (if possible) or make a note for the next time I have a similar task (if refactoring is not possible right now).

So, be honest and humble in order to admit that your code is not perfect, and spend time actively searching for better solutions.

Jason Berkan
+7  A: 

I try to do something impossible at least once a year.

Nosredna
and whats that?
streetparade
@streetparade: A humility exercise.
Nosredna
I also find exercises in humility impossible.
Carl
Once a month for me ;)
RCIX
+1  A: 

Practice ofcourse. Do use readable names for variables/objects and classes for better results

Raghav Bali
+1  A: 

Work alongside stronger developers; do code reviews and pair programming; read top quality books, blogs, and articles; study "beautiful" code; and of course practice, practice, practice!

Jim Ferrans
+12  A: 

Write tests before writing code. That way the code only does what it's required to do, no more and no less.

Kaleb Brasee
+2  A: 

All of this answers. From reading books and blogs to learning about new approaches. But practice is the most important. A lot of it. So i recommend some of the online competitions that will teach you through concrete examples:

www.topcoder.com

www.codechef.com

Siblja
A: 

Add Error Handling.

When you're banging your head against the wall, one of the best things you can do, is go back to the last version that compiled only 4 minutes ago, and add some error handling. Compile it, make sure it runs, then drop in the stuff you were adding, and see where the error is. I find this to be better than using the debug routines, with the added bonus of having my program now handling errors correctly.

Plus I always learn by doing. So when I screw up, and catch it with some nice error handling, I learn not to be that stupid. (One reason why I've become adamant about my tabs/hierarchy/brackets. For me, having beautifully indented code is a necessity to ensure I don't waste 2 hours playing "find the missing bracket".)

UEC
+7  A: 

The main rule is: Always learn a new paradigm.

  • If you are programming on an OO environment, try to learn a functional language

  • If you use Relational Databases, try to lean a document based database

  • If you always learn through your own code, try some code reviews

  • If you only make code for your job, try a code kata or code Dojo.

Thinking on a different way is challenging and contribute a lot to a learning experience

Diego Dias
+1  A: 
  1. I read a lot. Both blogs and books.
  2. Write tests. Preferably TDD.
  3. I've got constant reminders that my work requires careful thinking (I've got the Pragmatic Programmer tips hung next to my monitor, and a Clean Code wristband).
  4. Always ask team-mates for their opinion when I think I'm doing things in a way that's too messy.
  5. I sometimes read through code I've produced lately and 'rate' myself. I find things that bother me and make sure to fix them.
  6. Read code.
abyx
+15  A: 

If you're open to non-standard answers, consider the following: I find a mastery of beautiful, expressive English goes hand in hand with beautiful, expressive code.

With that being said, resist the urge to downvote and just humor me here -- speaking and writing skills are concerned with a person's ability to compose their thoughts fluidly, present them to others, and think with some degree of creativity. Incidentally, these are the same skills you want to see in programmers.

Its worth noting that the human brain develops computational models and prosodic language functions in the same regions of the brain (wikipedia article has some information on this topic), and Jeff Atwood seems to connect language and programming skills in a similar way.

Take the time read more books -- not just programming books -- or maybe even write a novel (I know National Novel Writing Month is coming to an end, but you can make any month your nanowrimo).

Juliet
I'd take this two steps further: first to de-emphasize the English language specifically, and second to emphasize the benefit of learning second (and third and nth) human languages, as the ability to mentally translate between language models can heighten the value of a command of any given human language per se.
eyelidlessness
Juliet, I can't agree with you more. Clear writing and clear programming are unfortunately far too rare.
Dr. Tim
"Besides a mathematical inclination, an exceptionally good mastery of one's native tongue is the most vital asset of a competent programmer." - Dijkstra
JC Denton
+1  A: 
  • Code in pairs
  • Write unit tests
  • Refactor relentlessly
  • Do the simplest thing that could possibly work
  • Don't speculate about future requirements
  • Use the language that is closest to the problem
Doug Knesek
Coding in pairs and unit tests are great for corporations that want to maintain a certain level of code quality and that are risk averse, but I disagree they are practices particularly conducive to individual skill development (or indeed rapid development, which - I find at least - goes hand in hand with learning).
Iain Collins
Don't speculate about future requirements is a terrible suggestion. Requirements always change, so you better anticipate what's coming.
erikkallen
@Erik - Speculation about future requirements almost always proves to be wrong. As *you* said, requirements always change. You can rarely anticipate what's coming. Trying to do so and baking this speculation into your code invariable complicates your system to the degree that it costs more to make routine changes than you saved with your speculation should it turn out to be correct.
Doug Knesek
@Iain - Coding in pairs forces you to collaborate resulting in much faster leaning. Check with your local university regarding the learning value of collaboration. Also, writing unit tests force you to create code that is testable, i.e. code that is loosely coupled and cohesive with a clean public interface. You should try it sometime.
Doug Knesek
+11  A: 

Help others on Stack Overflow.

Mongus Pong
Or newsgroups or other quality online forums.
Tony Toews
A: 

My ways

  1. reading
  2. Asking
  3. Participate in online technical communities
  4. doing open source projects
anishmarokey
A: 

Have a clear and concise definition of "better." Do you mean quicker to write, easier to maintain, better performance, fewer bugs, or more reusable? Are you looking to write better code or write code better? Remember the adage "price, performance, quality - pick any two?" Your definition of "better" will be affected by what you choose.

Whatever you decide, you'll get better by:

  • comparing your code and your approach to coding to those you want to emulate
  • reading books to develop your philosophy of coding
  • studying sample code to develop the craftsmanship of coding
  • posting to forums like this one for getting objective feedback
  • talking to those who use, support, and sell your code

But you have the most important part already - you WANT to get better.

ebpower
+2  A: 

Maintain somebody else's code. I have learned allot from the pain I experienced trying update legacy applications.

Clark
Seriously, I know I've learned a lot from upgrading atrocious QuickBASIC code that was C/Ped into a production VB6 app.
Heather
+2  A: 

Glass of good wine or whisky does miracles sometimes :)

pablox
yep sometimes it does realy
streetparade
http://xkcd.com/323/
starblue
+3  A: 

There may be several types "better" to strive for:

Better from a performance point of view - study algorithms, learn how to analyze and classify problems from a computability point of view. Study optimization techniques; study and understand the language, machine and operating system architecture - knowing how these work together (or at odds with one another) can have a huge impact on how you develop "better" programs.

Better from a maintenance point of view - Make sure your code fits the design and architecture principles that the system you are working on is based upon. Do peer reviews - if other people on your team find the code difficult to understand or follow, then it may not be all that maintainable - even if it is technically correct and fulfills the intended business function.

Better from a best practices/standards point of view - Study the standards and best practices that your organization has developed then write your code taking the spirit and intent of these guidelines into consideration.

Better from a readability point of view - Structure and write your code to reflect the abstractions you have employed in designing the program. Keep data structures; methods and classes clean, well named and documented. Try to have each method written at a consistent level of abstraction. Make the logic flow as if you were reading a guide book - try to keep the reader informed as to what you are doing at each step, how that step contributes to the final solution and maybe why another alternative was not considered. Provide pre-conditions, post-conditions and invariants to help the reader understand what they are coming in with and what they should leave with. Do not assume that the "code says it all".

The above are just a few of the possible dimensions of "better" when applied to code and programming in general.

Always reflect on code you have written - there is always room for improvement. Read code other programmers that you respect have written; encourage them to read and comment on yours. Do this in a way that encourages discussion and debate.

Keep an open mind. Understand that criticism may be a positive thing in that it may enlighten your understanding of a problem that was poorly solved, or a practice that could be improved upon.

Finally, and most important: Read. Study. Learn. Reflect. Repeat.

NealB
+1  A: 

my solution: type faster

George
+2  A: 

Write code that is easier to read than it is convenient to write.

Justin Swartsel
+1  A: 

I certainly agree with most of the above (except alcohol and "type faster"), but most of all, in terms of what most developers forget, I'm with Juliet. Remember that someone else is likely to have to read your code someday, and that "someone else" might turn out to be your future self who will have little memory of writing it. We all remember that our code needs to make a computer do something, but that is just the "zero level" of useful code. In my experience, most developers forget that it also needs to be a good piece of expository writing.

As much as code needs architecture and structure, it needs well-chosen variable and constant names, with a consistent naming pattern. Code needs summary comments expressing intent, which allow skimming when looking for a particular portion of the code. In short, code needs to be written, not just churned out.

I also want to add: I don't think I ever worked in a place where there was too much code review. Code review makes everyone's code better: the code being reviewed, and the reviewer's future code.

Joe Mabel
A: 

1st step: I read Code Complete (long back). Now sometimes scan it. That refreshes my coding style.

2nd ask my collegues to review my code.

3rd Study/try to read open source

4th StackOverflow.

so on.

Saar
+2  A: 

"Write as if whoever’s going to have to maintain your code is an axe-wielding psychopath who knows where you live."

Doesn't necessarily suggest a particular approach to improving one's code, but I find it motivating.

Dan Blanchard
I tried that, and found i couldn't write any code...
RCIX
A: 

Just read Code Complete by Steve McConnell. I believe it's the most comprehensive 'bible' of coding practice. All reasoning is backed by scientific research results, it's not one man's opinion. There's also Programming Pearls by Jon Louis Bentley which is more practical, and Knuth's books that are more academic. If your problem is more 'how to solve it' then read How to solve it by Polya. More coding is bad advice. There are people who have written a gazillion bad lines of code.

Michiel van der Blonk
+1  A: 

Every mistake is a learning opportunity

When you make a mistake, always think what you could change to avoid that mistake in the future.

starblue
A: 

The best way to write the best code:

  1. Write the code to get the job done.
  2. Look at the code and start sorting classes and the defined variables, editing them for readability.

Instead of this:

String myString;
String mySecond String;
private Bool myBool = true;
public String thirdString = "";

make this:

private String myString;
private String mySecond String;
public  String thirdString = "";
private Bool myBool = true;

(note it is sorten on variable type and added private/public/protected etc.

  1. Remove unnecessary white space. (the one that doesn't have any function at all)
  2. Start modifying the code (even though it's already working) and shorten functions, unloading unnecessary resources, rewriting functions so they work more efficiently.
  3. Add commentary that doesn't explain what the code does but why.

You don't have to write good code right away from start, it is all about polishing afterwards.

Pieter888
Editing for readability takes some time. Do you think there is any advantage doing it manually over pressing a shortcut and having Resharper clean your whole solution automatically? The thought of manually formatting my code now makes me cringe.
Alex
well, whether you remove all white-space or instead just keep it for readability is all about what language you are using. If you're using C#, VB or any other language that needs to be compiled before use, white-space doesn't effect performance since it will all end up the same in .net after it's compiled.If you're using php however, when the text is being pre-processed the reader needs to skip over the white-space which won't take much longer than other code but still it makes a difference. choose wisely :)
Pieter888
+1  A: 

I believe good code is code that are used.

So, my suggestion is to write software other people use, either as end users or other developers if you are designing a framework. I think doing full working program with all details are good to understand all parts of a program. Listen to your users and try to solve their problems

This will put you in front of the problems that are associated with useful programs. Non-linear, cut&paste, printing, etc

Because, if you have a great program, what can you say from the outside just at looking at the program running.

epatel
Great point. If you never get bug reports about your software, it probably means no one is using it.
Alex
A: 

Print code on paper, and review it with a pencil in hand. It gives a different view compared to what you see on the screen, so more defects can be identified.

Andy
A: 

Three essential tools that minimise the effort needed to keep the code working:

  • source control e.g. git or subversion
  • test-driven development so I don't have to spend ages on manual debugging
  • build automation - rake or ant - so the product is consistently built
cartoonfox
+1  A: 

I write bad code, because this is the only way to have a chance to write a better code :-)

Martin Kopta
+2  A: 

Learn a functional language.

Functional programming will give you great abs, a pearly white smile and make you more attractive to the opposite sex.

But seriously, its made my everyday OOP code much better. Particularly given the integration of lambda expressions into .NET.

I guess the moral of the story is to learn as many different programming paradigms as you can.

Alex
+2  A: 

Turn up the compiler warnings.

Justin
+2  A: 

As has already been said: Just writing more code won't help.

Spend more time writing code.

My personal guestimate is that it takes around 25000 hours to become good at coding; And about 50000 hours to become excellent. (The lucky ones among us managed to get through the first 20k during school ;) )

But as with everything the only way to really master a subject is to teach it.

Even if you consider yourself a "coding god" you will be amazed about what you can learn teaching programming to absolute newbies.

Teaching forces you to really understand (and question) what you do - in detail, instead of just "feeling" what is right or "knowing" it has always been done this way.

Andreas
+1  A: 

Do some more coding... and do some pet projects.

test test