Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

How would one know if the code he has created is easily maintainable and readable? Of course in your point of view (the one who actually wrote the code) your code is readable and maintainable, but we should be true to ourselves here.

How would we know if we've written pretty messy and unmaintainable code? Are there any constructs or guidelines to know if we have developed a messy piece of software?

share|improve this question

We're looking for long answers that provide some explanation and context. Don't just give a one-line answer; explain why your answer is right, ideally with citations. Answers that don't include explanations may be removed.

73  
Obligatory link (for once not to xkcd): osnews.com/images/comics/wtfm.jpg –  Jerry Coffin Mar 22 '12 at 17:17
4  
1  
I’d just flippantly say that you know it when you see it but this argument was fundamentally flawed and embarassing even in its original form, never mind applied to source code. –  Konrad Rudolph Mar 23 '12 at 11:15
2  
"Of course in your point of view your code is readable" - not that obvious! –  UncleZeiv Mar 23 '12 at 12:42
3  
I'd say you know it when you see it a few months after you wrote it. –  JeffO Apr 18 '12 at 12:57

20 Answers 20

up vote 163 down vote accepted

Your peer tells you after reviewing the code.

Rationale:

You cannot determine this yourself because you know more as the author than the code says by itself. A computer cannot tell you, for the same reasons that it cannot tell if a painting is art or not. Hence, you need another human - capable of maintaining the software - to look at what you have written and give his or her opinion. The formal name of said process is "Peer Review".

share|improve this answer
2  
Nothing beats empirical testing. –  World Engineer Mar 22 '12 at 17:39
11  
+1 Your most important audience is your peers who are immersed, with you, in knowing the whys and hows of the problem you are working on and its solutions. Good code reflects your peer group's current understanding of this. Assuming the team is capable, thoughtful, and open to new ideas, "your peer telling you its good/maintanable" is, in my experience, a better definition by far then any other. –  Doug T. Mar 23 '12 at 0:55
14  
In my experience, this only works when your colleague know what is good and what is bad. Otherwise it will sounds like this : "You should write those code in the same method, that's easier to find code" –  Rangi Lin Mar 23 '12 at 5:30
3  
@RangiLin, well, your colleague may be right. –  user1249 Mar 23 '12 at 14:25
3  
@Rangi You have to work with the colleagues you have. if they find your code difficult that is a problem with your code. In the longer term, you can educate them, or try to get better colleagues (you can move or you can influence the hiring process)... Oh yes, and do always remembers that they may be right. –  MarkJ Mar 27 '12 at 22:57

Sometimes, the best way to know, is to come back to code you wrote six months ago and try and understand what it was written to do.

If you understand it quickly - it's readable.

share|improve this answer
4  
Yeah, that sounds good (and is true), but it's not a very good approach for deciding what/how to do today... –  Michael Durrant Mar 22 '12 at 18:05
8  
Dissection suggests it's taking a while and you have to do it carefully... –  deworde Mar 23 '12 at 9:06
1  
I might drop the timeframe for revisiting down to a month, or even less, for a first revisit. I think it depends on the complexity of the project and domain, as well as your mental approach. I find that in six months, I get distracted by seeing refactoring or optimization opportunities using tools or techniques I've learned since i first wrote the code, instead of real readability. –  Chris Bye Mar 23 '12 at 15:14

It is:

  1. maintainable if you can maintain it.
  2. easily maintainable if someone else can maintain it without asking you for help
  3. readable if someone else, on reading it, correctly understands the design, layout and intent

The real test for 1. is (as Alex in Paris and quant_dev say) that you can pick it back up after a few months doing something else.

The test for 2. and 3. is that someone else can pick it up, and figure out how to extend or fix your code while following the grain of your design. If they can't understand the design, how it relates to the problem space, or how your code is intended to be used, they'll hack a solution across the grain instead.

