278

I love programming. I've been messing around with code since I was a kid. I never went the professional route, but I have coded several in-house applications for various employers, including a project I got roped into where I built an internal transaction management/reporting system for a bank. I pick stuff up quickly, understand a lot of the concepts, and feel at ease with the entire process of coding.

That all being said, I feel like I never know if my programs are any good. Sure, they work - but is the code clean, tight, well-written stuff, or would another coder look at it and slap me in the head? I see some stuff on Stack Overflow that just blows my mind and makes my attempts at coding seem completely feeble. My employers have been happy with what I've done, but without peer review, I'm in the dark otherwise.

I've looked into peer code review, but a lot of stuff can't be posted because of NDAs or confidentiality issues. A lot of you professionals might have teammates to look at stuff over your shoulder or bounce ideas around with, but what about the independent and solo guys out there like me? How do you learn best practices and make sure your code is up to snuff?

Or does it not matter if it's "the best" as long as it runs as expected and provides a good user experience?

16
  • 29
    You can post snippets on codereview.stackexchange.com for peer review :)
    – Michael K
    Mar 24, 2011 at 22:37
  • 24
    Don't be put off too much by some of the mind blowing stuff you see on SO. I'm a pretty good programmer, and I still get my mind blown - which is why I come here (instead of elsewhere) for help! SO is supposed to blow your mind in a good way, not make you feel inferior! Standing on the shoulders of giants, and all that.
    – Kevin
    Mar 24, 2011 at 22:50
  • 13
    Most of my really good code evaporates when I wake up...
    – PSU
    Mar 25, 2011 at 14:15
  • 5
    Good code is the code that doesn't need comments like the "You are not expected to understand this" :)
    – sakisk
    Mar 25, 2011 at 16:16
  • 9
    @Maxpm - "other developers" can be yourself in a couple of years revisiting your old code. Been there, done that, slapped head, got the scars to prove it. Mar 29, 2011 at 18:18

25 Answers 25

338

The biggest clue for me is:

When you have to go back and add/modify a feature, is it difficult? Do you constantly break existing functionality when making changes?

If the answer to the above is "yes" then you probably have a poor overall design.

It is (for me at least) a bit difficult to judge a design until it is required to respond to change (within reason of course; some code is just bad and you can tell right away, but even that comes with experience.)

11
  • 15
    This. 10 this's. Mar 24, 2011 at 23:54
  • 22
    +1 and also: if you never have to change a piece of code again, it really doesn't matter if it's "good" or not. "Bite that bullet once" as Uncle Bob says.
    – pdr
    Mar 25, 2011 at 2:55
  • 1
    @pdr: Agreed. I try to write the best code that I can at all times, but sometimes you have to deal with weird edge cases and, if that code not likely to change, get it working as best you can and move on.
    – Ed S.
    Mar 25, 2011 at 2:58
  • 3
    I constantly break existing functionality, but that's because I become refactor happy. Yet another skill to hone. But that's why we have distributed version control :-P
    – Jeremy
    Mar 25, 2011 at 13:12
  • 3
    @Jeremy - + 1, re-factoring is a fine tool for honing your skills, but when you get too OCD on it (as I have), it becomes an obsession.
    – orokusaki
    Mar 25, 2011 at 16:19
182

This is certainly a pretty standard measure where I work.

Code Quality = WTFs/minute

Which door represents your code? Which door represents your team or your company? Why are we in that room? Is this just a normal code review or have we found a stream of horrible problems shortly after going live? Are we debugging in a panic, poring over code that we thought worked? Are customers leaving in droves and managers breathing down our necks...

(Robert C Martin, Clean Code - book that opens with above picture)

6
  • 9
    literally? (10 chars)
    – Louis Rhys
    Mar 25, 2011 at 10:15
  • 32
    You'd be surprised (or perhaps horrified) at how accurate this cartoon is in my particular circumstances. Mar 26, 2011 at 9:02
  • "OH GOD I CAN SEE FOREVER."
    – Maxpm
    Mar 27, 2011 at 0:22
  • 2
    I recall stories of measuring how a meeting with Bill Gates wnet on how many F-Bombs he dropped. And there were always quite a few.
    – JeffO
    Jan 25, 2012 at 14:12
  • 1
    @jeffo Here's Joel's story about f-word counting as a metric of Bill Gates' technical satisfaction joelonsoftware.com/items/2006/06/16.html
    – MarkJ
    May 18, 2013 at 13:58
