Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Alternative code styles (swalladge.id.au)
230 points by _7ffc on Oct 15, 2018 | hide | past | favorite | 102 comments


Nowadays I couldn't care less about what style is used. As long as the code is consistent and there's an easy way to adhere (clang-format, black, prettier, etc.) I'm happy.


Put another way... if the proponent of a particular (serious) syntax style guide can't be bothered to automate it, then they are pissing in the wind.

I laugh when I see those 50-page English-language documents describing how some institution wants code to be formatted. Ain't nobody got time for that.


I worked at a place recently where someone (who left before me) argued seriously that automated syntax fixing shouldn't be brought into the millions of lines multi-project codebase with approximately a dozen developers with a 40% retention rate over any two year period because it would encourage bad habits by not properly punishing people for being bad.


There are some limits to what you can automate but stuff like spacing should definitely be enforced by a tool.


I feel like Prettier does a really good job with JavaScript.

What situations have you found where automated formatting doesn’t suffice or has these limits?


Ordering code.

Some tools order/deduplicate imports. Prettier does not. [1]

And no tool that I've seen orders fields/constructor/method, etc.

[1] https://github.com/prettier/prettier/issues/949


Interesting, yeah, that’s definitely missing. ESLint has rules for ordering, feels like it’d be a relatively simple addition to prettier.


In JavaScript, imports sometimes (too often, really) have side effects. I don't know if it makes sense for prettier to do that, at least by default.


I don't have a problem with anything that discourages imports with side effects. You can always ignore[0] any cases where this happens.

[0] https://prettier.io/docs/en/ignore.html


In my experience, side-effecting imports are fairly uncommon.

But in any cases, all formatters allow you to selectively disable it for certain liners.


Hopefully uncommon, anyways. Imports with side effects sounds like a nightmare to debug.


> it’d be a relatively simple addition to prettier.

It would be, but as you can see in the linked issue, it was closed for being a non-goal. So, it's not likely to change.

(Prettier generally keeps the AST identical; i.e. whitespace and parentheses changes only.)


eslint and prettier are not mutually exclusive


I didn’t mean to imply that. In fact we use eslint + prettier where I work.


I don't know if it supports JavaScript but Resharper does this for .Net


I think all three major Java IDEs do this as well.


Humans format with rules that take into account semantic information, symmetry, and aesthetics. They know that a function call that gives the entries of a matrix is formatted as a grid for a reason even when the auto-formatter could fit it on one line. They know that that arm of the match that would be formatted weird if it were on its own is actually formatted well because it exhibits that case's consistency with the other cases in the match. Probably the most important formatting decision they make is to, rather than format a long line, break it into intermediate results and store them in local variables given human-meaningful names.


Many programmers are still committed to manual formatting, or fixed width fonts would have been obsolete already.


Fixed width fonts let you quickly parse syntax. Syntax and semantics are equally important when reading code, whereas semantics are generally the only thing you need for understanding the written language.

That said, I haven't seriously tried programming using variable width fonts; maybe it's a well-kept secret to digesting code. Or maybe it's like Hemp Milk, there's a reason it hasn't caught on.


There is actually no evidence for that. Programmers in general seem to be faster with whatever they are used to. I personally have trouble parsing code in fixed width fonts versus proportional ones* because I’m used to the latter and the kerning of fixed width formatting annoys me. Keywords pop out easily with syntax highlighting in any case, making syntax pretty obvious.

* to be fair, I’d have trouble with a bad proportional font like Times New Roman, but I’m sure many would have trouble with Courier New on the other side, the specific font matters.


I don't know if variable width fonts are a help or a disaster but I've been using multiple fonts in a single editor window for quite a while and the productivity boost is huge. My choices are Operator Mono (to typeset keywords and math stuff) and Firecode (to typeset ligatures). You can find my custom Atom stylesheet here if you want to try.

PS: The idea is not mine but I can't remember where I read the instructions about this editor setup, so Google is your friend.

https://gist.githubusercontent.com/diegoperini/853d54c8873e7...


wait are you saying fixed width fonts are only useful for manual formatting? because I find they make it much easier to read code.


There is no evidence that fixed width fonts have any advantage. It seems to be a matter of just what you are used to.


Fixed with fonts work well when you are using the alt key to work with multiple lines of code at once. This is especially helpful in the middle ground where the lines of code are similar enough that one can easily use a pattern but the extent needed to be written with that pattern doesn't justify creating some tool to automate writing the code.


I strongly prefer coding in normal fonts instead of typewriter fonts. This is the primary reason that tabs are better than spaces. Working with a proportional width font in a space-indented file is always trying.