There are rules of thumb, principles (ie, rules of thumb someone wrote up nicely and gave a name) and all sorts of suggestions that may lead you in the right direction, or away from common pitfalls. None of them will guarantee the qualities you're asking for, though.

share|improve this answer

If your code follows the principles of SOLID and DRY and has a good set of unit tests around it, it is probably maintainable.

Is it readable? Read it. Do method and variable names make sense? Can you follow program logic without a problem? If the answer is yes, then the code is readable.

share|improve this answer
5  
...and after you read it, hand it to someone else to try to read. –  jcmeloni Mar 22 '12 at 17:01
5  
This is not a particularly good test. Many applications of those rules are subjective, and you can almost always read your own code right after it's been written. –  DeadMG Mar 22 '12 at 17:39

If you can understand it after 6 months, it's not bad.

share|improve this answer

The proof is in the pudding. Watch what happens after handing it off to a reasonably competent person. If they don't need to ask many questions relative to the difficulty of the code, you've done a good job.

This was an early lesson in my career. A mentor said, "Document everything, so that you can escape the program later on. If you don't anticipate questions when the answers are fresh in your mind, you'll have to figure them out when they're not."

share|improve this answer
2  
Beware that people may refrain from asking questions due to fear of exposing their ignorance. You may even be perceiving those people as 'reasonably competent' in the first place due to their tendency to refrain from exposing it. So lack of questions may not be a good thing unless you know you both are being sincere. –  Hermann Ingjaldsson Nov 10 '12 at 12:03

Despite how it seems, there are some fairly objective measures you can consider. Books like C++ Coding Standards, Refactoring, and Clean Code have long lists of criteria to judge your code by, looking at things like meaningful names, function sizes, principles like coupling and cohesion, object design, unit testing, successive refinement, etc.

The list is too large to be amenable to a checklist, but you read the book and pick out a few key things to work on, then after several months read it again to improve further.

share|improve this answer

Reading How To Write Unmaintainable Code - Ensure a job for life by Roedy Green, laughing, and learning.

...how to write code that is so difficult to maintain, that the people who come after you will take years to make even the simplest changes. Further, if you follow all these rules religiously, you will even guarantee yourself a lifetime of employment, since no one but you has a hope in hell of maintaining the code...

The essay gives you numerous examples of how to write bad code, using plenty of funny examples. It continues to explain how to utilize Creative Miss-spelling, Reuse of Names, the highly appreciated technique of Reuse of Global Names as Private.

In a humorous way the essay teaches you how to avoid all of the examples of unreadable and unmaintainable code.

Actually, I found it hard to believe that anyone would write code with similarities to the examples in the text. That was when I was fresh from school. But, after working for a few years I see code from the text every day…

share|improve this answer

I read through all the answers, and I noticed nobody mentioned code complexity.

There's a tight correlation between code complexity and readability/maintainability. There are numerous code complexity scoring algorithms, but I'll just talk about how McCabe complexity scoring works.

Basically, McCabe scoring reads through your code and computes the number of unique "paths" there are through it. If you use McCabe as your numerator and lines of code as your denominator, you get a pretty good approximation of "readability" as well.

If you've got 10 lines of code, and there are 300 paths through that code, that is some pretty unmaintainable code (difficult to change safely and easily), and it's probably not very readable. Conversely, if you've got 300 lines of code, but there is only 1 path through it (it has no conditions), it's both readable and easily maintainable.

Where McCabe falls down however is in that latter example. If I've got 300 lines of code with no conditions, there's a really good chance I've done "copy/paste reuse", and obviously that's not a good thing either. So there are system-wide metrics that you apply in addition to McCabe -- like duplicate or near-duplicate code detection.

share|improve this answer
1  
This should be the answer. Measure. Other answers are more opinion than fact, if I can understand it, it must good? First measure using complexity analysis, then human refactor to look for duplication, etc. –  Jon Raynor Jun 20 at 14:36

