15

I have two friends that have completely different schools of thought on how to lay out their code.

The first says that code should be well-indented and use lots of spaces and to name variables judiciously in order to organize things in a way so that you can immediately understand the hierarchy and semantics of the code.

Here's a sample of what his code looks like:

var Stack = function () {

    var pair = function ( first ) {
        return function ( second ) {
            return function ( dispatcher ) {
                return dispatcher ( first ) ( second );
            };
        };
    };

    var getFirst = function ( pair ) {
        return pair ( function ( x ) {
            return function ( y ) {
                return x;
            };
        } );
    };

    var getSecond = function ( pair ) {
        return pair ( function ( x ) {
            return function ( y ) {
                return y;
            };
        } );
    };

    var emptyStack = function () {
        return function () {
            return null;
        }
    };

    var stack = emptyStack ();

    var self = {
        push: function ( item ) {
            stack = pair ( item ) ( stack ); 
            return self;
        },
        pop: function () {
            var top = getFirst ( stack );
            stack = getSecond ( stack ) || emptyStack ();
            return top;
        },
        top: function () {
            return getFirst ( stack );
        }
    };

    return self;
};

The second says that it's better to have your code written in a more compact way so that you can see a bigger part of the picture at once and be able to recognize more immediately how one part of the program will affect another.

Here's the same program written in his style:

var Stack=function(){
var pair=function(x){return function(y){return function(f){return f(x)(y)}}};
var fst=function(p){return p(function(x){return function(y){return x}})};
var snd=function(p){return p(function(x){return function(y){return y}})};
var empt=function(){return function(){return null}};var stk=empt();
var slf={push:function(val){stk=pair(val)(stk);return slf},
pop:function(){var top=fst(stk);stk=snd(stk)||empt();return top},
top:function(){return fst(stk)}};return slf}

I personally prefer writing code the first way, but I haven't really tried the second way much, so maybe I'm just not used to it.

I have noticed that when I look at the Javascript code of most professional websites, they usually use the second style, so there might be something to it.

Other than just subjective stylistics preferences, is there a reason to prefer one over the other?