Fixed width fonts are used for programming because of cargo culting. I tried programming in serif fonts only after a HN comment suggested it (would never have thought of it myself) and it's fantastic. Very readable. They were right.

And you can still manually format code, serif or monospace.

Proportional or monospace font choice is orthogonal to formatting.

(Edited to be more specific)


I prefer a San serif myself.

Mono space allows you to do manual alignment, eg if you want ascii art in your code or non standard formatting. Doing this with a proportional font means other people can’t read your code without using the same font.


Sign of an experienced architect. Read: "I'm old and too tired to argue, just don't break it ok."


I'm 32 and I feel like I'm already at that stage sometimes. What will I be like when I'm 50?


I'm 70, push out production code every day (Horstmann style https://en.wikipedia.org/wiki/Indentation_style#Horstmann_st...), and I'm having the time of my life.


Horstmann style looks like my ideal, but there's very little tool support for it, from what I've seen. For instance, if I want to swap the first two lines of an "if" statement, I can't use "line-based" copy/paste. Do you do things manually, or does your editor support it fairly well?

EDIT: looks like the tool support is so bad, Horstmann himself pretty much gave up: http://horstmann.com/unblog/2010-06-28/braces.html


Better.


Consistency is key. Follow the style that the code already uses. For new apps, I make sure the team has the same style template and use the editor to format the page.

At the end of the day, it is important that the code looks like it was written by one consistent person and not 20 random different people.


Unless the code you're working on combines different styles not only in the same project bet even in the same file.


pet peeve #1 right here.

I really don't like the mandatory use of eslint (used as style enforcement), prettier, etc. When used as a bat to hit developers over the head, all this tells me is that the organization has too many anti-social developers that can't check their ego at the door.

Often someone will recommend a tool or technology in place of simple social common sense. If a developer can't follow the existing code style, they should be shunned. It's their problem. It's not a problem to solve with a fancy tool. You solve this particular problem by telling that person that they are an asshole. Using technology to solve social problems just exacerbates the problem.

All of that leads to a situation where we can't have nice things. You go into a codebase and see hundreds of exceptions to turn off eslint or whatever. Instead of just working around one-off style exceptions with common sense (who really gives a damn if a line needs broken/indented a certain way for a specific function) you have to plead with the style cops to let you off each and every time.

Developers really hate each other. Small organizations or teams tend to be a bit better in my experience. There is more camaraderie. But I often feel like I'm in a group of mercenaries, each ready to stab you in the back.


Linters save so much formatting time, I don't really see what it has to do with ego.

I certainly could go through and make sure all the spacing is exactly right, the functions/properties are in the right place, and rest of the rules of the styleguide are followed. But it's much easier to do when you get a warning, squiggly, or can use an autoformatter to match the rules.

I would never intentionally violate a rule, but I might forget a rule or miss a violation. With linters this is not an issue, the machine will let you know.

Everyone can focus on the correctness and quality of code and let the machine worry about making sure everything is formatted correctly.

Clearly the project you describe, where linting is disabled every other line is bad. But I wouldn't blame the linter for that. I don't know what can be done if a team has such a commitment to their own style that they put in the extra work to disable the linter.

A linter is not a tool for punishing people who violate a style guide, it's an assistant for people who are trying to follow a style guide.


I don't think even you believes that. You're telling me you would be "happy" if every source file was one line?


Just replace "style" with "half reasonable style".


Lint to personally preferred style on checkout. Lint to project style on checkin. Not a problem.


Do you actually do this? From what I hear (and this makes sense from what I know about formatting/parsing algorithms) it's a huge pain, and not implemented for many languages.


I have my IDE do all the formatting every time I close something and rarely personally intervene.


That's easyish: it's a one-way street. The OP imagined something where everyone checks out code in whatever state it's in, applies their own system, then transforms it back, with no artifacts. That's hard.


Same here, with a twist: the test suite does: global reformat (uncrustify or astyle, depending on the team), build, run the actual tests. As people almost always run the test suite before checking code in, all the project stays properly formatted.

My experience is: each time a team started doing this, all coding-style related discussions vanished, and it became a non-issue. It turns out it's a lot easier to accept a coding style you're not the one doing the actual formatting (this is why, BTW, I think stylechecking hooks alone are a bad idea).


Surprised nobody talks about the kdb codding style: https://github.com/KxSystems/kdb/blob/master/c/c/k.h


That's Whitney's style. My preferred example is http://www.kparc.com/b/b.c

It looks obfuscated, but in fact it is just a lot of information. Many people would claim dividing it in 10 files with longer function names and less tricks would make it easier to understand, but after spending a long time studying (and partly rewriting) this code, I actually find the terse version better.


