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.

I am a big fan of good coding style, producing clean, clear code that runs well and is easy to use and integrate into larger systems. I believe that we programmers are essentially craftspeople who should take pride in our work, every line. I am not fond of code that is inconsistently formatted, cluttered with commented out experimental code, and rife with unhelpful or misleading function and variable names. But I sometimes find it hard to argue with code like this that basically works.

If you think that coding style matters, I am looking for recommendations for ways of teaching good, professional coding style to the junior programmers under me. I want them to take pride in their work, but my concern is that they appear to become satisfied when their code just barely works, and seem to have no interest in producing what professionals like me would consider professional code. On the other hand, if you think coding style is not particularly valuable, I welcome your comments and am open to reconsidering my standards and tolerances.

I know the usual arguments in favor of good code: comprehensibility, ease of maintenance, etc., but I would also like to hear some rebuttals to arguments like "it works, what more do you want?"

In our industry we can use the compiler to hide a multitude of sins. Clean code and messy code can both lead to identically functioning programs, so does cleanliness matter, and if so, why?

[While there are several existing questions on coding style, I didn't find any that related to teaching methods and ways to instill good coding style in junior programmers.]

share|improve this question
35  
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." –  marco-fiset Apr 23 '12 at 13:26
1  
Thanks everyone for the great answers. I think we all just made this site and our profession a little better. –  Randall Cook Apr 24 '12 at 17:32

17 Answers 17

up vote 44 down vote accepted

Make a good impression

Take some of the well-known books, e.g. Clean Code, Code Complete, Coders at Work, The Clean Coder: A Code of Conduct for Professional Programmers etc. (see here for full lists) and give them a couple of days to read one - at work, in a private office. Space those out, say 1 book a month or a quarter. They will see from the effort that what you're personally saying is really important, not just "the company line" to take with a grain of salt. Obviously make sure you've got management in line with this - you don't want them saying in passing "huh? what's person X up to? holed away in there with the door closed?"

Along with continual, more formal training classes in the latest technologies.

Also, as things are done "the right way" gave big encouragement and even rewards. Otherwise it can be more of a negative, punishing, rather than positive, rewarding environment. Most folks want to do and want to be known for doing "a good job" if they have the tools to do it.

Practice what you preach, Preach what you practice

Talk about code, talk about the good principles, talk about new tools, become 'known' for it.

Provide / support /suggest screencasts, videos, peepcodes and whatever online tutorials and classes you can find.

Support and suggest appropriate local user groups, including those on sites like http://www.meetup.com

If you are in office (i.e. not virtual) a well-stock bookshelf of the actual books you would like people to use is good. Find a way to make this be "not just dusty bookshelf in the corner" but placing it really prominently, Moving the books around,etc. Use your imagination too. Maybe every programmer gets one book as 'homework' a month and you have a monthly meeting where they get to 'present their findings' !

This will make far more of an impression that any 10 minute conversation alone and it will remove you from the 'criticizer' role and allow them to learn how to fish for themselves (rather than giving them fish, you know the deal). Some junior folks also find it intimidating to have a senior folk always explain stuff, when sometimes all they really want is some time to study, practice and absorb it.

Instill a culture of learning and excellence

Basically you want to create "a culture of learning and excellence" so that you can Practice what you Teach and inspire others to do the same.

This should be in conjunction with code reviews to see if/how the principles apply to the actual work being done. Conversely, code reviews done without the above can feel like whipping sessions to the student no matter how well intentioned by the teacher.

share|improve this answer
3  
Interesting point of view. I have always considered practice and one-on-one mentoring to be infinitely more helpful than books and lectures. –  Phil Apr 23 '12 at 13:34
1  
@Phil: I'm a fan of both books and one-on-one mentoring. In the past I've asked junior devs to read Code Complete, then followed up with concrete examples from our own codebase which demonstrate how one principle or another benefited us. Your comment below about "Do this because it's important, not just because I want you to." sums this up nicely. –  Joshua Smith Apr 23 '12 at 15:05
2  
Uncle Bob (and group) makes a strong argument on why it matters in Clean Code. I found the argument that as programmers we spend more time reading code than writing code, so reading it should be as easy as possible even if it makes writing code more difficult. Since they are junior, I'd also recommend his The Clean Coder: A Code of Conduct for Professional Programmers as it sets the tone on why they should care about improving their craft. I've also found katas to be great tools for this as well. –  Paul Apr 23 '12 at 19:28

I think the best way to encourage this behaviour from young developers is to practice it yourself and be a role model for them. If possible, you should pair program with them often and put emphasis on code quality when you program with them. While pairing, you can explain and justify good coding choices as you make them. You can explore the "worse" options and explain why they aren't a good solution in the long run. Being a part of this kind of development in a hands on way is probably one of the best ways to teach new developers about the importance of code quality. If everyone on your team thinks code quality is important, they will learn to respect it as well.

share|improve this answer
1  
@RandallCook You'll find that most mid-level programmers don't really care about the arguments. If you give them a "process" to follow and enforce they will. The ones that actually care will be more than willing to engage in debate with you about the arguments of good code. Put something in place that others can follow and engage in meaningful debate with the ones that want to know the "why" –  Andrew Finnell Apr 23 '12 at 1:19
2  
@AndrewFinnell They may not care, but I have found that explaining why we do things is important (in all areas of life). It helps them understand things on a deeper level so that when they encounter a situation that is outside the scope of your explicit rules, they will still know what you want from them. It also communicates "Do this because it's important, not just because I want you to." Easier to be motivated to follow the rules when you know why. –  Phil Apr 23 '12 at 13:39

The actual problem is that people disagree what exactly is clean code. Once you've written perfect code with every detail exactly correct, the next person is still going to think it's crap. Every programmer is looking at different parts of the code and finding things he doesn't like while simultaniously ignoring all the good parts. This is necessary part of the programming, since programmers need to find the bad stuff before it goes to version control for the first time. So programmers can easily regognize bad code. It's just that it's different for every programmer.

In a team, this feature is going to cause problems, if there is too strict rules for conventions, or if people have to maintain and work with code written by other persons. Best solution is to keep conventions, but not enforcing them. And then make sure everyone knows who is responsible of each part of the code.

Now teaching junior programmers is tricky. Most attempts end up in junior programmer thinking that his last code was somehow bad and the teaching session is required because of it. Like it's a punishment for some error that happened before.

share|improve this answer
2  
Any recommendations for how to make teaching not seem like a punishment (to the junior programmer, of course :) ), @tp1? –  Randall Cook Apr 23 '12 at 3:03