108

You know you are writing good code when:

  • Things are clever, but not too clever
  • Algorithms are optimal, both in speed as well as in readability
  • Classes, variables and functions are well named and make sense without having to think too much
  • You come back to it after a weekend off, and you can jump straight in
  • Things that will be reused are reusable
  • Unit tests are easy to write
8
  • 39
    +1 for "Unit tests..." If it's hard to document, it's probably wrong. If it's hard to test, it's almost certainly wrong. Mar 24, 2011 at 21:29
  • 1
    +1 for the readability, good naming, and clever but not too clever. Very good point. I don't consider it "good code" if it's very smart but completely unreadable by anyone else. Mar 24, 2011 at 21:35
  • 3
    +1 for being able to jump straight in after the weekend off. I'd say that's the biggest change I've seen in my code since college. Mar 24, 2011 at 21:52
  • 46
    I prefer "elegant" to "clever". Clever is complex, elegant is simple. Mar 24, 2011 at 22:07
  • 8
    Never mind a weekend, I love it when I return to something after a year or more and I can't remember writing it but I'm impressed with the job I did back then. Wish it happened more often. Mar 25, 2011 at 10:16
61

Although you said you don't have other coders around to do this, I'll include this for the sake of others.

The code quality test: Have another programmer who has never seen the code read it an explain what each module does to you while you look over their shoulder. The stronger your urge to jump in and explain something the worse the code likely is. If you can calmly sit there with your mouth shut and they don't need to ask a lot of questions, you are probably good.

For your benefit, here are some general guidelines for when you don't have a peer handy. They are not absolutes, just "smells".

Good signs

  • Methods tend to be very short that ideally perform a single task.
  • You have enough information to call methods WITHOUT looking at the body of them.
  • Unit tests are easy to write.

Bad signs

  • Long methods made up of 2-3 sub-tasks that are not broken out into other methods.
  • Methods share data through some means other than their interface.
  • If you change the implementation of one method (but not the interface) you need to change the implementation of other methods.
  • Lots of comments, especially long winded comments.
  • You have code that never runs in your application to provide "future flexibility"
  • Large try/catch blocks
  • You are having a hard time coming up with good method names or they contain the words "OR" and "AND" (e.g. GetInvoiceOrCustomer)
  • Identical or nearly identical blocks of code.

Here is a longer list of code smells that should also be helpful.

