share
Stack OverflowHow to deal with with programmers who refuse to indent their code?
[+39] [30] Phulore R - Profile 2
[2010-02-16 18:38:14]
[ language-agnostic coding-style ]
[ http://stackoverflow.com/questions/2275349] [DELETED]

The firm where I work has programmers who still don't seem to understand the importance of indentation and write all the code aligned to left margin. What arguments can I put to convince them of the importance of indentation?

(62) Just reading this makes me cringe... - Reed Copsey
(78) Can you fire them? - SLaks
(12) It may be useless to argue. Why not put a pre-processing task that indents everything properly when you check in code? >:) - Kylar
(7) If they don't even indent, do you really think they use source control? - SLaks
(11) Boy, that's a tough one. Just look for PhD level senior people, who are not software engineers but have their expertise in other areas, and you will see this disease. And they will not consider changing it. It's not just that they don't indent, they also cram inscrutable code like tuna in a can. I suspect part of it is, part of being a highly respected researcher is that almost nobody should be able to understand what you've done. - Mike Dunlavey
@Reed: me too... - Arthur Reutenauer
(2) My way of dealing with this would require getting a pillow case and a couple dozen oranges.. - Tim
(2) If you are not their boss, talk to you boss about it and make him enforce it. - trinithis
(17) That's crazy! Everyone knows the first line of each paragraph of code should be indented. - Jason Orendorff
(3) Visual Studio 2008 - Ctrl-K, Ctrl-D - Joe
(5) I think SLaks is the closest, but I don't think he goes far enough. Perhaps you can take the poor soul out behind the shed and put them out of their misery. - Chris Lutz
Proper use of whitespace is king. - Josh K
(1) I've never even heard of anyone aligning all their code to the left. How strange. - Sam
(1) Maybe this question should be on a management related forum, but I do not know where. - rleir
(1) Why do compilers accept unindented code? - dsimcha
(4) You should indent those coders... into 6 feet of dirt >:) - Mark Rushakoff
@Tim: Cobblestones, not oranges... ;-) - EricSchaefer
(1) Where do you find these people??? - Tom R
(1) Well, this is what coding standards are for. Every shop should have one, and everyone should follow the standard, whatever that is. - Robert Harvey
@Sam, you've been lucky. I've slogged through more crap code the last couple of weeks and poor ( or lack of) indenting was a huge one. - Elizabeth Buckwalter
(1) I'd like to add that I don't think this should be closed, though I may be biased. - Elizabeth Buckwalter
(1) I agree (though I'm biased as well). It's argumentative as worded, maybe, but "Why should code be indented?" seems legitimate to me. - Jason Orendorff
[+96] [2010-02-16 19:04:16] Eimantas

Make them code in Python.


(16) Make them code in Haskell. - trinithis
The only issue that I see is that some jerks refuse to consistently indent their brackets - dassouki
(7) Make them code in Whitespace (compsoc.dur.ac.uk/whitespace) ;) - David
(5) +1 for whitespace! But technically speaking, whitespace isn't indented either, right? - Steve
They'll just write it all on one line then. - RCIX
(4) So if whitespace is used to indent most programming languages, are alphanumeric characters used to indent Whitespace? :-) - Steve
(12) My first idea involved knives, but Python is fine too. - Manos Dilaverakis
Well, make them code in assembly language, everybody will be happy... - PhiLho
1
[+39] [2010-02-16 19:42:52] Jason Orendorff

Clearly we've all internalized this so much that no one can remember why we do it. At least, none of the other answers so far. ;)

Why is indentation so useful? Because control flow jumps around in a program, and indentation helps you find where it's going. For example:

if (k == 0) {
if (!foo.hasKey(bar))
foo.put(bar, 1);
if (order.held())
order.release();
else
order.markUpdated();
}
Notifications n = order.getNotifications();
if (n != null)
n.sendUpdate();

On the first line, what if k isn't zero? Where do we jump to?

With indented code, you can just visually scan down to the next bit of code directly underneath the if:

if (k == 0) {
    if (!foo.hasKey(bar))
        foo.put(bar, 1);
    if (order.held())
        order.release();
    else
        order.markUpdated();
} //<---- here!
Notifications n = order.getNotifications();
if (n != null)
    n.sendUpdate();

Similarly, at the end of an if block, indentation helps you visually skip over the else block. And at the end of a loop, your eyes can easily zip back up to the top.

Once you're used to it, you can easily follow a break or continue.

