views:

1258

answers:

23

I would like to increase the code quality of myself and my team. What do you recommend me to do in order to achieve that?

We are working with Visual Studio and C# (don't know if it's relevant though).

Thanks! Shay.

P.S. I've written a blog post that summarizes the answers from here: http://ironshay.com/post/How-to-Increase-Code-Quality.aspx

+24  A: 

Unit testing

My perception is that when I write good unit tests my code is written better. I don't always go for a full TDD approach, but by considering the code paths and the ways to test different conditions you just naturally catch silly off-by-one errors.

So, devise a Unit Testing strategy, and ensure everyone uses it.

Peer Reviews

Great for learning from other developers as well at catching errors early.

Agree Standards

It's all too easy to let standards become a bureaucratic overkill. But if you can keep to some simple guidelines then you can help junior programmers quite a lot.

I would focus on

  • Error Handling and Exception strategies
  • minimal naming conventions
djna
+1 for code reviews.
Paul Biggar
+1 for exception strategies
Treb
+15  A: 

Read Code Complete. It's the best book I know on the subject.

nikie
Darn it, this was going to be my answer.
Martin
I still got the first version dating from 1993. It tried to reread it a few weeks ago, but a lot of the text is out-of-date which makes the book a difficult read. How is the second edition?
Florian
@Florian: I don't have the first edition, so I can't really compare the two. I'd say most of the material in the SE is timeless.
nikie
+10  A: 

I'd suggest you to use FxCop, StyleCop, Resharper, NUnit . These are the tools that will force you to write clean code. Also do code reviews.

Sorantis
While I agree these are nice tools, they in no way "force" you to write clean code. If you don't know how to use the tools, they are completely wasted. Resharper is nice, but can be ignored. NUnit just helps with unit testing, but if you don't know how to unit test, then the tool is wasted.
Martin
I think that knowledge of how to use these tools is taken for granted
Sorantis
Taking that knowledge for granted would be a fallacy.
Novelocrat
He said "use the tools", not "install them and then ignore them"!
Jason Williams
+3  A: 

Work with a revision control system like Subversion to avoid copy/paste and manual merge ? (relevant for a relatively big project)

Isaac Clarke
relevant for ANY project I'd say. But that won't improve code quality.
NomeN
From my own experience, it has (when working on the same source files). It is however bound to communication, conventions and such. We weren't exactly skilled nor experienced programmers, btw...
Isaac Clarke
If you are not using source control, even if it's a pet project of one developer, you are doing it wrong. Distributed version control programs like Mercurial and Git don't require a server and it takes two command lines to have all your code in the repository.
J. Pablo Fernández
+6  A: 

I would say :

  1. Code review
  2. Team meeting every week or every month where each member speaks about his learning, his tips found...The goal is: increase the quality of the whole team
  3. Doing some learning about the importance of testing (unit testing, and so on)
  4. Recommending some great reading to your team
  5. Introducing some development methods (SCRUM,...) or quality concepts: CMMI or ISO 90003
Matthieu
+2  A: 

Start writing unit tests for your code. One framework you can use for this is NUnit. You can then use extra tools like code coverage to tell you how much of your code has been hit by your unit tests, e.g. NCover.

Plug that into a Continuous Integeration environment (e.g. CruiseControl.NET) and you can have frequent, automated builds and running of unit tests.

In addition to unit testing: - Code Reviews - Follow consistent, defined standards within your code

AdaTheDev
+4  A: 

Put the responsibility onto the developer

I would personally advise that you instil the importance of code quality your developers. As developers we are all creative, and kinda do this thing because we like to be proud of the things we create.

The way we have approached code quality is through unit testing, code coverage, peer reviews, and most importantly a developer only says their work 'is done' when he can whole heartedly 'stamp' it knowing that it is;

  • A reflection upon his/her standards
  • Does what it was supposed to do (meets the requirements)

Just start talking ;)

I have found that Peer review, white boarding and stand-up meetings (See SCRUM) are all things that can help improve code quality.

Ok, so the wear the hat/shirt aspect I previously proposed hasn't gone down well - some may not work in jolly places that can take a tongue in cheek bit of fun for an hour or so. It is important to reward success so assign a talisker that represents success to sit on top of someone's monitor or alike - or exclude that person from buying that weeks pizza/beer.

Then hit the computer

Some tools that can help,

  1. StyleCop - Code Analysis - OpenSource
  2. Resharper - commercial (and a StyleCop plugin - OpenSource)
  3. Code Style Enforcer - free