18
  • 12
    I've never understood why some believe long, explanatory comments are a bad thing. I comment the heck out of everything I write that is even remotely complicated or confusing. It comes in handy when I come back 3 months (or 3 weeks) later, and wonder what that code means and why I wrote it that way. There's nothing wrong with comments; change your syntax highlighting to make them less noticeable if you prefer not to read them. Mar 25, 2011 at 5:12
  • 4
    "You are having a hard time coming up with good method names or they contain the words "OR" and "AND"" - .NET, IEnumerable<T>.FirstOrDefault. Contains the word "or", yet quite a useful method. I'm not a fan of religious views like many of the bullet points in this response. As general guideline they're good, but in practice every non-trivial application out there probably breaks all of them at one point or another.
    – Ed S.
    Mar 25, 2011 at 5:41
  • 15
    "Long methods made up of 2-3 sub-tasks that are not broken out into other methods". This isn't really necessary if those 2-3 sub-tasks are never used elsewhere in your code. I call this abstraction for abstraction's sake. Similar to (but not as bad as) creating generic abstract super classes where there's no added benefit to defining a class hierarchy (Ie, it will never be polymorphed and doesn't have common elements). Breaking everything down to the finest granularity just adds complexity (and more jumps during debugging). IMHO, unnecessary complexity = code smell. Mar 25, 2011 at 8:31
  • 6
    @Evan - it isn't about abstracting for re-use. It is about abstracting for easy testability and readability. Say you have a block of code that queries a db for an order. It is much easier to read/test if you have a separate method "GetOrder" than inline code in another method.
    – JohnFx
    Mar 25, 2011 at 13:01
  • 5
    @Cody - With good naming conventions and programming practices your code can read almost like english. if (isCustomerPaymentOverdue(Bob)) {sickDogsOn(Bob);{
    – JohnFx
    Mar 26, 2011 at 14:57
29

For me personally, I think it's when I forget about the code. In other words:

  • Bugs rarely occur
  • When they do occur, other people resolve them without asking me anything
  • Even more important, no one ever asks me anything regarding my code
  • People don't have a high rate of WTF/min when reading it
  • A lot of new classes in the system start to use my class (high fan-in, as Steve McConnell would call it)
  • The code is easy to modify and/or refactor when/if needed, without cursing me (even if it's me - cursing myself!)
  • I also love it when I guess just the right amount of abstraction which seems to suit everyone on the team

It's a nice feeling when you open a file you've written a year ago and see all the nice additions to a class, but very few modifications, and - very high fan-in! :)

Of course, these are the things that make me feel like I'm writing good code, but in reality, it's really hard to know. My guess is, if people start making fun of your code more than they're making fun of you, it's time to worry.

20

I have three golden rules:

  1. If I feel compelled to copy/paste blocks of code I'm doing something wrong
  2. If I can't take the whole code in my head I'm doing something wrong
  3. If someone jumps in and gets lost in my code I'm doing something wrong

Those rules has guided me to do some real architectural improvements, ending up with small, clean and maintainable classes/methods.

3
  • 1
    Copy/paste can be used for more than duplication of code that should be kept in one place only. Mar 25, 2011 at 16:29
  • 2
    #1 - YES! #2 - For small projects, yes. For big ones, no. Can Linus keep the whole Linux kernel in his head at one time? We use abstraction and encapsulation so that we can work on one part of a big problem at a time without breaking the whole thing. #3 People get lost in code all the time. I'd add some metrics about whether it does what it needs to do or not - is the user happy? Feb 6, 2013 at 14:43
  • @GlenPeterson: I don't interpret this answer as talking about the entire project, but the entire scope of what you're working on at a given time. If you have to keep jumping back and forth between editor windows, or API references, your code is too complex.
    – Flimzy
    Nov 17, 2013 at 23:30
12

This is an excellent question, and I applaud you for even asking.

First, it's good to get your mind blown every once and a while. Keeps you humble, keeps you realizing that you don't know everything, that there are people out there better at you than this, and gives you something better to strive for.

Now, how do you know when you're writing good code?

  • When your classes each serve a single, very clearly defined purpose, separated from other classes with other clearly defined purposes.
  • When your methods are short - ideally under 50 lines and certainly under 100 - and their names clearly define what they do exactly. A method should not do anything but what it's name implies. If you're going over 100 lines, or tabbed in very far, you can probably pull something out into it's own function.
  • When your code provides one way to do something - when it does not provide the option to zig or zag, but instead provides a single linear path for each possible course of action the user may send it down.
  • When you've done everything you reasonably can to reduce coupling between classes; so that if Class A depends on Class B, and Class B is removed and Class C is put in it's place, little to no changes have to be made to Class A. Class A should be as blind as possible to what's going on in the outside world.
  • When your class, method, and variable names can be read and immediately understood by anyone that comes across the code - there's no need for 'pktSize' when 'packetSize' reads much more easliy.

As others have said, essentially, if you're doing Object-Oriented Programming, and when the time comes to change something you find it like trying to untangle and rewind a ball of yarn, the code isn't following good Object-Oriented principles.

I highly recommend the book "Clean Code", if you're interested in digging a little further into this. It's a good read for novices and experts alike.

2
  • 100 and 50 too much for me .I disagree it.
    – AnyOne
    Jan 26, 2012 at 13:21
  • As in, too 100/50 are too long, or too stringent? Only curious.
    – trycatch
    Jan 31, 2012 at 18:56
7

I'd say my main points would be:

  • Readability (for you and anyone else who has look into your code)
  • Maintainability (easy to modify)
  • Simplicity (not complicating things when there's no need for that)
  • Efficiency (of course your code should execute fast)
  • Clarity (if your code is self-explanatory, there's no need for comments most of the time, name your methods/properties etc. sensibly, break the long code down, never copy & paste a block of code)

I'm not putting Design in this list as I believe a good code can be written without sticking to a design pattern as long as it's consistent within your project.

Good MSDN article on this topic: What Makes Good Code Good?

7

Look around for a good open source project in your favorite language and see what they do.

For example, sendmail is someplace to look to see if you write spaghetti code. It's not sendmail's fault really; it's just 20 years old so it has a lot of cruft in it. So if your code looks like sendmail code, you're probably on the wrong track.

I have not looked at Postfix lately myself, though, and it is probably very well designed. So if your stuff looks more like postfix you're on the right track.

When I started programming as a kid there was no Internet and you had nothing to compare to. But now with a bazillion lines of code available for viewing for comparison, you should start to get an idea if you're doing it right or not.

And just because the Linux kernel is the Linux kernel doesn't mean it's well written. Keep that in mind.

2
  • 2
    In my opinion, this is the most valuable thing you can do. Good coders are made the same way as good writers: they read a lot. Find a good open source project that is known to be well written and dive into it. Code reading can start out boring, but if you just sit down and slowly pick it apart, it is almost certain that you will grow significantly. And this is not limited to just coding ... it may change many other aspects about how you do software development in general. And as stu said, in this age of open source, there is no shortage of good code to explore.
    – Mike Owens
    Mar 25, 2011 at 1:55
  • ah! sendmail is going into its thirties. (it's from 1980/1983) Actually, I thought it scored even older.
    – ZJR
    May 3, 2012 at 0:46
6

This has been my experience since shifting from the college world of programming to the industry over the last five months:

  • Ease of use is so important that we pay people just to design user Interfaces. Coders often suck at UI design.
  • You find that that getting it to work isn't enough
  • Optimizations become more critical in real-world scenarios.
  • There are a thousand ways to approach a problem. However, often times the approach does not account for slightly less well-known factors that could adversely affect the performance of your approach such as database authentication, transactions, file I/O, reflection, just to name a random few.
  • Maintainability is a very important aspect of coding. Just because your code is super optimized and super dense ... doesn't mean that it is sexy. Sometimes it is simply labeled as "Hero coding".
  • Design skills are learned, not inherent. I'm sure there are a few brain children out there, but generally speaking, solid design with respect to real-world problems, is wrought through time, investigation, and most importantly, the imparting of knowledge from your superiors =P
  • Documentation is not an convenience, it is a necessity.
  • The same thing goes for unit testing (this varies from company to company admittedly)

I would suggest that you take an opportunity with an open source project. You will get a chance to see how much you really know if you work along side other programmers bottom line. An open source project is probably the best way to find out based on your background.

2

When you can read it like prose.

1
  • It should read like an obituary and highlight the important features. The style should be in an accepted format that has been thorougly edited.
    – JeffO
    Jan 25, 2012 at 14:24
2

From a code and design perspective, I like what others have already said about maintainability.

In addition, I also look at stability. Look at the production support statistics. If you are getting a high instance of support correspondence for things that seem like fundamental functionality but are finding that many people are unable to understand how to use the software or are finding it does not meet their needs, then there's something wrong.

Of course, there are some users that are truly clueless, but if over time you're still getting reports of breakage, confusion, or significant feature change requests, then this is an indication that one or all of the following apply:

  • The requirements were broken
  • The code is broken
  • The application is not intuitive
  • The developer did not understand the user need
  • Somebody pushed for delivery date over quality
  • Somebody didn't test well or know what to test for
2

Read good code and figure out why it's good. Read bad code and figure out why it's bad. Read mediocre code and figure out which parts are good, which are bad, and which are ok. Read your own code and do the same. Pick up a couple of (well-regarded) textbooks specifically for the purpose of looking at the examples and understanding why they wrote them the way they did. Mostly, read code until you can tell the difference between bad and good, and can do your own "Wtf?" tests.

You can't know whether you're writing good code until you can recognize good code in general. Just because something's over your head doesn't mean it's well-written ...

("Read other people's code" has popped up in a couple of comments on this thread, but I thought it deserved its own post)

2

Ask someone else to take over your job for one day and check how stressed out he or she is at the end of the day ;-)

I'm bad at documenting and cleaning up stuff - so that's how I check it.

2
  • LOL - problem is, my job is a hybrid...there are no other coders here, no one would be able to even make sense of my stuff. I'm the catchall - everything from Excel macros to SQL queries to "Hey, how hard is it to make a contact management system, say, by next Tuesday?" Even our IT staff roster has not one programmer on it...
    – Jim
    Mar 24, 2011 at 21:18
  • I have a variant of this test. Ask another programmer to read your code with you looking over their shoulder. If you can resist the urge to explain it to them, it is probably okay. The more talking you feel compelled to do, the worse it is.
    – JohnFx
    Mar 24, 2011 at 22:01
1

That all being said, I feel like I never know if my programs are any good. Sure, they work - but is the code clean, tight, well-written stuff, or would another coder look at it and slap me in the head?

Have you considered asking another coder what they think of your code?

Some places uses "peer review" where code must be acceptable to another coder before it is accepted to the code repository.

3
  • I have - the problem, as I alluded to in the original post, is that I don't have any other coders here at work to show, and I can't post a lot of this stuff outside the company. However, I love the ideas on here about working on open source stuff to gain exposure to peer review and other people's code.
    – Jim
    Mar 25, 2011 at 14:24
  • I missed the solo programmer notion. In that case you need to Dó what you already dó. Seek out peers and discuss things in general. Being the sole programmer is rarely a good thing.
    – user1249
    Mar 25, 2011 at 15:03
  • Feel free to look at open source stuff, but if you ever work for a company that does software dev, be sure your employer doesn't own your code (or is willing to put it out there) before you contribute.
    – cHao
    Mar 25, 2011 at 21:43
1

IMHO, there's no "good code" per se, but there's "good piece of software".

When we are working on something, there are many constraint on our work, which many times would make us producing the code that falls out of "good code" standard of other fellow programmers.

Some might say "good code" is the code that easy to maintain. The counterargument for this statement for me is, how easy? Do we need to put like 200% effort to the piece of code to make it so easy to maintain for the sake of "good code" standard, even we know we won't need to maintain it that much? I'm sorry but I don't think so.

In fact, I'm the one who really promote "good code" in my team that no one really cares for it. Every time I look at their codes, I never found that they write any perfect code. However, I must accept that they really got the job done, and also be able to maintain it adequately for our company needs. Of course the application is sometimes buggy, but we just made it in time, making our customers and users happy and securing our company in the position far ahead of our competitors.

So, I would say that "good code" is the code that produce what you need. You just have to think of what you really need, then use that to evaluate your code.

1

Good code is subjective to the person. A professional coder that has read lots of books and been to seminars and used different coding techniques would probably tear your code to shreds... However, I have found that code is really indicative of where the coders level of experience is. To me it reads like a history book or an auto-biography. It is what the coder knew at the time or what tools he/she was limited to.

Ask yourself this... Why does Microsoft take 3 versions of software to get something right? Because they are constantly fixing the mistakes they made in the previous versions. I know that my code always gets better and better after a revision. Sure there will be people here that say, I write code perfect the first time. If you believe that then I have some swamp land to sell you...

As you understand the concepts things get easier. For me, the beginning of learning something new is "can I get it to work?", then the next step is "I wonder if I can do it this way...", then usually when I've nailed it I ask "how can I make it faster"...

If you want to be a programmer then you have to dive into it and just do it. It takes a lot of work and to be honest it is like a piece of art that never can be finished. However, if you want to be just a casual hobbyist then if it works then don't worry about it. You have to adapt to your surroundings. If you don't have a way to do code reviews then ignorance is bliss =)

But no matter what... Everyone is going to have their own opinion. Sure there are right ways and wrong ways of doing things... But mostly I have found that there mostly better ways of doing things than just wrong ways...

1

For a particular piece of code:

If it works and is maintainable (pick your good practices), it is good code.

For you as a developer over time:

Good is a relative and dynamic term, to the language domain, problem domain, current trends, and most importantly your experience. The "GOOD" acid test for this continuum might simply be looking back at your previous work and if you say "sigh did I really solve it like that?" then chances are you are still growing and are likely to keep writing good code.

If you look back and see perfect code then either - you are perfect, and there is a risk you are stagnating and you may soon cease to write good code.

0

Release your code, let some people mess with it to make sure that it does what it's always supposed to. Or if you would like, design a spec and make sure it meets all of those specifications. If you pass one or both of these tests, then your code is "good for right now." For most people, your code will never be great, because you'll come back in a year and say "Why did I do that when it would've worked so much better this way?"

With more experience, you get better code. But if you continually practice the same habits, you'll continually fall into the same pitfalls. It's just a simple take on an old adage of "Practice makes permanent." If you continually do things the right way (like testing your code to always make sure it works for what it's supposed to do), then you'll get better. If you continually do things the wrong way (like never testing your code for certain situations, or failing to recognize where bugs could occur), you'll just get stubborn with your code.

2
  • 1
    The best place to learn though is by looking at code from other more experience people. I had been programming in a silo for 10 years or so before I started my professional career and started to see code written by other people. My level of experience and good code increased dramatically as I saw how other people did things better than I had up until then.
    – stu
    Mar 24, 2011 at 21:22
  • 1
    I hope I'm on the right track then...I'm a stickler for always striving for best practices. I always try and learn the best way of doing something, and when there is an argument in the community (say, on how you should/shouldn't use singletons in iOS programming) I try and learn each side's argument and make up my own mind. I try and keep good design practices in mind, keep reading and learning, etc... Thanks for the answer!
    – Jim
    Mar 24, 2011 at 21:24
0

Nothing beats having someone experienced look at your code, but there are some resources to help you evaluate and improve your code on your own. Take a look at Martin Fowler's Refactoring (or website). Sutter and Alexandrescu's C++ Coding Standards is good if you're writing in C++. A lot of the recommendations in there are language agnostic, but others may be able to recommend similar books for other languages. Test driven development can be very useful to solo developers, as it provides a sort of quality check as you go, and you know when tests become difficult to write that it means your code could probably use restructuring.

Some other signs are more process-oriented. They usually lead to better code, but not directly. These include things like use of source control, an automated build process, not developing directly on the live server, use of bug tracking software, etc.

0

You can use code analysis tool such as FindBugs, PMD. That will provide some information about your code's quality.

0

In effort to code well, I aim to ensure that the program is highly functional and speedy about it. Make sure everything is in a place it should be so that the file, data, function and abstractions are fairly obvious.

After this point I put it to a test: Find a person fairly unversed in computers in general, try to explain some of the main code pattern. If they can sorta-kinda read it, wow. Good job.

Mostly just KISS and try to be innovative without crashing anything. I would also make more notes about coming back to the code and having a nice time improving and maintaining it, but that has been covered pretty well.

0

Never.

"Good code" is only code for which no way of improvement has been found yet. As Jeff Atwood said:

There are a handful of programmers in the world capable of producing brilliant, perfect code. All the rest of us can do is keep making our software less shitty over time-- a process of continuous improvement

And by the way, you don't have to reach the perfection, because sometimes, "Sufficent Design means poor design".

1
  • What if someone else has found a way to improve it?
    – JeffO
    Jan 25, 2012 at 15:01
-1

I use 5 points to know if code is good or not:

  • procedure, method, and class names are both usefully short and yet tell me what they do.
  • commenting out any include causes failure to run
  • looking at the code after a month away, I can follow the flow
  • code compiles and runs cleanly.
  • program performs the intended actions and only the intended actions.

For me, GetCustIDFromDB(var* DB, char* customer) is better than getcid(var* DB, char* c) because it tells me what I'm looking at. But *DBLookupCIDByName(var* DB, char* customer) works, too.

I often test to see if I actually still use all my #includes... If I can remove it, great. Sometimes, it's possible to examine your included headers, and see if the needed functions are actually in something that header includes via #include instead... but I've only done that rarely, and it saves a little bit of space, too, tho' it may make the process of adding new features much harder.

-1

It is a hard thing to say. There's always a question of taking longer to do it right, or taking less time and getting it done sooner so you can work on other things.

http://xkcd.com/844/

I've gone back and looked at code I did a few years ago, and I think it looks awful. We are constantly learning in this field, and the best way to code right is to look at other people's examples and learn from them. Once you learn something new, share it with others so that we all can benefit from it.

1
  • 2
    Loop: "Code Fast. Does it work yet? No." or at the "Code well. Are you done yet? No."
    – Pindatjuh
    Jul 30, 2012 at 23:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.