11
  • 16
    I think the Javascript you see that looks like the second sample looks that way because it is automatically minimized or "minified", to reduce the amount of whitepace and strip out the comments. It makes it harder to read, but is done to reduce the amount of data being sent to the client (browser). en.wikipedia.org/wiki/Minification_(programming) May 23, 2013 at 14:59
  • 3
    It's a matter of taste, but personally I like the middle ground. I also think that most coding standards (if not all) don't fall into either extreme. All those spaces before and after brackets (style #1) seem totally unnecessary. Perhaps someone should just increase the font size in their IDE. Other than that, I'm actually fine with #1. May 23, 2013 at 15:03
  • 7
    Being able to see the bigger picture of something illegible is still not very useful IMHO.
    – JayPea
    May 23, 2013 at 15:06
  • 9
    #1 doesn't convey very much info at a glance. #2 has the potential to become an unreadable wall of text. A reasonable middle ground is probably preferable to either extreme. May 23, 2013 at 15:07
  • 2
    "bigger part of the picture" - ASCII art? May 23, 2013 at 15:13

7 Answers 7

17

You should use the first approach because it scales to larger programs.

The mentality of "I need to see how everything affects everything" is harmful to software development. You want functions/objects decoupled, so that you can change one thing without breaking another distant/unrelated function.

Even if you use a compact coding style, you will eventually have more code than can fit on the screen at once.

A better solution (from Clean Code by Robert Martin) is to list public "high level" functions first, and have each function stay at one level of detail.

1
  • 2
    "Even if you use a compact coding style, you will eventually have more code than can fit on the screen at once." - I'm picturing the OP's coworker trying to fit the whole of a larger codebase on the screen by using a small font, zooming out the text, and squinting until they're cross-eyed. May 23, 2013 at 20:26
2

Most IDE-s will allow to collapse the first sample into 8 (or even 1) small lines, so that you can see the big picture. The second sample on the contrary can't be made to look like the first one easily.

The first sample is easier to understand, especially for newbies. It reveals the hierarchy and the sequence of the actions performed. Besides IMO newbies would rather have difficulties in grasping the second sample at once, because it look rather "scary" and complicated.

So if you work in an environment of more or less experienced professionals, I'd prefer the second sample _ if you're used to that style, you can grasp the whole idea in a glance. But because in reality very few (if any) development environments consisting of experienced developers only, the first sample is better.

P.S. if you don't like to write all those spaces and new lines manually, you could have an automated tool for that.

2

I generally write indented code, similar to #1, but with fewer blank lines. Indents allow for the detecting issues with brackets easily. This, combined with each assignment on it's own line, keeps things easier to read. Tab completion allows the use of longer variable names without typing too much extra.

Yes, it is longer, but there is nothing wrong with writing long code. Just as I am using paragraphs in this answer to make reading easier, why not do the same in your code? Since the interpreter doesn't know the difference*, the only person benefiting is you.

Emacs has a VHDL plugin that I use on a daily basis which auto-beautifies code via a keyboard shortcut. This allows for more focus on coding instead of spending time on formatting.


*language dependant. Some languages, like python, use indents as part of the syntax, in which case the interpreter does know the difference.

1

I agree with what superM said. My two cents:

I prefer the first one (not in that extreme) because that way I can maintain the code much more easily. Even if I have to change my own code from 6 months ago, I won't understand the second style as fast as the first.

What you see in JavaScript was probably written in a more human way, and even with comments, but some semi-compiler made some mechanical changes (like reducing the name of a variable from usersFacebookID to a and deleting all comments). This reduces the amount of data sent to a user, and this is the main bottle-neck of web apps, so the site seems to load faster. (And the end user anyway doesn't care about the codes style).

1
  • 1
    I'm just going to note that in many cases where I code Javascript, there's a reason to close the entire thing in one set of braces for scoping. For that, I tend not to actually apply that particular level of tabbing; since it doesn't help understand the structure an enormous amount (unless you have multiple declarations in one file - which you shouldn't.)
    – Katana314
    May 23, 2013 at 17:29
1

If your IDE doesn't support parsing and folding for your language, then maybe a more concise form would be in order, but overall it will be harder to pick up errors. The information density is so high you'd easily step over some error. Besides that, the length of the lines would become quite long in cases where you have to make multiple calls in one function, which would necessitate scrolling to the side. (much more annoying then scrolling down, which is what most of our IDEs are designed to do) If you're using s scripting language that will be interpreted instead of compiled, then you'd want to use a minifier before you ship it. The use of a minifier is a common practice in web development firms when using JS for bandwidth reasons. In interpreted languages white space is noise. Compilers usually remove any excessive whitespace when they tokenize the source code, leaving only usefull information after processing. (either to byte code or machine language) Compilers only have to deal with the noise once. Interpreters have to deal with the noise every time. (although most have some kind of caching to alleviate the problem these days.)

In the end it depends on the platform you use to edit your source and the language/environment you intend to use your code in, but I'd vote for option 1.

1

I agree with Friend 1

From a compiler viewpoint, it doesn't matter... and option 2 will only save you a few bytes of file-size on your gigaByte hard-drive

From a human perspective, it doesn't matter to you which way you use today, as you know what you have written.

But when you come back to it in a day, week, month or year - or someone else comes back to it, Option 2 will be much less readable and much less understandable.

0

Don't do either extreme! I would rather write

var Stack=function(){
    var pair=function(x){return function(y){return function(f){return f(x)(y)}}};
    var fst=function(p){return p(function(x){return function(y){return x}})};
    var snd=function(p){return p(function(x){return function(y){return y}})};
    var empt=function(){return function(){return null}};
    var stk=empt();
    var r={
        push:function(val){stk=pair(val)(stk); return r},
        pop:function(){var top=fst(stk); stk=snd(stk)||empt(); return top},
        top:function(){return fst(stk)}
        };
    return r}

It's compact and readable.

1
  • 2
    without an explanation, this answer may become useless in case if someone else posts a differing opinion. For example, if someone posts a claim like "Don't stop midway, choose either of extremes!", how would this answer help reader to pick of these differing opinions? Consider editing it into a better shape
    – gnat
    May 23, 2013 at 15:55

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