David Christiansen
Research shows that we learn more from success than failure (http://web.mit.edu/newsoffice/2009/successes-0729.html), so mabye it's better to keep a SUCCESS hat to award people when they do a good job. Also it might switch group focus away from shame and blame which should improve the work atmosphere.
jandersson
@jandersson: I disagree with that: In my current project, the most important lessons came from our mistakes. @David Christiansen: I disagree with *wear the hat* part. Public humiliation should **never** be among your management tools (agree with all the rest, though).
Treb
Downvote for the "wear the hat" part.We have better and more constructive way of handling that : baby-sitting the build for exemple.
Antoine Claval
Not really sure it was worth a down vote mate. You can choose yourself what suggestions to take on board. If you think it would be taken as anything other than tongue in cheek then its obviously not something you would want to do.
David Christiansen
+1  A: 

Unit testing with coverage analysis -- and aiming for a high coverage score -- will help point out the dusty corners of the code. The discipline of testing will encourage you to write code that is more direct and to the point. Here's a blog post where I ramble on about this at length.

Having some examples of what good code looks like will help you see where you are going -- join the CLUB (Code like Uncle Bob) with Clean Code.

Steve Gilham
A: 
MadKeithV
+2  A: 

I completely agree with mentioned code reviews, test-first approach, static analysis and code style unification as ways of improving code quality.

I'd like to add one more option: learn and use other languages, especially with paradigm other than object-oriented. It extremely raises your mastery. Even if those languages are not appropriate for your production code, you can find ideas in them and you can build your own internal tools with those languages.

Rorick
I second that. Learning other languages is a great source of ideas, even if you're sometimes disappointed with some features not being shared between languages.
Isaac Clarke
+1 for other languages
Steve Gilham
A: 

First, Use design patterns. For a given functionality, a good design will lead to a reduced number of lines of code. To me, the less code you have (of course, without altering functionality), the better it is.

Secondly, code review.

Finally, never used some tools checking coding rules, but I guess they can help if well configured. Check initial cost and deployment cost.

dilig0
A: 

Automated Regression Tests

As others have said, unit testing certainly is a great way to improve the quality of your code. However, to really improve things you often need to refactor and break functionality (and at the same time re-write the unit tests). This is where automated regression tests which test the interfaces to your system, rather than the code itself, really become invaluable. There's nothing like having the confidence to really tear up your code that a full automated set of tests can give you for improving code quality and generally extending the life a of system.

Alex Spurling
Isn't that the principle of Extreme Programming ?
Isaac Clarke
+1  A: 

I agree with almost everything said so far, but I think that there is one more critic factor which is design review. You cannot achieve quality code with poor feature design because sooner or later walk around will start to appear. It will also reduce the total development time by reducing the amount of bugs and avoiding redesign and recoding the new design.

A: 

This is a question that I have been thinking about a good bit lately as I am involved in a project in which I am not writing any code, and have no influence over the code that is being written. But when I look at the code in the repository I find it to be God-Awful horrendous.

There are a lot of good suggestions here to help write more uniform, more correct, and yes, better quality code. But as someone earlier pointed out, what is important is just what do you mean by better code. To me, at this point, by quality code I would mean code that can be easily understood and modified. It doesn't matter how clean, or uniform, or even correct the code is if a maintenance programmer who is unfamiliar with the code will not be able to understand what it does, or is attempting to do.

From that aspect I would say the quality code is code that is easily understood and modifiable. Write clear code. Where that is not possible, write good comments. Even where the code is clear, document the purpose of the method. Don't Repeat Yourself; make it so that any errors that are found need to be fixed in only one place.

Dave Derry
+1  A: 
  1. Design testability, debuggability, and self-diagnosis into your software system from the beginning.

This means unit testing, assertions, always testing for erroneous conditions AND ensuring that the program will display the error in a way that is easy to track and understand later, even by a new developer.

Larry Watanabe
+1  A: 

Hi

First step define what you mean by quality. If you can't do that, all your reviews tests and inspections are worthless. It's not too difficult to define quality, check out Bertrand Meyer's OO Software Construction for a very good starting point.

Once you have a definition of what you want to achieve, implement those other suggestions that you like best, gradually, and review progress regularly.

Finally -- Quality is Free -- quality is conformance to specification and is built-in, not bolted on.

Regards

Mark

High Performance Mark
+4  A: 
  • Design your code before you start writing it!
  • Seek to simplify the problem/design/code wherever possible. This makes it easier to understand, code correctly, and maintain.
  • Try to break the design/code into small well defined functional units (folders, files, namespaces, classes, methods) to keep the codebase logically organised and well structured
  • Encapsulate behaviour where possible so that the implementation is hidden from the end user.
  • Get a coding style guide - there are loads on the web. Read many and pick out the best ideas from them (Don't just follow a rule because someone says you should - look for a good reason for every rule)
  • Document the code. Writing down how it works to a level where another programmer understands how to use it without having to ask any questions forces you to think about it, and often highlights problems.
  • Single-step your code so you fully understand how it actually works (as opposed to how you meant it to work)
  • Unit & regression test
  • When you find a bug, don't just fix it; work out why it happened and learn from the mistake.
  • The best way is to work as a team. Learn from each other, and the code others write. (Work on other people's code, pair program, discuss ideas in dev meetings, do code reviews)
Jason Williams
+1 - design your code before you start writing it ).
akf
A: 

better to start with code metrics.
they are easy to understand, easy to show where exactly the code going to be ugly.
the next step is automated testing, especially unit testing.

Avram
+3  A: 

Unit Test

Make sure that every scenario in your code has a solid set of unit test cases

Code Coverage

Make sure that the unit tests are passing through the maximum number of lines (at least 70%)

Build \ Test Automation

Make sure you have the infrastructure to automatically build your code base and run unit tests against the builds and sends reports to all team members for build breaks or unit test failures

Estimate designated time for testing

Most unexperienced developers will always underestimate the time for testing or sometimes include it in the dev time, which results in half baked code that breaks on edge cases.

Integration Tests

If your project is large enough that you needed to mock out some dependencies, you need to write some extra test suit that test the end to end scenario without mocking the dependencies or at least with minimum mocking also have this test suit automated to run with every build.

Code Review

No code checkins without a reviewer Period.

You can also have one hour per week to go through the most significant code changes for team review.

bashmohandes
A: 

Check out Joel Spolskys The Joel Test: 12 Steps to Better Code

  • Do you use source control?
  • Can you make a build in one step?
  • Do you make daily builds?
  • Do you have a bug database?
  • Do you fix bugs before writing new code?
  • Do you have an up-to-date schedule?
  • Do you have a spec?
  • Do programmers have quiet working conditions?
  • Do you use the best tools money can buy?
  • Do you have testers?
  • Do new candidates write code during their interview?
  • Do you do hallway usability testing?

http://www.joelonsoftware.com/articles/fog0000000043.html

Jonas Söderström
A: 

More focus and awareness of management towards code quality This will ensure that management does not ask developers to ship code early at the cost of quality. It will ensure that required time and resources will be allotted towards quality. Also better coders will be rewarded.

Hire Better People Bad programmers will never write good code no matter how good the processes and tools are.

Communication Ensure communication between domain experts, developers, testers etc. Carry out code reviews, pair programming and knowledge sharing sessions.

Tools Use static code analysis tools like fxcop, resharper etc

Unmesh Kondolikar
A: 

NDepend documentation comes with some pretty cool and advanced online blog posts, articles and white books concerning code quality and testing of .NET code:

Fighting Fabricated Complexity

Layering, the Level metric and the Discourse of Method

82 code metrics definition

Code metrics on Coupling, Dead Code, Design flaws and Re-engineering

Make the most of your test coverage data

Are you sure added and refactored code is covered by tests?

Also, NDepend comes with Code Query language (CQL). CQL is dedicated to write code quality rules about code quality that can be verified live in Visual Studio, or that can be verified during build process and through a report. Here are a few samples of CQL rules (designed to be highly customizable):

Code refactored recently should be 100% covered by test:

WARN IF Count > 0 IN SELECT METHODS WHERE CodeWasChanged AND PercentageCoverage < 100

I don’t want that my User Interface layer to depend directly on the DataBase layer:

WARN IF Count > 0 IN SELECT METHODS WHERE CyclomaticComplexity > 15 AND PercentageComment < 10

I don’t want that my User Interface layer to depend directly on the DataBase layer:

WARN IF Count > 0 IN SELECT NAMESPACES WHERE IsDirectlyUsing "DataLayer" AND NameIs "UILayer"

Static fields should not be named m_XXX (Custom naming conventions):

WARN IF Count > 0 IN SELECT FIELDS WHERE NameLike "^m_" AND IsStatic

Methods out of MyAssembly and MyAssembly2 should not have more than 30 lines of code:

WARN IF Count > 0 IN SELECT METHODS OUT OF ASSEMBLIES "MyAssembly1", "MyAssembly2" WHERE NbLinesOfCode > 30

Public methods should not be removed to avoid API breaking changes:

WARN IF Count > 0 IN SELECT METHODS WHERE IsPublic AND IsInOlderBuild AND WasRemoved

Types tagged with the attribute MyNamespace.FullCoveredAttribute must be thoroughly covered by tests:

WARN IF Count > 0 IN SELECT TYPES WHERE HasAttribute "MyNamespace.FullCoveredAttribute" AND PercentageCoverage < 100

Patrick Smacchia - NDepend dev

related questions