Persuading people of anything is hit-or-miss no matter how right you are. :) It seems like it would be best to try to convince one person at a time, in a totally non-confrontational way, using respectful language and real-world examples.

I hope you can convince your colleagues to use indentation, but if not, remember they are human beings doing what works best for them. And remember they're your teammates. Treat them humanely. Write code they can work with. If you like, spin yourself a little emacs mode that auto-indents the file when you open it and un-indents it when you save it. It'll be fun, and you'll have a story to tell. Life is too short to spend it bickering over stuff like this.


(2) +1 for the emacs thing. If all of the code written had no indention(while you could still develop), surely they would start to see the light. - Earlz
(1) If you can't persuade someone to understand something so universally accepted (and demonstrably useful), you're either a very poor communicator or the people you are persuading are making a conscious decision to disagree. In the latter case you should simply resign, lifes too short for putting up with such stupidity. You also mention treating teammates humanely. The humane thing to do is actually to help improve their chances of ever getting a job anywhere else by helping them understand why it is important to indent their code. - Ashley Henderson
(2) @Ash My view is that if they won't be persuaded, either you're an average communicator, for a programmer, or they're just not cut out to be programmers. In other words, it's not an unlikely outcome and it doesn't necessarily involve anyone being stupid or malicious. Also, going into any conversation with "If you are so stupid and stubborn you can't see this, I'm going to quit" in the back of your mind sounds like a plan for leaving your job. - Jason Orendorff
2
[+27] [2010-02-17 01:19:24] Aaronaught

Institute a rule where all code must be written on one line, with no unnecessary white space at all (including white space between operators, arguments, etc.) A single class would then start to look like the following:

class OrderManager{void submitorders(cust){int c=db.getordercount(cust.id);if(c>0){orders=db.getorders(cust.id);for(int i=0;i<c;i++){o=orders[i];if(o.isactive){submit(o);o.isactive=false;o.save();}else{log(orderinactivemsg,o.id);}}}else{log(ordersemptymsg);}}void submitorder(order){db.orders.insert(order.id,order.refnum,order.prodid,order.qty);}}

Once people start to complain that they can't write code like this, fight them at every step of the way. Make insane claims like "white space makes the program waste memory" and "we need to keep the code minified in case we ever decide to convert to JavaScript."

Insist that they're being unreasonable and recite fabricated war stories about how they didn't even have enter keys in the '70s and the company would dock 10 cents off your $20/week salary every time you pressed the space bar. Admit that it was harsh, but, darn it, it got the job done, and that's how it's going to be on your watch.

Then, after the complaints reach fever pitch and people are either burning effigies of you or threatening to quit, finally "crack" and relax the rules. Come up with a set of "revised guidelines" that include proper indentation and say that you're willing to test it out for a trial period and see how it goes, but if anybody doesn't follow it to the letter then you'll revert back to the old rules.

Insane? Probably. Sadistic? Maybe. Effective? You'd better believe it.


(5) that is amazing. nicely done :) - Peter
3
[+22] [2010-02-16 18:41:23] Alexander Gessler

Take the most complex algorithm implementation you can find and remove the indenting. Show it to them and let them explain the control flow.


(33) I have a hard time imagining this will work on real live human beings. Nobody likes being confronted like this, especially by someone who obviously considers himself superior in some way, however minor. Coders who write everything left-aligned might have trouble explaining "the most complex algorithm implementation you can find" regardless of how it's indented. They might say, "This is stupid. We don't have code this complicated." And the thing is, they'd be right. - Jason Orendorff
(5) So then pick out a more complex method from your program (that one of them worked on), strip indenting, and ask them the same question. - RCIX
4
[+18] [2010-02-16 18:41:05] dassouki

Implement a code style [1] policy. As part of your code review, you should ensure that it follows a code style. People will moan and complain at first but will get used to it eventually,