The problem with satire is that no matter how far over the line you think you've gone, someone will always wonder whether you really meant that.


> after spending a long time studying (and partly rewriting) this code, I actually find the terse version better.

I'm sure Mr. Goldberg understood his machines just fine, too.


I've tried Whitney's style and got some good takeaways from it. I don't need that level of density, but it made me realize that when the code is already doing something very abstracted from business logic, there is no sense in trying to name the variables with more than one or two letters. (x0 and x1, appearing in geometric functions, are favorites of mine.)

I also started using "result" after seeing it in Pascal code and have quite liked it for many years, but I just had the epiphany that "ans" (answer, as seen on several graphing calculator lines) would be a little more dense.

Basically, it was well worth it to try these radical styles out. They did a lot to smooth my everyday coding.



:O that is ... interesting. Sure that's not an entry for the ioccc? ;)


Nope :) This is being used everyday in production by most financial institutions. https://code.kx.com/wiki/Cookbook/InterfacingWithC

I've been told that the guy who wrote this believe that the brain only has a limited buffer to compute source code. So he is trying to use the shortest code possible everywhere.


I think looking at this code has already caused a buffer overrun in my brain ;)


"This is being used everyday in production by most financial institutions" — you can't be serious...


KDB developers make BIG money. It's an APL-like language and used to analyze financial time-series.


I'm not surprised, it's an APL family language.


It looks more like the guy that wrote this wanted good job security and pay, and ended up making and industry with good job security and pay.


that's just for writing c interfaces to kdb.

As someone who writes q all day, it's typical to see functions written in one line and no white spaces. The mantra is, if it takes you more than 1 line you're probably doing it wrong.


The only style there that is actually used by a person is the Bourne style. There are other styles that people develop for themselves, for example there was some Haskell program posted to a mailing list with a warning about personal style. This defines:

  (.) :: a -> (a -> b) -> b
  x.f = f x
And then the author can write e.g.

  x.length
Instead of

  length x