All programmers should always do code reviews with a senior programmer before committing/merging their code changes.

  1. This gives the senior programmers a chance to come to a consensus regarding which styles they want to enforce (and recognize which ones are just a matter of preference) among themselves.
  2. It gives junior programmers a chance to learn what practices are expected from their team right from the get-go. Within a couple of months, 90% of the code they write will already be following those practices before the code review.

Also, most IDEs have tools you can configure to enforce the vast majority of coding style preferences with handsome little squiggly underlines and options to automatically correct the style throughout a file. Junior programmers will pick up on that pretty fast.

share|improve this answer
3  
+1 I do like your first point as it emphasizes that ALL programmers should have their code reviewed. –  Marjan Venema Apr 23 '12 at 6:18
2  
All programmers should always do code reviews with a senior programmer before committing/merging their code changes -- Really? That's a pretty sweeping statement. We don't do this in our shop at all. We do code reviews periodically in a meeting-style setting, but to do a code review before every code check-in would be quite onerous. –  Robert Harvey Apr 23 '12 at 17:14
2  
@Robert Harvey: We also do code reviews for each check-in. No new code can be tested if it has not been reviewed. It is part of the process. Of course, well-written, clean code is easier to review. :-) The reviewer can reject the commit if some coding guidelines are not respected (missing doxygen comments, badly formatted blocks or method headers, missing NULL pointer checks, and so on). –  Giorgio Apr 23 '12 at 19:26
4  
@RobertHarvey, it's not onerous at all. In my experience it's typically on the order of 15 minutes of review a day and has huge payoff in terms of knowledge dissemination, and small payoff in terms of code quality. Reviews don't have to be extremely formal, by the way, and you can give them an informal name like "buddy checks" or whatever. "I added a check for this case to fix bug #12345." "Okay, if you put the constant first, the compiler will catch the case where you type '=' instead of '=='." "Oh, neat trick. Anything else?" "No, looks good." <commit> –  Russell Borogove Apr 23 '12 at 21:28
2  
@tp1: Many people have found a lot of benefit from this practice, so your calling it "evil" just sounds bigoted. For me the slight delay is totally worth the improved code base. Besides, Distributed Version Control Systems can solve the dependency chain issue: you can do your work in your own branch, and if some other developer is chomping at the bit to start work based on the change you just made, they can merge your changes in with their branch and start working on it while you do your code review. After your review, your code gets merged into the head. –  StriplingWarrior Apr 24 '12 at 18:18

Take two coders with similar coding style problems, and have each maintain the others code. See what they learn from that experience.

share|improve this answer

It seems like something as simple to enforce as a coding standard is only going to be handled by:

  1. Hire people who agree with you.
  2. Code Review
  3. Use applications that can automate this stuff.
  4. Make is as much a part of doing your job as showing up. There have to be consequences for not doing your job.

Personally, I would be leary of a manager that made this too much of a priority. Focus on what is important and don't get nitpicky. You should be able to justify why, but there are times to just pick a standard (Who knows why a 4 space indent is better than 5 other than you're just being mental.).

Get some team consensus on standards. This will improve the quality and level of adherance. Don't waste too much time on a debate. Eventually a leader makes a decision based on the amount of input.

share|improve this answer
1  
Indeed. I'm happy with an 8 space indent as long as my manager is providing me with a nice widescreen monitor. :-) –  Cody Gray Apr 23 '12 at 9:15
1  
+1 for point #1. Some programmers will just be sloppy regardless your standards. Don't hire them in the first place. –  Phil Apr 23 '12 at 13:43

If if it is important to you use something like checkstyle and put it in a pre-commit hook. If the checkstyle fails, the code can not be committed. Checkstyle is pretty good at giving feedback messages. People will figure out why their code did not meet the standard and what they need to do to make it through.

share|improve this answer

Do Code reviews

Especially point out problems occurring from bad coding style or prevented by good coding style.

Do a lot of talking why this is important.

Depending on how junior your coworkers are, do realize you have to learn to write code before you can write beatifull code.

share|improve this answer