You can be mean and do something like this:

                                class my_class (blaMe1,blaMe2):
 { // code here;    //code here
            //code here
     //code here
  //code herererrer herererrerherere rrerherer errerherererrer herer errerherere rrerherererrerher ererrerherererrer herererrerher ererrer; function me_function {//hello there };
 // code here adadatqradadadadada }
[1] http://en.wikibooks.org/wiki/C++_Programming/Code_Style

(5) on top of this, make code style policy conformance a job performance indicator which is measured periodically. - KP.
5
[+13] [2010-02-16 19:11:22] wheaties

Use a code beautifier. That way, they can code however they'd like and the ultimate end result will be code that everyone can read.


(3) … and link it into your VCS so that code gets reformatted into the company style on commit (and reformatted into your preferred style when you check it out). - Quentin
6
[+13] [2010-02-16 23:17:12] Elizabeth Buckwalter [ACCEPTED]

Have them read this question and all the answers.


(9) @Scrub: You marked this as the answer. Does that mean it worked?? - Robert Harvey
The greatest upvoted meta-answer of all times? - progo
7
[+12] [2010-02-17 10:01:42] James B

I can't believe there are still people in this industry who believe this kind of rebellion against the groundswell of opinion, wisdom and common sense is a rage against the machine. Perhaps suggest this kind of formatting instead?

#include                                     <math.h>
#include                                   <sys/time.h>
#include                                   <X11/Xlib.h>
#include                                  <X11/keysym.h>
                                          double L ,o ,P
                                         ,_=dt,T,Z,D=1,d,
                                         s[999],E,h= 8,I,
                                         J,K,w[999],M,m,O
                                        ,n[999],j=33e-3,i=
                                        1E3,r,t, u,v ,W,S=
                                        74.5,l=221,X=7.26,
                                        a,B,A=32.2,c, F,H;
                                        int N,q, C, y,p,U;
                                       Window z; char f[52]
                                    ; GC k; main(){ Display*e=
 XOpenDisplay( 0); z=RootWindow(e,0); for (XSetForeground(e,k=XCreateGC (e,z,0,0),BlackPixel(e,0))
; scanf("%lf%lf%lf",y +n,w+y, y+s)+1; y ++); XSelectInput(e,z= XCreateSimpleWindow(e,z,0,0,400,400,
0,0,WhitePixel(e,0) ),KeyPressMask); for(XMapWindow(e,z); ; T=sin(O)){ struct timeval G={ 0,dt*1e6}
; K= cos(j); N=1e4; M+= H*_; Z=D*K; F+=_*P; r=E*K; W=cos( O); m=K*W; H=K*T; O+=D*_*F/ K+d/K*E*_; B=
sin(j); a=B*T*D-E*W; XClearWindow(e,z); t=T*E+ D*B*W; j+=d*_*D-_*F*E; P=W*E*B-T*D; for (o+=(I=D*W+E
*T*B,E*d/K *B+v+B/K*F*D)*_; p<y; ){ T=p[s]+i; E=c-p[w]; D=n[p]-L; K=D*m-B*T-H*E; if(p [n]+w[ p]+p[s
]== 0|K <fabs(W=T*r-I*E +D*P) |fabs(D=t *D+Z *T-a *E)> K)N=1e4; else{ q=W/K *4E2+2e2; C= 2E2+4e2/ K
 *D; N-1E4&& XDrawLine(e ,z,k,N ,U,q,C); N=q; U=C; } ++p; } L+=_* (X*t +P*M+m*l); T=X*X+ l*l+M *M;
  XDrawString(e,z,k ,20,380,f,17); D=v/l*15; i+=(B *l-M*r -X*Z)*_; for(; XPending(e); u *=CS!=N){
                                   XEvent z; XNextEvent(e ,&z);
                                       ++*((N=XLookupKeysym
                                         (&z.xkey,0))-IT?
                                         N-LT? UP-N?& E:&
                                         J:& u: &h); --*(
                                         DN -N? N-DT ?N==
                                         RT?&u: & W:&h:&J
                                          ); } m=15*F/l;
                                          c+=(I=M/ l,l*H
                                          +I*M+a*X)*_; H
                                          =A*r+v*X-F*l+(
                                          E=.1+X*4.9/l,t
                                          =T*m/32-I*T/24
                                           )/S; K=F*M+(
                                           h* 1e4/l-(T+
                                           E*5*T*E)/3e2
                                           )/S-X*d-B*A;
                                           a=2.63 /l*d;
                                           X+=( d*l-T/S
                                            *(.19*E +a
                                            *.64+J/1e3
                                            )-M* v +A*
                                            Z)*_; l +=
                                            K *_; W=d;
                                            sprintf(f,
                                            "%5d  %3d"
                                            "%7d",p =l
                                           /1.7,(C=9E3+
                              O*57.3)%0550,(int)i); d+=T*(.45-14/l*
                             X-a*130-J* .14)*_/125e2+F*_*v; P=(T*(47
                             *I-m* 52+E*94 *D-t*.38+u*.21*E) /1e2+W*
                             179*v)/2312; select(p=0,0,0,0,&G); v-=(
                              W*F-T*(.63*m-I*.086+m*E*19-D*25-.11*u
                               )/107e2)*_; D=cos(o); E=sin(o); } }

If you are going to use <pre> you have to encode < and > to &lt; and &gt; I just indented it by four spaces to change it to Markdown format. - Brad Gilbert
what's the output ? - dassouki
8
[+7] [2010-02-16 18:43:55] batbrat

I've tried to convince programmers to indent their code before. Experience worked where arguments failed. I found that having people who don't indent code to debug/maintain even a few hundred lines of unindented code made them see light. Short of firing them, or having a code style policy imposed, experience works best.

On a lighter note, start using Python. (or make them learn it!) ;)