I think this is really quite a natural operator (and other languages support it, eg in F# it is pronounced |> and closure has something like it with ->)


This operator is (&) in Haskell these days.


neat, I think D has language level support for this too


That's basically uniform function call syntax. D and Nim use it and a few others.


The best coding styles are the ones that allow to be translated back and forth to another style.

It doesn't matter which style you prefer. As long as a computer can pick it up and translate it into the project standard style and back to yours again. You can simply setup git filters and live in you own style world.


Using git filters is a great idea! I've heard of this for translating between unix and dos line endings in git, but hadn't thought about using it for entire styles. There are heaps of automatic code formatting tools becoming more popular these days too.


Code is meant to be read first and foremost by humans.

As such, code should be written for clarity and presentation. To communicate intent. Automated tools destroy this human/code connection. They reduce your coworkers to simple cogs in a machine, rather than authors and communicators.

I'm not a fan of this cold, brave new world.


How code is styled doesn't distract from the main purpose to communicate intent. Most often humans are the ones mindlessly layering on the meaningless formatting/style on top of syntax and its then becomes the pivotal point of code reviews, burying the essence of the code.

I applaud companies like Google and Hashicorp for forcing formatting as compilation errors. As it lets you get on with the real tasks ahead.


That Fibonacci based indentation might not be a bad idea after all. Especially when doing callback-style javascript.


Or as a cautionary measure against heavily nested code.


, but you repeat yourselves.


I think something simpler like (n)(n+1)/2 is better. This means that the difference between the n-th and (n+1)-th indentation level is n spaces (barring of by one errors I made).

We still get a curving indentation, and we are still warned against nesting, but the indentation doesn't explode exponentially.


there's also the "inverse fibonacci mode", where the indentations become smaller and smaller at each level

it feels like when your handwriting becomes more compressed as you are about to reach the right end of the paper


I'd prefer something like 3^n. Would really make you try to avoid needless nesting.


Make it 1.3063778838630806904686144926...^(3^n), where 1.306... is Mill's constant. Then all your indents will be to prime columns.


Why should I avoid needless nesting ? Is there any other reason besides the holy 80 character limit !? Nesting can for example be used to limit variable scope and make use of closures, or to avoid creating more code paths, or just make the code more readable. You can however often break some code down to named functions and it will be easier to read, with the added benefit of less nesting. But I don't see how avoiding nesting is a good rule by it's own.


You've given some good examples of nesting which don't introduce branches, but most nesting does and therefore, nesting is an approximation for the cyclomatic complexity of a piece of code. Reducing this complexity helps with testability and (moreso) with the ability of humans to understand the code https://en.wikipedia.org/wiki/Cyclomatic_complexity

Agree with you that reducing nesting is not in and of itself beneficial.


Cyclomatic complexity seems like a great example of Goodhart's Law [1]. I absolutely agree that on the whole, code with fewer paths tends to be easier to read. However, taking deeply nested code and arbitrarily pulling chunks of it out into functions which only have a single caller and don't really abstract anything that's ever going to be terribly meaningful on its own seldom makes it better in my experience -- and can force a lot of skipping around if you're actually trying to understand what the system as a whole is trying to do.

[1] https://en.wikipedia.org/wiki/Goodhart%27s_law


If you punish nesting a smart developer might use imaginable horror (with the same or worse complexity) to keep the code flattened. Nesting makes the complexity apparent.


> Why should I avoid needless nesting ?

Because it is, by definition, needless. If there is a good reason for doing so, it is no longer needless.


Highly nested code is hard to understand.


I think it would help with clarity - too much nesting in a function can mean it's doing too much and might need splitting into several functions


One place where nesting makes things difficult is in error handling.

If at each potential error point you best one level, you quickly find yourself deeply nested.

I find the pattern of exiting early and having the “happy path” running to the end of the scope to make it much easier to comprehend a function (I’m sure there’s a term for this coding style but I can’t find the name of it at the moment).


I also find myself doing a similar thing in loops - 'continue'ing early instead of wrapping everything in conditionals.


Putting every single item in this on my list of "reasons to kill a motherfucker".

Seriously though, I find myself oddly attracted to the Python-braces style .. if only I could use it without running afoul of my own list.


make your syntax highlighter show braces and semicolons in a faint color – similar effect, better editability!


Or just use Python or other languages that require fewer braces/semicolons in the first place? We have so many options now, we don't have to deal with the tyranny of overly precisely punctuated languages if we don't want.


I followed the link to the OOPS source code from the comments: http://people.idsia.ch/~juergen/oopscode.c (originally from http://people.idsia.ch/~juergen/oops.html)

Aaaand… “we're achieving levels of nerdery that shouldn't be possible.”


> Poetry... quite eye-pleasing

I disagree with this comment. That style makes the code extremely hard to follow, as there's no proper indention to identify scope.


'eye-pleasing' is a subjective thing here and doesn't have much to do with functionality/readability (on the contrary, which is why you posted your comment). I think I understand what the OP means: that code sample, when looked at as an art form and not as code, indeed can be considered eye-pleasing by some because of the symmetry etc. For that aspect whether the code is readable has nothing to do with it.


Most of these examples are meant to be a joke, I’d assume.


Yes, the whole article is semi tongue-in-cheek. I tried to bring it back to reality by mentioning my appreciation for the creativity of people who designed the styles. :)


Probably I've taken this so serious since the article mentioned Bourne Shell code, which is a real project, and the Fibonacci indent style is actually nice.


Design rule for non-designers I like: Don't use center alignment (unless you know what you are doing)


This has to be satire. Most of these are terrible and I'm pretty sure the fibonacci indentation originated on /g/.


I love the Fibonacci indentation. Deeply nested code then looks like the gravity well in a black hole, drawing a direct and clear analogy to where readability and understanding are headed.


I'm totally into these suggestions but they couldn't possibly work in a team setting


Yes, satire and some examples of programmer creativity. I hope none of these styles are used in production code, but they are all definitely styles that someone has used for something. Even if just for fun.


Kevlin Henney gave a talk ( https://vimeo.com/97329157 ) that included an interesting idea for style:

Imagine every non-whitespace character in your code were replaced with garbage. Indent so that the reader could still understand the structure of your code.


Braceless Rust does look very nice. I wonder if a python style syntax is possible?



I appreciate the honesty of the readme


Wow! I've never heard of bournegol. That is really cool.


Sadly I have been asked to use it. Horror story time.

First job out of school, I joined a place with a lot of EE's writing VHDL tools.

So EE's--no offense--at that time viewed software as a solved problem if you did everything by a book (any book) and a spec and a waterfall.

So despite working in C, which was already plenty idiomatic with a fine K&R standard, they insisted that while(p-- = p--) was verboten and instead made a bunch of FOOL/LOOP, WHILE/ELIHW, IF/FI and other abhorrences to hide the idioms they didn't like (such as braces) and make it more like algol/pascal. This was all less important than actual CS principals.

Then to make matters worse, there was a SPEC, a binder full of PAPER pseudocode mostly in algolish, some hand written. But every piece of code needed to refer back to its spec. Of course those things got out of spec quickly so any new feature was always about triple work.

Yes, and it was uphill both ways.


oh god no stop.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: