views:

1948

answers:

30

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?

+18  A: 

Implement a code style 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 }
dassouki
on top of this, make code style policy conformance a job performance indicator which is measured periodically.
KP
+21  A: 

Take the most complex algorithm implementation you can find and remove the indenting. Show it to them (with comments removed) and let them manually explain the control flow to you.

Alexander Gessler
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
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
+7  A: 

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!) ;)

batbrat
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
+4  A: 

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..

Earlz
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
@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
A comment that tells me that the `getColor` method gets the color is best left out. Seriously. DRY applies to comments, too.
Christopher Creutzig
+4  A: 

Lead by example.

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

Jon Seigel
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
If that's happening, then it's a separate issue entirely, and should probably be escalated to a manager.
Jon Seigel
+89  A: 

Make them code in Python.

Eimantas
Make them code in Haskell.
trinithis
The only issue that I see is that some jerks refuse to consistently indent their brackets
dassouki
Make them code in Whitespace (http://compsoc.dur.ac.uk/whitespace/) ;)
David
+1 for whitespace! But technically speaking, whitespace isn't indented either, right?
Steve
They'll just write it all on one line then.
RCIX
So if whitespace is used to indent most programming languages, are alphanumeric characters used to indent Whitespace? :-)
Steve
My first idea involved knives, but Python is fine too.
Manos Dilaverakis
A: 

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.

mythz
+11  A: 

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.

wheaties
… 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).
David Dorward
+37  A: 

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 (n == 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 n 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 (n == 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.

Jason Orendorff
+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
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.
Ash
@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
A: 

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.

Ritsaert Hornstra
A: 

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.

Soraz
By “discarded” you mean “silently discarded and removed from their sandboxes as well“, right? ;-)
Christopher Creutzig
A: 

right-click is your friend

Doug G
A: 

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

Slauma
Good luck when they call your bluff. Now you're in the same position you were before, and you've earned their *distrust*.
Tom
+2  A: 

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.

jdv
+2  A: 

Find them and pinch their heads off.

codingguy3000
A: 

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'))
fullchip
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
+2  A: 

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.

anon
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
+2  A: 

Two words: Choke Slam.

jerry's kid
+10  A: 

Have them read this question and all the answers.

Elizabeth Buckwalter
@Scrub: You marked this as the answer. Does that mean it worked??
Robert Harvey
A: 

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.

Chris
+1  A: 

Get a new job.

Soon.

Alex Baranosky
+1  A: 

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.

Sara D Gore
+2  A: 

Talk to their manager.

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

Paul Nathan
+23  A: 

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.

Aaronaught
that is amazing. nicely done :)
Peter
+1  A: 

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...

Ganesh Shankar
A: 

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.

Sergio100
+2  A: 

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!
Jim Dennis
+1  A: 

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

deleted
+1  A: 

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 ;)

Shaaf
+8  A: 

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); } }
James B
If you are going to use <pre> you have to encode `<` and `>` to `<` and `>` I just indented it by four spaces to change it to Markdown format.
Brad Gilbert
what's the output ?
dassouki