(2) Yeh, when I was at the very beginning of the programming learning curve, I thought indenting was a waste of time, as well as good variable names, comments, and readability in general. I changed my mind fast the first time I ever had to read my code more than a day after I wrote it. - dsimcha
I know cases where experience did not work. At all. - mafutrct
@mafurct I shudder to think of that. How did you deal with it? - batbrat
9
[+4] [2010-02-16 19:02:03] Earlz

Do something like that FXStyleCop or whatever and force them to install it and use such a thing so that they get warned all the time about how poorly formatted their code is..


(1) Even better, instead of a warning, make it an error so it breaks the build if they don't do it. We do that to ensure comments are correct and present on all our public methods. - womp
(2) @womp: How do you check comments are correct? If the comment claims that the function doing 2*x “adds 1 to its argument”, I'd be surprised by an automatic checker that found this discrepancy. And just having every parameter named in some special place in the comments does not seem worth the effort to me; the primary thing I ask from a comment is that it tells me something that is not obvious from the source code alone. - Christopher Creutzig
@Chris - yeah, you can't tell that kind of thing, however you can enforce that the comments indicate what the parameters and return values are, as well as having descriptions. You can also enforce certain patterns for comments, like that the descriptions for properties begin with "Gets or sets...", or "Gets ... " for read-only properties. - womp
(4) A comment that tells me that the getColor method gets the color is best left out. Seriously. DRY applies to comments, too. - Christopher Creutzig
10
[+4] [2010-02-16 19:02:16] Jon Seigel

Lead by example.

If your properly formatted code really is easier to read and modify, then the others should see the benefits immediately.


(1) I have tried that many times and it is so frustrating when those kind of people have been over your code and "re-formatted" it even though emacs can clean up the mess. - Christian Madsen
(4) If that's happening, then it's a separate issue entirely, and should probably be escalated to a manager. - Jon Seigel
11
[+4] [2010-02-17 07:14:43] Jim Dennis

The best suggestion I ever heard for this situation comes from a fortune cookie that my wife read to me aloud, years ago:

# This code should be indented vertically ... six feet DOWN
# and covered with dirt!

12
[+3] [2010-02-16 22:22:48] jerry's kid

Two words: Choke Slam.


13
[+3] [2010-02-17 00:40:42] Sara D Gore

I would continually ask them questions about their code. Tell them that you can't understand it the way it is, and ask them to explain specific parts to you. Explain that their poor stylistic choices make it difficult for you to understand what they've done. Hopefully they will do a mental cost analysis and decide that it's less work to indent (or use a styling program) than it is to deal with questions.

I used to have a coworker who refused to pass on vital information about projects. The rest of the team constantly called him at home on his days off to get the information that he neglected to give us while he was at work. Eventually he started communicating better.


14
[+3] [2010-02-16 21:06:36] jdv-Jan de Vaan

Start with coding standards (already suggested). Make sure that your management supports this. I assume that the majority of the workforce will support you too. Be sure to tell everyone that the coding standards are going to be a compromise.

To enforce coding standards, the best thing I know is pair-wise check-in. This means that for every check-in, a fellow software engineer reads through the code and agrees that coding standards were followed. Works best if you require that check-in comments say who was the peer reviewer. "(peer: JDV)". The nice thing is that you make everybody responsible for enforcing the rules, and there are really no excuses if it gets "forgotten".

Now you can go as far and make your version control system reject check-ins that don't mention a peer reviewer, but you should not need to go that far.

To get started, you can feed some formatting tool with the indenting rules you agreed on and have it fix all files (batch mode, preferrably) over the weekend. Be sure to tell everyone to check-in that friday.... Jetbrains has good tools for java and C#.

Lastly, it helps if everybody uses an editor that makes correct indenting correctly.


15
[+2] [2010-02-16 21:09:29] codingguy3000

Find them and pinch their heads off.


16
[+2] [2010-02-16 22:19:32] anon