One point I'd share is if the code is built in "modules," and when I say that I mean that you can change one thing in a module and easily have it working with the whole. It eliminates effects between unrelated things. Also:

  • Code is easy to reuse
  • Your code is flexible (this ties in with building in modules)
  • DRY - Don't Repeat Yourself

I highly recommend reading, The Pragmatic Programmer.

share|improve this answer

I would say one way to know would be if new team members can pick up the code, understand it, and modify it to fix defects / meet new requirements with relative ease.

share|improve this answer

How would one know if the code he created is easily maintainable and readable?

You can spot easy to maintain and readable code by looking for these properties:

  1. Objects, methods and/or functions always do one thing.
  2. Methods and/or functions are concise (as in "brief but comprehensive").
  3. Objects, methods and/or functions do essentially what you think they are supposed to do based on their names.
  4. Code that is destined for re-use is actually re-usable.
  5. Last but not least, if you can immediately unit-test the code, you have likely written single-responsibility, modular code at the very least.

How would we know if we've written pretty messy and unmaintanable code? Are there any constructs or guidelines to know if we developed messy software?

  1. If you are reading through a method and it isn't apparent what the intent was, this is inelegant at best and likely unmaintainable at worst.
  2. If it doesn't seem simple, it probably isn't simple and that is a sign of unmaintainable code or code that will soon become unmaintainable.
  3. If there is a lack of symmetry (consistency) across the codebase, you are likely looking at unmaintainable code.

Below is an example of code that obfuscates intent (comments removed from both):

ksort($params);
$first = true;
$oauthParams = '';
foreach ($params as $key => $value) {
  // only include standard oauth params
  if (strpos($key, 'oauth_') === 0) {
    if (!$first) {
      $oauthParams .= ',';
    }
    $oauthParams .= $key . '="' . urlencode($value) . '"';
    $first = false;
  }
}

The following is one example of how one might refactor the above:

public function buildXoauthParameters($params)
{
  ksort($params);

  $oauthKeys   = array_filter(array_keys($params), function($key){
    return preg_match('/^oauth_/i', $key);
  });

  $oauthParams = array_map(function($key) use($params){
    return sprintf('%s="%s"', $key, urlencode($params[$key]));
  }, $oauthKeys);

  return join(',', $oauthParams);
}
share|improve this answer

Readable and maintainable code: Code that, upon first-sight, a programmer can understand well enough to be able to easily:

  • re-use it via its interface, or
  • debug it, or
  • change its behaviour. (add/remove a feature), or
  • optimise it
  • test it

This boils down to 'clarity'. i.e How many questions does the programmer have to ask of a particular segment of code before they are sure that they 'understand what it does well enough' to achieve the current task in hand without causing unexpected side-effects.

The book 'Code Complete, by Steve McConnell' goes into this in great detail.

He goes through various metrics that you can use determine if code is of good quality.

See an example here: http://books.google.co.uk/books?id=3JfE7TGUwvgC&lpg=PT376&pg=PT389#v=onepage&q&f=false

share|improve this answer

Here is a technique I like to use:

Show the code to one of your peer programmers and have them explain to you what it does. Watch for these things.

1) If they can't easily explain the purpose of a block of code refactor it.
2) If they have to jump to another section of code to understand the current section, refactor it.
4) Anytime you feel an urge to speak during the process, that section of code needs refactoring. (The code isn't speaking for itself).

share|improve this answer

Get someone who is not on the project to review the code. Eventually, you'll start to get an idea of what you are taking for granted. Your variable names may not be so obvious. Yes, you do need a comment to explain WHY you're doing this. Having a set of team standards and a review process to keep them in check, can go a long way.

share|improve this answer

In a single word, Experience.

To start, you need to have put in the ground work, so I can't recommend more highly that programmers should take the time to read books such as Refactoring, which will provide some of the more essential tools in a programmers arsenal that will improve your ability to maintain code, and Clean Code which has been written by some of the most highly recognizable talents in our field, and which describes nearly everything you need to understand in order to ensure your code is clean and readable.

No amount of reading however is a substitute for hard-earned experience. You really need to have worked with code for a while in order to fully appreciate the difference that attention to code quality can make. Through experiencing the pleasure of working with clean, well factored code, as well as the pain of working with code spaghetti, you learn to better understand what the authors of these books were really trying to teach you, but you do so in the wider context of real live production code, where the quality of what you do really matters, and impacts your ability to work easily with your code on a daily basis.

It also helps to have either a good mentor, or a peer with the experience to confirm that you are putting the effort into writing code to a high standard. This is just one reason why code reviews can be so useful. Using code checking and formatting tools can also be a very useful aid to ensure that you are keeping things clean. Nothing however compares to experience earned through years of writing software, such that you automatically find yourself writing code that is clean, readable, and structured simply for ease of maintenance, and all because you've made it a habit to apply best practices for so long.

share|improve this answer

Some Tests/Indicators:

  • Turn off the IDE. Can you still read your own code? When there's a bug is it fairly easy to trace through it by hand and figure out what class you'll need a breakpoint in to figure out that's where the problem is? Or when you do use the IDE do you just not even bother and just step through from the very beginning?

  • Does debug often becomes a game of wack-a-mole where fixing one bug creates 2+ more.

  • From trigger pull to something useful actually happening, how many method calls does it take? How many methods pass the exact same or most of the same exact parameters on to another method call?

  • How many files do you have to open to just add a simple new method to a class?

  • Think on patterns and practices you've adopted. Did you do it because they made perfect sense or because somebody convinced you that "it's the only way to do it?" or because you wanted it on your resume or because some rockstar dev said so.

share|improve this answer

Without being puritanical: prefer functional style. Most languages these days (.NET, Ruby, Python, Javascript, etc.) support and promote it (e.g. LINQ, underscorejs).

It is exceedingly easy to read.

var recentTopCustomers = OrderList
    .Where(o => o.Date >= DateTime.Now.AddDays(-5))
    .Where(o => o.Amount > 1000)
    .OrderBy(o => -o.Amount)
    .Take(10)
    .Select(o => o.Customer);

It forces each node to have single, focused intent lending to clarity of purpose. And because each discrete task is isolated popping out, plugging in, and rearranging nodes (operations) to different ends is trivial. This lends to ease of maintenance.

share|improve this answer

Developing thinking in the architecture is a good practice. For example is good create mini-applications using hmvc architecture. So you can take each mini-application and use it in another environment.

For example, working with Codeigniter + hmvc extension you can create min-apps for:

  • Manage users
    • crud
    • auth
  • Manage files
  • etc

So you can take one and use it in another application.

share|improve this answer

Code is maintainable if you have, in some way, document the LOGIC you are using. It can be in comments, a separate text file, hand-written on paper, whatever. For every set of variables you use, you must document, in very few words, what the variable is supposed to go through in its life, in how many ways can it be initialized, where, when and by what code its supposed to change etc.

Another sign of good code is one that use as much less state as it can. This can be achieved by using lots of static methods, so that its ensured that they don't use any state/field.

Another sign is to have related code gathered at one place. Its too hard to maintain in practise a class that uses single-responsibility principle because of proliferation of lots of small cases. Your class can have many responsibilities if they are related and each has its own method.

Another sign is consistency. Every code has a convention: are you using stored procedures, if yes, do they do anything more than dml, i.e. do they have any logic (loops, conditions) in it? are you using triggers, cursors, bridge-tables vs parent-child relations etc? Whatever you do, be consistent. Don't sacrifice architectural consistency for fast development. When write new code, first go to any approach that works, then do some little tweaking for obvious edge cases, then do a little tweaking for some performance, then do a lot of refactoring till it follow the same architectural principles as the rest of your code.

share|improve this answer

protected by Doc Brown May 2 '13 at 21:21

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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