One idea: show them what code could look like if deliberately made to be not easy to read and comprehend (http://www.ioccc.org/2011/konno/konno.c is a short nice example for instance). Ask them would you like to receive code like this to maintain?

Highlight the importance of

a computer language is not just a way of getting a computer to perform operations ... programs must be written for people to read, and only incidentally for machines to execute.

(quote from SICP)

share|improve this answer

Give them a really badly written unit of code to modify (and test) and then to rewrite (and test) and then give them a really well written unit of code with unit tests to modify (and test) and ask them about the experience.

After this give them a list of standards to read and refactor their code (from the previous exercise) to match those standards as practice.

You will need an organized documentation of your standards prior to this.

share|improve this answer

I have learnt good coding style from one of the senior developers from one of my past projects. He reviews my code for every commit during code review meeting and he will explain me line by line if something can be improved there.

  • He goes thru each naming of the variables and methods and explains how to name them better.

  • He goes thru each methods and tells me how to make more readable and more efficient.

  • He was very polite but his mentoring helped me a lot.

  • It took only three months for me to align myself with him and now he rarely finds mistakes in my code.

I follow the same method of teaching my junior developers and it works.

share|improve this answer

I believe that you should not be teaching a specific coding style for the following reasons:

  • Junior programmers need to learn from their mistakes. They will continuously improve by evaluating their work and doing code reviews with senior developers.

  • Coding guidelines will vary with a culture of a company you are working for. I might argue against what you consider to be a clean code.

  • Junior programmers normally don't get much exposure to the enterprise systems, and that's where the clean code normally lives.

  • Quite often university lecturers have been stuck in the academic world for decades. I have personally found their guidelines and feedback to be rather unhelpful and poor in comparison to current industry's standards. Some, of course, are very good.

To summarise:

  • I think the solution is not to teach any specific guidelines or coding styles, but try to explain their importance in projects of various sizes.

  • There is only so much you can explain in the classroom and from the books.

  • Developers will have to get their hands dirty to see the real benefit for themeselves.

  • Allocate junior developers to pair program, then review their work and give them feedback. Eventually they should start seeing the benefit.

There isn't a silver bullet coding style that will always work, just like anything in systems engineering.

share|improve this answer
1  
Good answer. I don't think it is getting the upvotes it deserves. –  Randall Cook Apr 24 '12 at 17:28

I first learned programming by being handed a well written program and lead through it line by line. (I learned a lot in those couple of hours that I didn't get in my entire degree program.) Try the same with them, walking them through one of your best modules pointing out how and why it is constructed and styled that way. You can do this in a group session.

If you can, play benevolent dictator. Depending on your revision control system you may be able to use it to help you. However, you could end up being the bottleneck in the development process.

Deploy an automated style checker to verify as many styling rules as you can. (Many checkstyle rules should be portable between Java and C++.) This will get you part way there, but will not substitute for code reviews. Getting your developers to peer review code may help reduce the load.

If you are implement an automated style checker, you may also want to implement a static code analysis tool. This should help eliminate some of the bugs than may be missed in code reviews. It will also enable you to concentrate on stylistic issues rather looking for the errors the static code analysis tool covers. There may still be common cases that need to be checked for.

Develop a checklist for developers to use before checking in the code. This can contain other things you want to occur before check-in. There is growing evidence that checklists can help reduce errors. Encourage developers to build their own check list of mistakes they commonly make, so that they can avoid repeating them.

share|improve this answer

Talk them about D. Knuth's literate programming.

I believe that the time is ripe for significantly better documentation of programs, and that we can best achieve this by considering programs to be works of literature. Hence, my title: "Literate Programming."

Let us change our traditional attitude to the construction of programs: Instead of imagining that our main task is to instruct a computer what to do, let us concentrate rather on explaining to human beings what we want a computer to do

Donald Knuth, about literate programming.

In my humble opinion, the fact that a computer program's primary goal is to communicate intellectual entities to other programmers, is a decisive argument for the importance of coding style.

share|improve this answer

I think it would be great way to train the new programmers with the techique of Naming Conventions [ it is the standard for naming a variable, method or class]. For better following flow of programmers who touch the code will be easily handle such with knowing the relevant names used.

For eg: static Variables starts with s, argument Variables starts with a, etc.,

share|improve this answer

Clean code and messy code can both lead to identically functioning programs, so does cleanliness matter, and if so, why?

A difference between clean and messy code is so huge :

  • changing a messy code is always a daunting task, because usually it has no a safe net called unit tests
  • messy code tend to have huge and very complex functions and classes. Trying to understand them is pointless and very difficult
  • messy code usually has copy/pasted code parts, increasing the complexity further

On the other hand, having a clean code, everyone in the team can easily understand the logic behind, and add new features without much efforts.

share|improve this answer

I think an underestimated aspect of coding style is that it manifests itself naturally. When I see a source code I've written a long time ago, I usually feel a compelling wish to break through time-space continuum just to punch myself in the face for the (perceived) monstrosities I've performed in the said source. Since you are mentoring juniors, and they tend to learn fast (since they need to), do the simplest possible solution: allow them to write a bad piece of code (once!), then make them maintain it. Chances are, if they're good at software engineering, they'll repent their sins and refactor the code properly. Of course, don't release their spaghetti collection as production-grade code, I'm certain there are a lot of opportunities to make a junior dev write something small, almost 'throwaway'.

There's no software school like real life

DRY makes perfect sense when you've had to edit that copy-pasted line 4 times, and you did it only 3, that's why the code dereferences a null pointer and the app crashes...
Also, the energy you will spend trying to convey 'good' methodologies upon them will probably be a lot, and it's not certain they won't dismiss it with a "Whatever, it works" as you pointed out.
So show them in practice that code style matters, by demonstrating its better readability to themselves, too.

Supporting software is way more useful for programmers than they think it is

I think it's another topic, but most people instinctively assume they write good code (I plead guilty). So fixing someone else's mess can be good for one's habits - you wouldn't sin if you just returned from a vacation in hell, right (religious views aside)?

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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