Are you in the states? I believe there, and in some other countries, you still have the death penalty. Even better if you are somewhere you can torture these offenders first.


Software engineers are only given a death sentence here if they write a program that shoots a gun; not if they write un-indented code for their missile aiming routine. - San Jacinto
17
[+2] [2010-02-17 00:50:17] Paul Nathan

Talk to their manager.

Managers deal with policies such as this, and they have enforcement power.


18
[+2] [2010-02-17 09:10:56] deleted

Use a brick to indent their thoughts. Or tell them their job depends on it. Whatever feels best.


19
[+1] [2010-02-17 09:35:11] Syed M Shaaf

Vicious:

I think you should start coding without any End of lines and no tabs. And make sure they debug your code in recent future. And not to forget add "_" and "$" to variables as well to make it more easier for them ;)

Perhaps they will get the hang of it soon ;)


20
[+1] [2010-02-17 01:22:34] Ganesh Shankar

See if you can get "Using good coding practice" tied into the performance review process at your workplace. Or maybe just give out a reward for well formatted code. It's amazing what a competition of some sorts can get you...


21
[+1] [2010-02-17 03:31:48] community_owned

First step: Back in my last job, there was a code beautifier that you could run and it'd auto-fix mostly everything style-related, except the most horrible things (having two public classes in one file comes to mind).

Second step: I'd expect you to have a source control system of some sort. Like it's been said (but perhaps not clearly enough), find a way to institute a server-side code policies job that verifies the code before checking it in.

If that's too expensive to implement, just make code reviews compulsory, and there's no check-in unless there's a code review approval. The problem I see with this is that's tiring for the reviewers to check for simple mistakes like a tab instead of a space indent, that a script could do almost instantly.


22
[+1] [2010-02-16 23:29:29] Alex Baranosky

Get a new job.

Soon.


23
[+1] [2010-02-16 21:43:21] fullchip

Python forces the programmer to follow indentation.

class file_op:
    def file_read(self, file):
        self.file_to_read = file
        self.rfile = self.file_to_read.readline()
        print self.rfile 

if len(sys.argv) == 1:
    r1 = file_op()
    r1.file_read(sys.stdin)
else:
    r1 = file_op()
    r1.file_read(open(sys.argv[1], 'r'))

unfortunately, Python syntax is flexible enough that it has zero value for enforcing readable indentation:

class file_op:
 def file_read ( self, 
file):
        self.file_to_read = file
        self.rfile = self.file_to_read.readline(
); print self.rfile 

if len(sys.argv) == 1:
 r1 = file_op()
 r1.file_read(
sys.
stdin)
else:
                r1 = file_op(
); r1.file_read(open(sys.argv[
1], 
'r'))

(6) The very existence of the question leads to the conclusion that the code is not being written in Python, Haskell or IBM Job Control Language. - Pete Kirkham
24
[0] [2010-02-16 20:20:09] Slauma

Tell them the little lie that the next version of their development environment will mark code not properly indented as ERROR and stop compiling.


Good luck when they call your bluff. Now you're in the same position you were before, and you've earned their distrust. - Tom
25
[0] [2010-02-16 19:47:51] Ritsaert Hornstra

Whatever kind of lay-out you choose, the main thing is readability, next readability and last readability. You can argue on the details but I think a small test might let them see differently:

take a small piece of code and ident it, print it, unident it, print it also and then ask two groups to see how fast they can see what it does. Good formatted code is much easier to read.

If all else fails: Make using a code formatter obligatory when checking in code and agree on how this code formatter is set up. I once was part of a team where they used this because of some real code formatting wars going on.


26
[0] [2010-02-16 20:12:44] Soraz

Integrate it into the build process. Preferrably in such a way, that their commits are discarded if they don't uphold the company standard for code.


By “discarded” you mean “silently discarded and removed from their sandboxes as well“, right? ;-) - Christopher Creutzig
27
[0] [2010-02-16 19:05:55] mythz

A 17" monitor with low resolution should force the issue :)

Seriously though, it improves readability. Your eyes can scan and understand properly indented code much faster than otherwise possible.


28
[0] [2010-02-16 23:20:29] Chris

Make build process that does code style checking. The build fails if the code isn't properly indented. Readability is the biggest reason. When the code is consistent and styles are followed there aren't any surprises when reading hundreds of lines of code everyday.

Productivity increased is a pleasant side effect because consistent styles make reading code more like reading a book than translating a foreign language.


29
[-1] [2010-02-16 20:14:31] Doug G

right-click is your friend


30