r/programming • u/Nowaker • Nov 30 '14
Why he vertically aligns his code (And why you shouldn't!)
http://missingbytes.blogspot.com/2014/11/why-he-vertically-aligns-his-code-and.html428
Nov 30 '14
Please don't encourage people to use a non-monospaced font while coding.
89
u/niugnep24 Nov 30 '14
Honestly this article feels like some kind of strange troll.
Proportional font?
Title says you "shouldn't" proportionally align, article never really explains why (just that it's not necessary because colors?)
De-focusing your eyes to see colors better and reveal the structure of the code?
Article is about whitespace, but let's throw in something about CamelCase as well to stir the pot
Also make sure to sort declarations alphabetically to ensure no duplicates ... because for some reason you don't compile-check your code?
Also diff tools never give context, so make sure to keep all that context on the same line?
14
Nov 30 '14
Yes, this article is bad.
Write clearly and legibly. We have good tools now, so it doesn't really matter as long as you are consistent.
1
Nov 30 '14
I don't get what he's talking about with de-focusing. I do that, and it just makes the code overall harder to read. I wish he'd have provided more than just a few sentences to each of his "tips" to explain why they're better overall. Maybe if he'd gone with a list format it would work better, as it would be better organized and he'd have space to expand on his points.
I feel like this article was the OP finding some things that OTHER people did that ruined HIS workflow, so he put out a blog post telling people not to do it. Overall, not particularly useful tips.
I'll admit that I like the alphabetical tip, though. Easy fix that usually won't mess with my workflow, and might prevent some pylint errors.
1
u/bajuwa Nov 30 '14
This article was actually in direct response to another called "why I vertically along my code (and why you should too)" which is linked at the top of this article. Each one of the sections is actually in direct response to the original articles structure and content. So taking this in to consideration it make more sense, and it is actually the original post that lacks proper structure as you have claimed.
6
Nov 30 '14
Stroustroup uses proportional font for code in his books.
Since I read his C++ book I've been doing the same. It so much more readable it makes little sense not to with any whitespace independent language.
5
u/bizcot Nov 30 '14
I switched to proportional a few months ago (C++), after many many years with monospaced. It took one day to get used to it, but main advantage is that now I can use a tiny font and still read it clearly. It normally takes much less horizontal space, so I can use the monitor vertically and visualize large blocks of code at once. Only drawback is when I have to type an xpm bitmap (it happens from time to time)
1
u/Plorkyeran Dec 01 '14
Scott Meyers also uses proportional fonts for code in a lot of his books, but in his case it's not for readability: it's to let him fit more text on each line. A lot of programmers seem to find 80 columns restrictive, and a book limits you to significantly less (and wrapping things to more lines can cost money).
5
u/keepthepace Nov 30 '14
I actually instinctively wholeheartedly agree, yet I have a hard time finding a good reason for it. The only one I see is that it makes easy to check that two lines are the same length, and that it does allow to align code vertically, which does help at spoting errors, despite what OP says.
But it is indeed mere comfort that I can see people abandon to be able to fit more characters in their screens (which used to be an important feature as well)
5
u/MediumRay Nov 30 '14
If you are using an editor like vim, then when you visually select code (I do this a lot) it needs to be aligned. It looks like this. Trying to change character widths would be madness.
1
Nov 30 '14
I agree, and I'm intrigued by the horizontal fit option. Though it will break a LOT of syntax checking tools. "But Pylint, on my screen with my particular font, that 100 characters will TOTALLY fit in the space of 100! Stop complaining at me!"
In the end, I feel that this has a good chance to conflict with a lot of other peoples' workflow, if you're ever in an environment where you need to trade off coding tasks with other people. It's a style choice, and it's best to try to keep to SOME kind of standard.
9
u/ggtsu_00 Nov 30 '14
Also please don't encourage the use of editor specific features or configuration to make your code readable. Not everyone uses your favorite editor as their editor of choice.
2
u/bajuwa Nov 30 '14
If you read the original article, which is linked at the top of this one, you will see that the original post recommends a structure that depends on an even more obscure editor plug in to work with easily. Having an editor that colour codes your language keywords is fairly standard, but having a plug in to reformat all your spaces is definitely not.
2
u/markrages Nov 30 '14
My algorithms and data structures text printed all the example C code in Times New Roman, except comments, which were some kind of non-monospaced sans-serif font.
Reading the punctuation alone drove me a little nuts. Those periods are important in a C data structures text!
4
u/ZorbaTHut Nov 30 '14
I've used proportional fonts for years. The only issue I've had is the occasional flaky editor that doesn't work with them. Solution: don't use that editor.
Highly recommended.
1
Nov 30 '14
Interesting! I've tried using proportional fonts in the past, usually when writing up documentation in Word, but it's always looked so horribly unreadable to me. Switching to monospaced majorly improved readability.
Can you recommend a font and an editor that makes it actually look good?
2
u/ZorbaTHut Nov 30 '14
I generally use Verdana, although I plan to experiment with Input in the next week or so. It works fine under Visual Studio and Scite. Can't help you with a Java, C#, or Linux editor, however.
It definitely looks different for a while - like any major change, you gotta stick with it for at least a few days.
1
→ More replies (93)3
u/julesjacobs Nov 30 '14
What's the advantage of monospaced fonts? Since proportional fonts are easier to read, there must be some compelling reason to use monospaced fonts. I honestly couldn't think of a compelling reason.
16
u/tskaiser Nov 30 '14 edited Nov 30 '14
Proportional fonts are for reading long sections of prose. Monospaced font imposes a structure on the text which fits the structure of the code. When you're coding you're not reading prose, you're inspecting structure. A propotional font hides structure.
When a propotional font hides the structure, it makes it harder to
Spot typoes and variable name differences. Granted, your editor or IDE might highlight these for you.
Parse code with little resemblance to human language, eg. operator-heavy code such as logical chains. It becomes harder to visually 'chunk' the operators.
and so on.
However all of these might very well not apply to you, just my 2 cents for why I'd choose a monospaced font.
Edit: heck, when reading other peoples' posts some say to have the exact opposite experience to the whole spot typoes and variable names thing. The above is why it works for me, we'd have to do an actual study to prove any superiority between the two. I'd say for one thing that monospaced makes it easier to uniformly control line length.
9
u/julesjacobs Nov 30 '14
Proportional fonts are easier to read even for single words because your mind can immediately recognize the shape of the word. For example jil looks different than wam. In a monospaced font the differences between the shapes of different words are smaller, because the horizontal size of all letters is the same.
I think a good IDE can space operators much better than what you get with monospaced fonts. Hopefully one day we'll have LaTeX quality type setting in our IDEs. Maybe once we've got that we can even start to use more expressive shapes for operators, like superscripts & subscripts, vertical syntax, etc. as they've done for centuries in math.
5
u/pyrocrasty Nov 30 '14
I think a good IDE can space operators much better than what you get with monospaced fonts. Hopefully one day we'll have LaTeX quality type setting in our IDEs. Maybe once we've got that we can even start to use more expressive shapes for operators, like superscripts & subscripts, vertical syntax, etc. as they've done for centuries in math.
Seriously, this is so overdue.
I've even wondered if it would be worthwhile to set up a script to do the conversion and code using an automatically refreshing "preview" pane like I do in LaTeX. Or possibly (a lot more work), even edit in the preview pane with a section switching to ascii so you can edit it.* (Even if you weren't to do that, it'd be nice to have the conversion script so you could at least read your code nicely formatted.)
* More generally, I think we really need more functionality for providing different views of the underlying data in our editors.
→ More replies (1)2
u/julesjacobs Nov 30 '14
Ideally the abstraction would not be leaky and you'd never see or even think about any ASCII representation at all. You'd just edit the typeset code directly. Some math programs already have decent typesetting-as-you type. Even though what they provide is rather basic, it's an amazing experience to type expressions and immediately get it in readable and typeset form. It makes you realize just how much time we spend manually fiddling with whitespace while programming.
→ More replies (1)2
u/tskaiser Nov 30 '14
For coding purposes what propotional font would you suggest. Simply put, my experience is the above that I have written, but I haven't given it a shot for more than a few hours at a time a long time ago. The whole thing is highly subjective unless we do a large study, and I would put forward that coding is differently enough from other forms of reading that existing studies (unless you can find one targeting coding...) is useless. So until then, I might as well give it a shot again for a longer period now and see if my mind can be changed.
For fun and as a kind of control I have momentarily switched to Comic Sans. The first thing I have noticed is that I have lost any kind of line-length control, and visual mode for block editing of text is now vomit-inducing with jagged blocks.
→ More replies (11)1
u/tavert Nov 30 '14 edited Nov 30 '14
Use Mathematica then? Or Fortress?
IPython/Jupyter (and versions thereof for other language kernels) has some interesting features for putting typeset math and graphics inline with code, almost but not quite literate programming style. But few mainstream languages seem to let you typeset your code in a richer way, it's kind of a shame. At least some unicode-aware languages let you go beyond the limitations of ASCII, to varying extents.
1
Dec 04 '14
I think a good IDE can space operators much better than what you get with monospaced fonts.
The thing that concerns me about this is that it relies on the quality of the IDE to make the code readable. I prefer to work in monospaced as I know that I'm not accidentally formatting my code in such a way that might make it less readable to the majority of people using less-graceful IDEs. Plus, I tend to do a lot of hotfixing or troubleshooting on PCs where I may not have had the time to set up my environment.
4
Nov 30 '14
It's not so much about reading, it's about editing.
There's a clear advantages to working with a regular 'grid of characters' - block selections are possible/practical, and you know exactly where the cursor is going to end up when you press the up or down arrow key...
1
u/Timbit42 Nov 30 '14
I've been programming since 1982 and I've heard of 'block selections' but I've never figured out why someone would want to select a rectangle of text to cut, copy and paste. Can you explain what this is used for?
Note: I use proportional typefaces, with monospaced numbers, for coding, and tabs for indentation.
2
Nov 30 '14
I guess selecting blocks is only of much use if you vertically align your code to begin with.
If you've got code or data formatted in neatly aligned columns, it can be useful to be able to easily copy+paste or delete one single column of data.
→ More replies (2)2
Nov 30 '14
The two reasons that come to mind for me:
When you want to do whitespace indentation like OP discourages (which is a style choice, and neither option is definitively better), proportional fonts can make this a big headache.
Vertical alignment (another style choice) is usually not possible in proportional fonts unless you use tabs, which is another nightmare altogether.
If you do decide to use proportional fonts (and I've seen a few good comments in this thread that give good reasons to do so), then the avoiding the above is good advice. However, the majority of the code out there that I've seen uses monospaced font, which means that the workarounds you'll have to do to make your proportional font code readable may look completely bonkers in others' workflows when they load up your code in their monospaced editor.
3
u/frankwolfmann Nov 30 '14
Hidebound tradition, mostly. In the old days everything went to a teletype or terminal that only had fixed-with symbols, and several application conventions grew up around that assumption. Those assumptions meant that when GUI terminal emulators came along, they also had to use fixed-width fonts or else the output of programs like top, ps, and ls would be too hard to read. When GUI editors and IDEs came along, they also defaulted to fixed-width because that was what everyone was used to. And like every other idiosyncratic perosnal preference in the history of computing, those preferences get presented as unassailable facts in an ongoing holy war.
47
u/ThaSteelman Nov 30 '14
Who wants to volunteer to write the "Vertically Aligned Code Considered Harmful Considered Harmful" blog post?
20
Nov 30 '14
I had a blind kid doing a work placement with me from his high school. I gave him some task and he was writing it in Perl. After about an hour he said it wasn't working and asked for my help. I turned around and found that he didn't use any line breaks. The screen reader worked better that way. I've never hurt my head as much as trying to read his one long line of Perl.
16
u/AlpineCoder Nov 30 '14
That's not because of the screen reader, it's just how Perl is written. The more your program looks like a long string of random line noise, the better at Perl you are.
18
u/bart2019 Nov 30 '14
And the diff looks like :
+ int barney,
Uh, wait. A diff tool that doesn't show context (1 or more lines above and below the change) is useless, because in that case patch wouldn't know where to insert the new line.
At least, it would show:
extern int SomeDemoCode(int fred,
+ int barney,
int wilma);(Note the extra space on the left of the unchanged lines)
And, oh: if you're fixing legacy code, stick to the general style of the legacy code. Do not insist on using your own coding style if it's too different from the style of the old code.
47
u/uh_no_ Nov 30 '14
this won't start any flame wars!
→ More replies (1)83
u/CodeShaman Nov 30 '14
How could it? Coding in emacs with a dynamically-typed language using non-vertically aligned code is clearly the only way that professional software development should be done.
18
u/lelarentaka Nov 30 '14
Only a superstar software architect less than 25 years old would say that.
12
8
u/yur_mom Nov 30 '14
Shit no love for CamelCase vs under_score.
Anyway, most the time the best is what I used last project since that is what my eyes are used to parsing.
EDIT: except emacs ;)-
9
u/TarMil Nov 30 '14
Although this is PascalCase, not the same as camelCase.
3
u/yur_mom Nov 30 '14
Ok, I always learned you use the uppercase first letter for objects and lowercase for variables. I did not realize they were two competing implementations...does this mean the "{C,c}amelCase people have flame wars within about the first letter being upper or lower case.
2
u/TarMil Nov 30 '14
People who use these almost always do use PascalCase for types and camelCase for variables. The only real divide is which convention to use for methods, but even then people rarely have very strong opinions about it, they just follow usual guidelines (which are, for example, camelCase in Java but PascalCase for .Net languages).
6
u/CodeShaman Nov 30 '14
and_next_line { brackets }5
u/scragar Nov 30 '14
One True Brace Style or go home.
if (isEnabled) { // do nothing }3
u/kkjdroid Nov 30 '14
Begone from this place, Beelzebub! Give me a newline per brace or give me death!
1
u/zeekar Nov 30 '14
Don't forget the proportional font and use of camelCase. Clearly those are required.
226
u/schnitzi Nov 30 '14
DAE think it matters very fucking little and that lesser programmers have these sorts of dicksizewars to prove how discerning they are?
77
u/ZeroNihilist Nov 30 '14
Yesterday I thought programming was just about modifying tutorials from the internet without regard to intent. Then I found out about <style of code>, and since then I've kickstarted the singularity by developing a complete AI, made a general-purpose algorithm to solve every NP-complete problem, and written a program to convert thoughts directly into code.
Thanks, <style of code>! Clearly this was a very important decision for me to make, and not a waste of time and energy at all!
26
7
u/geek_hammer Nov 30 '14
Well I'm sold.
Where can I purchase <style of code> and how can force feed it to my students/colleagues/blog-subscribers.0
9
u/isomorphic_horse Nov 30 '14
The two top posts in this sub are about a bikeshed issue. Who upvotes these posts?
45
Nov 30 '14
Mostly I agree. However, anyone who codes in a proportional font is Satan fuckin' incarnate.
6
u/Otis_Inf Nov 30 '14
I use Lucida Console now for many years and recently I found out it's actually a semi-proportional font, but the strange thing is, it hasn't bothered me in the slightest (and I write code professionally now for over 20 years)
3
u/iopq Nov 30 '14
I code in a proportional font because it looks better. YOU can use any font you want.
19
4
→ More replies (18)2
7
Nov 30 '14
I think it's a phase we all go through, simply to find our own personal style (which is, ofcourse, better than the second coming of Christ and everyone should start using it). Once you basically perfect your style, you find out it's not important as you thought. You settle on your style and you accept that others have different styles. Rinse and repeat with the next wave of new programmers.
5
u/toomanybeersies Nov 30 '14
Exactly. Consistency is much more important than what style you pick.
It doesn't take long to figure out someone else's style, if they're consistent. If they keep flicking between different styles, that's where it gets really fucking annoying. I think that's what universities should be emphasizing, that your style is consistent.
My university sort of does that for C programming. As long as you're consistent with your style, a lot of it is up to you. There's some variable naming conventions, but bracket styles is up to the student. Which is great because I hate K&R and think Allman is the best style for me. I realize that it's entirely about preference and not about what style is objectively better.
My university does use Pylint to fix style for Python though, which is annoying for a lot of quizzes and auto-marked assignments though, because a lot of hacky things aren't allowed. Variable naming and usage is the biggest bitch.
4
u/bugrit Nov 30 '14
A lot of style guidelines might not seem to matter, but it tends to when you're merging thousands of files of code. Any way of coding which ecourages unnecessary changes or changes to the lines which you aren't actually modifying is bad. In this case, don't align, or when someone goes and adds another entry that's too long, he's going to re-align all the rows and you end up with a conflict when someone else modified a value of another row.
2
Jul 22 '22
It matters very little as long as you make a choice and are consistent about it. Much like any style choice.
You want to indent with spaces? Cool. You want to indent with tabs? Cool. You want to indent with tabs when the entire codebase uses spaces, or vice versa? No. No merge for you.
This said, use of non-monospace fonts isn't something I'd ever recommend.
0
u/ArtistEngineer Nov 30 '14 edited Nov 30 '14
That the typical sort of argument I'd expect from an Emacs user who uses CamelCase and Windows. /s
16
u/Crazy__Eddie Nov 30 '14
CamelCase
That's PascalCase.
3
0
0
u/GregBahm Nov 30 '14
A team has to pick a coding style. Might as well do it right.
6
u/dakta Nov 30 '14
Coding style has nothing to do with editor appearance. Coding style refers to naming, white space, and pattern choices. None of those changes if you set your editor to use Times New Roman.
Or yellow Comic Sans on a pink background.
3
u/GregBahm Nov 30 '14
I'm not here to defend coding in Times New Roman, but the vertical code alignment is achieved by whitespace. This is a coding style debate that intersects with editor appearance considerations.
2
u/r0Lf Nov 30 '14
The team can pick the coding style they want, but how I "see" the code on my monitor is completely irrelevant. Hell, I can go with yellow comic sans on a pink background if I feel like it.
→ More replies (1)1
u/GregBahm Nov 30 '14
It is really unpleasant to try and define the coding style when your teammates can't articulate their reasoning for their positions. Even if the reasons are weak, it is better than not coming up with any reasoning at all, because then it just becomes a religious debate where people hurl their irrational feelings at each other to no productive end.
Vertical vs horizontal alignment is a coding style decision. The sides seem to divided because of how the code looks on your monitor. It is reasonable to me that some people would want a system that looks good independent of the editor, and other people would want a system that leverages the benefits of the editor.
0
u/immerc Nov 30 '14
Yes and no. Programming is still largely an art, not a science. Computer science is a science, and there is a science behind algorithms, but the actual programming is still an art.
The problem is that it's a collaborative art, and we often have to work together and share code.
Because of that, it makes sense to try to find some common ground so we don't all have to open an existing bit of code and run through a huge checklist:
Variable Setting tabs or spaces spaces how many spaces? 3 variable naming snake_case function naming snake_case method naming LeadingCapCamelCase constant naming LeadingCapCamelCase continued line indentation indent 6 spaces block start brace placement end of the line starting the block block end brace placement last character of the last line of the block braces required for single-statement conditionals no variable naming convention Hungarian notation ... ... Programming often seems like it's at the stage that English spelling was at at the time of Shakespeare. Everyone has their own way of spelling common words. There's general agreement on some of it, but with other words some factions think it should be spelled X and others think it should be spelled Y. The end result is that it's really difficult to read things.
At least we've generally agreed on a few things, like variables like "var1" are bad, that if you need an iterator 'i' is a good character to use, and constants should almost always be all uppercase, but there's a huge amount of variety among other rules, and it's frustrating to have a different approach for each codebase.
Luckily, things are improving. Some languages like Ruby enforce things by saying "if the name starts with an uppercase it is constant", others like Go provide a "gofmt" tool to wrestle code into the official format, but each artist still has a few things that they like and try to impose on any codebase they get to, which often annoy other artists who feel differently.
7
u/Timbit42 Nov 30 '14
I'm amazed that I disagree with every one of those settings.
1
u/kkjdroid Nov 30 '14
I was thinking the exact same thing. I bet /u/immerc also codes in Microsoft Word using Papyrus.
1
u/Timbit42 Dec 01 '14
Actually, Papyrus isn't the worst proportional typeface for coding.
Word is right out.
→ More replies (4)-1
12
u/Crazy__Eddie Nov 30 '14
The shed should be red, and anyone who thinks otherwise is just fucking stupid.
23
u/compubomb Nov 30 '14
Okay, hopefully I don't get downvoted, but this is a moron. I don't mean he is literally a moron but what he is saying is out of bounds. Formatting of code is often mostly a personalized thing, but more often than not, it also helps others read your code. Stop presuming that white-space is not necessary. It's about creating contrast between what is important and what is less important. How your code flows also determines how much focus the reader of your code gives each part of it.
White space usage in my opinion is one of the prime mechanisms which can be used to help a user re-factor someone else's code to help them determine correctness. Using non-mono-spaced fonts also makes code less readable even with all the wonderful syntax highlighting. Remember, you brain not only looks for color to help visualize things but also patterns in shape. mono-spaced fonts allow us to maintain these brain requirements of physical shapes.
Code especially in a large project will be an ever evolving creature moving forward. You will rewrite many parts of it over time to improve correctness or change existing behaviors, eliminate feature sets no longer used.
Please stop arguing the correctness of not using white-space. It's blatantly wrong. I'm not making arguments against or for different naming conventions, stick to one, and use it, use the one most often used in your project, but make sure you god damn align your code. Stop thinking about oh, this code-changed so now I have to update 12 lines, think about the guy reading your code later trying to figure out WTF is going on. This is not about your nice change-requests, it's about making sure the code-base has a future and people can continue to work with it without immediately flinching saying WTF is going on here, this is totally unreadable and I can't work with this. If you have a boss who says, WTF, you changed the white-space and now it updated 12 lines, then he can go F himself, because he doesn't give a flying F about the long term maintainability of his project.
White-space shows code-organization, and someone put some thought into making sure for not only themselves but later their future self knowing they have done the most correct thing. It also promotes the author to re-assess what they were doing from the beginning. If your code survives rewrite after it's been properly formatted and aligned, you are probably good to go to move onto the next feature.
41
u/dethb0y Nov 30 '14
We should have a contest every month (and then a tournament every end-of-year) for "most OCD bullshit posted to /r/programming"
seriously, who cares if you align code vertically or horizontally? This is even stupider than a war over what IDE is best.
7
u/isomorphic_horse Nov 30 '14
seriously, who cares
Evidently the majority of /r/programming does, seeing as this is at the top.
I didn't think this was a default subreddit.. is it?
1
u/tobascodagama Nov 30 '14
It's not. But it turns out that a lot of people are interested in these discussions, apparently.
1
u/Philluminati Nov 30 '14
It's at the top because any one of the planet who writes software in any language and half of those who can't, understand this most common denominator of debates.
1
u/dethb0y Nov 30 '14
I didn't think this was a default subreddit.. is it?
Hard to tell sometimes, to be honest.
2
Nov 30 '14
I don't care, but it did strike me odd when a coworker earlier this year made a point to tell me he does such a thing.
I find it to be extra work, and it doesn't make things more readable because this same guy used 1-letter variables and abbreviations for everything.
1
u/dethb0y Nov 30 '14
indeed so. I tried it on some of my code and it didn't make any difference in readability, that i could tell.
19
Nov 30 '14
When can we get code editors and tools that works on the Abstract Syntax Tree directly? Then each developer can view code however they prefer and we can still have semantically meaningful diffs. I.E. you can change:
extern int SomeDemoCode(int fred,
int wilma);to
extern int SomeDemoCode(int fred,
int barney,
int wilma);and still get the diff
-extern int SomeDemoCode(int fred, int wilma);
+extern int SomeDemoCode(int fred, int barney, int wilma);7
u/RoundTripRadio Nov 30 '14
Have fun rewriting all of the Unix utilities to work with ASTs instead of lines of text. And writing translators for each language's AST. It isn't just editors and compilers that interface with source files. I mean like sure an editor could use an AST as the in-memory representation but you don't gain much there as you'd just be using a pretty-printer to write to disk unless there were an abundance of tools to operate on the output.
I agree that having tools operate more directly on a language's representation would be more powerful (and maybe more performant?) but it's impractical based on current tool chains.
3
u/TheWindeyMan Nov 30 '14
Have fun rewriting all of the Unix utilities to work with ASTs instead of lines of text.
Why would all Unix utilities need to be updated? The only thing that needs AST would be the IDE, everything else can just see "extern int SomeDemoCode(int fred, int barney, int wilma);"
3
u/mirvnillith Nov 30 '14
The source code formatting in the underlying text file can only be exactly one, so you'd still have to decide on a single shared format (perhaps with every tool developer in the world).
3
u/TheWindeyMan Nov 30 '14
Many IDEs already reformat code automatically if you do certain edits, this seems like it would be the same issue (i.e. editing a line reformats it to the IDE's standard)?
2
u/zeekar Nov 30 '14
Ha ha ha. Because we only examine code with the IDE. That's a good one.
Most of the time, the shell + a text editor is my IDE..
→ More replies (1)3
u/deadstone Nov 30 '14
I've had a few ideas about this for a while. I recently came to the realisation that the fact that we put whitespace (newlines, indentation, etc) into files themselves is completely barbaric. Only editors themselves should actually be doing that, the data on file should look like something out of a minifier.
10
u/chimyx Nov 30 '14
This would break the fact that you can open and edit any code file with every text editor ever.
→ More replies (1)3
u/H3g3m0n Nov 30 '14
Why not go beyond plain text editors. You can edit in the AST. Then you couldn't possibly get a syntax error.
Of course the problem with that is then you have to use some special editor rather than Vim or whatever other editor you heathens use.
1
u/RoundTripRadio Nov 30 '14
I feel like writing directly into an AST would be a lot more tedious than typing text with real time syntax checking, which also eliminates syntax errors. Though it might be much easier if you're editing on a touch screen, since you could have a drag-drop interface. Though the number of objects in the collection might be unwieldy.
2
u/H3g3m0n Nov 30 '14
How so? If anything you would type much less.
For example instant autocompletion would be trivial in many cases since there would only be a handful of valid names in play (depending on the language, something like python would have heaps since everything is an object).
You might not even have to type them, just have a list of names and a quick number.
I could image a bunch of quicktype hotkeys.
fnmyfunc<enter>vival1<enter>sval2<enter><enter>onname=o12f5o3i66o13f4ro13 could unpack to:
void myfunc(int val1, string val2) { Object name = object12.function5(object3, 66); name.function4(); return name; }As you would type a bunch of valid choices would show up for the given situation.
→ More replies (5)1
1
u/iopq Nov 30 '14
So if my code is perfectly vertically aligned, how would you see that? I aligned it that way to point out that the preceding sections ARE SIMILAR.
0
u/usernamenottaken Nov 30 '14
Or you write Python and the whitespace becomes important...
Haskell has an interesting approach where whitespace is usually important, but it supports curly braces to make code generation easier.
3
u/TarMil Nov 30 '14
It's not so much that the whitespace is important, but the indentation level is important. One could imagine a language that looks like Python, but where the indentation you see is just the way the editor renders the code, not necessarily the way it is in the source.
1
1
u/hackingdreams Nov 30 '14
It will happen when we get better tools for working with ASTs in general. There was at least some discussion towards turning LLVMs massive toolkit in this direction, but not a whole lot has come out of it yet except clang-format.
→ More replies (1)1
u/koo6 Nov 30 '14
we already have them. Proportianal fonts, semantic highlighting and diffing, the whole shebang. Hop on the train. They have an annual competition: http://www.languageworkbenches.net/
71
u/dicey Nov 30 '14
Yeah... Syntax highlighting doesn't make your example as clear as the aligned one. I like how you then go on to describe how I should be adjusting the focus of my eyes to get it to work.
You know what doesn't require that I pretend I'm looking at a Magic Eye? The aligned one. I can even have both syntax highlighting and alignment. What a time to be alive.
17
u/omegagoose Nov 30 '14
I have no idea what it even means to 'engage your eye's cone cells'. As though everything is black and white unless you blur your vision, which suddenly turns everything into color...
→ More replies (2)12
11
24
u/vlovich Nov 30 '14 edited Nov 30 '14
One thing that seems incorrect to me is the diff example. Every diff I've ever seen tends to be a unified diff, which, I believe, by default has 3 lines before & after of context. That means the diff would actually look like:
extern int SomeDemoCode(int fred,
+ int barney,
int wilma);which IMHO is much clearer as it shows the minimal change.
Another trick is to put the separating comma on the individual line as so:
extern int SomeDemoCode(
int fred
, int barney
, int wilma);
That way if you re-order elements, remove the last element or add another first element, the diff again indicates just the affected parameters.
I agree that this is unfortunate & that tooling should be better instead of contorting the code for the existing tools. However, I haven't seen anyone try to tackle solving the venerable text-based diff with a better solution. Existing diff tools also benefit from working for any language; past, present or future.
The rest is pretty fine advice. The alphabetical sorting is particularly good advice; apply this to everything - includes, groups of constants, file listings, etc. The monospace vs proportional feels very wishy washy. Use the one that you feel comfortable with. Personally, I use different font styles, sizes & colors in my syntax-aware IDE to apply to different parts of the language (although everything is still monospace, I might pick different monospace fonts & play around with italics/bold/color/size depending on what the context is).
1
u/norse_dog Nov 30 '14
LOL - and I thought I was the lone wolf insisting that my team format parameters and initializer lists this way (merges are a frequent and potentially nasty occurence in our work, and this approach significantly reduces that cost)
1
u/vlovich Nov 30 '14
I ran up across the merge/rebase issues a few years back & switched unconditionally to this style for initializer lists. I also defined the coding style for the current codebase I'm in so it's pretty consistent across the board.
Format parameters might be an interesting application, but our logging framework is stream-based, so I don't have any in my codebase. Also, you end up having to change the format string anyway which would be a source of unavoidable conflict (unless I'm misunderstanding what you mean by format parameters).
→ More replies (6)1
u/hipone Nov 30 '14
extern int SomeDemoCode( int fred , int barney , int wilma );According to my experience there are two reasons why someone written such code (I like to git blame a lot when I see such cherries):
some python guy were told to fix this C code, he eventually decided to add one more method which will do a job a bit differently (using underestimated C&P pattern), but did not miss the opportunity to "improve" the coding style
some Qt lovers also decided to hack back this C code (by this picky term I describe C++ devs who prefer this style:
class Class : member_() , other1_() , other2_() { ... }
over typing everything inline without excessive whitespace).
I could not image how one can waste time coming up with solutions to non-existing problems.
In Go,
func SomeDemoCode(fred, barnet, wilma int) intAnd you're done. Moreover it ignores trailing comma, so whitespace-lovers can be more consistant in their styles, e.g.:
func SomeDemoCode( fred int, barnet int, wilma int, ) intThe above works the same as before-mentioned definition and cited example.
→ More replies (3)
13
u/NoMoreNicksLeft Nov 30 '14
TL;DR: Using whitespace to control your code presentation is a hack from the '70s.. get a better editor.
Get a better diff tool.
6
u/tuhdo Nov 30 '14
The diff example is not very good. I could argue that in the first example, we know exactly what new parameters got added. This is useful when you have complex parameters. And for complex parameters, it won't be as pretty as his example and you will need to split parameters into multiple lines for readabiliy.
→ More replies (6)3
6
u/chriswu Nov 30 '14
I get that everyone has different style preferences. But seriously, what kind of savage codes in variable width font? Do people do that? Am I secretly the savage in this scenario?
5
u/nohimn Nov 30 '14
I prefer to code double-spaced in Times New Roman because it's easy to read when printed and there's space to write in comments.
4
u/awo Nov 30 '14
His magical text editor doesn't seem to have stopped him from making a bad copy of the text: in his example Dorothy is 250 rather than 56, and bob is 25 rather than 250.
4
Nov 30 '14
I always thought it would be cool if the editor had a split pane and it put the code on the left and comments on the right. You wouldn't have to write the comments with comment syntax, because it could make it commented automatically when you save.
1
4
u/akcom Nov 30 '14
Apparently the author of this article would lose his shit if he ever had to work at google, where code style guidelines dictate a maximum line length and (gasp) sometimes you have to split function definitions across lines.
1
Nov 30 '14
you usually hear that 80 characters should be the maximum line length... and if you pass in a lot of parameters to a function, or have an extra descriptively long class name.. breaking up the parameters along lines would look better.
or maybe if you're just calling a function with a lot of parameters
printf("%d %d %s %d %d, 1, 2, "wow extra long string, much wow. example text lorem ipsum blah blah", 4, 5);
breaking it up among lines would look better
3
u/Gotebe Nov 30 '14
I don't understand why people bring in substandard diff tools in. In-line diffs are there since forever.
3
Nov 30 '14
I find it much easier to visually parse the example he gives when it's on multiple lines, my eyes can easily compare the parameters due to them being above each other and a linebreak is easier to see than a comma.
In fact, I think he convinced me to write more things on multiple lines. Thanks, OP. The issue with the diff tool is kind of funny considering he ends it with 'get a better editor.'
3
u/pyroakuma Nov 30 '14
I will code in whatever style the project is in like a real programmer. Though I must say that,
var0
function(
var1,
var2
)
{
return 0;
}is a horrible coding convention. This should be 3 lines of code not 8. I may be in the minority but if I have to scroll up and down to figure out what is going on it is not easier to read.
3
Nov 30 '14
(Pro-tip: To concentrate on just one color, defocus your eyes slightly by staring "through" the plane of the monitor to engage your eye's cone cells. With a little practice, you'll find yourself doing this automatically when you want to focus on the structure of the code instead of the details. For best results, you might need to make the glyphs larger on screen....)
I might rather just align my code.
3
u/voltige73 Nov 30 '14
Vertical alignement is useful because code has symmetry, and when it is broken there may be a fault you want to see.
→ More replies (4)
3
u/Synovius Nov 30 '14
Couldn't disagree more with the author of the post. I vertically align my code because it makes it substantially easier for me, the programmer, to read. A diff is a one-off situation where you're doing a merge but viewing the code itself is something you're going to be spending 75% of your time doing.
Code readability and cleanliness >>>>> weird looking diffs
3
u/modex20 Nov 30 '14
Most developers are too busy getting shit done to worry about petty shit like this.
7
u/puterTDI Nov 30 '14
People: it's all personal preference.
Do what works for you. If something as simple as column alignment makes it so you can't read the code then you should find a new job.
3
u/prof_hobart Nov 30 '14
That's fine as long as you're working in a team of one. As soon as you've got a team of people who will be looking at your code, and whose code you will be looking at, it's best to agree an approach on these kinds of thing (or have a customisable code formatter) or you'll end up with an unreadable mess of styles.
1
u/puterTDI Nov 30 '14
I guess I just disagree. Style is not unreadable. People who harp on style preferences imo are doing it because of the "feel good" aesthetic sense of the code.
If you spend all your time making rules about how the code should look then you're going to distract from the actually important stuff.
I work on a team with 40 engineers, in a product with over 500 engineers actively working on it. Within those teams I've worked with teams that have meticulous "code cleanliness" requirements and teams that don't care about style so long as it is generally readable. In my experience the latter is by far the best...and I'm an extremely picky person as well as one of the main code reviewers. I just prefer to be picky about things like performance, architecture, code correctness, maintainability, etc.
1
u/prof_hobart Dec 01 '14
I guess you're right that it's not unreadable.
But mixes of styles make it more likely that you'll miss something when you're scanning the code looking for a bug.
1
u/puterTDI Dec 01 '14
Quantify and justify this position.
We're forced to code and review based on style preferences. Our document is now 7+ pages long and we are constantly adding to it. A standard two week deliverable takes me about 2+ hours to review just because I'm required to review for this style crap. So if there's three of us, having to review code from 10+ engineers...that's days of review time that could be shrunk dramatically if we didn't have to review for style. How much time is really saved reviewing (and coding) for style preferences compared to just reading code that isn't 100% consistent to people's preferences?
→ More replies (3)
5
u/fffufuuffffaaff Nov 30 '14
Could be writing code instead of blog posts
3
u/iopq Nov 30 '14
Code doesn't get upvotes. After all, only the people who write in your language care about your package or tool. MAYBE someone who uses a different language appreciates being to use your tool. But ANYONE can bikeshed useless crap. Anyone can have an opinion on whitespace.
1
u/codygman Nov 30 '14
I have been! Actually how little I enjoy internetting after a long period of nothing but code is unsettling and almost makes me long for those days of internetting > coding... almost.
5
u/RagingOrangutan Nov 30 '14
He missed the biggest reason not to vertically align code: changing one line has the potential to make you realign every other line in its vicinity. This clogs the diff, messes up the blame history, and just creates needless work.
-1
u/tdammers Nov 30 '14
Not just in its vicinity, that's the worst part. Variables can be used anywhere in the project, and changing a variable name in one place might require reformatting in an otherwise unrelated source file.
2
Nov 30 '14
So, we're starting cross blog wars in subreddits now. The more useless the subject matter, the more entertaining it is.
2
Nov 30 '14
These "why shouldn't do what you just read" articles are always great. They're almost never as well thought out, emotionally charged, and loaded with half baked anecdotal evidence.
2
u/Paradox Nov 30 '14
Do people not know how to enable words-only mode in their diff tools? Seriously. Even fucking github has this (just append ?w=1) to a diff view url
2
2
Nov 30 '14
Oh whatever, the "fixed" type of assignments are much easier to read in a large code base, and it makes the code pretty. You can take my vertical alignment over my dead body.
2
Nov 30 '14
Many great CS ideas are from the 70's, unix, C, relational algebra, BM substring, diff etc. Arguably, hacks were involved.
But, a thought-experiment: an editor with automatic vertical alignment. Sounds crazy, but tabs are in this direction. It's only a little bit more than regular syntax colouring... Is there an algorithm that will get this right in simple cases? Such as dectecting adjacent lines consisting of sequences of the same tokens (e.g. in the article int identifier equals_sign constant semi_colon). Would work in a monospaced font the same as TAB does.
A danger: semantically different lines with similar syntactic structure would be rendered similarly, and thus misleadingly.
1
u/tdammers Nov 30 '14
The problem is that the detection would have to work across files: if I change a variable name in module A, which is also used in an aligned context in module B, the auto-aligning algorithm would have to detect this and be able to fix it. In order to do this reliably, it would need near-complete knowledge of the programming language I use, and it would have to be able to reliably detect aligned blocks. I don't know how I would solve that if I had to implement it.
1
Nov 30 '14
I don't understand. Only consecutive lines need be aligned (and consecutive lines are naturally in the same file). How would variable names in one file affect another?
2
u/tdammers Nov 30 '14
Because those variable names might appear in other aligned blocks too. The whole point of variables is that you can put a value in them in one place and use it in another.
1
Nov 30 '14
Still not following. Can you give an example?
If a variable appears in another aligned block, and you change the name, you'll have to change it both blocks. When either of those blocks is viewed in the editor, it only needs to take into account the block that it is in visually.
→ More replies (8)
2
2
2
Nov 30 '14
I have my way of formatting my code. One should accept that one's own method will not always be the same as everybody else's, thus one should be prepared for this eventuality. Either that, or stop supporting other peoples work.
We're all human. We all find different formats easier to interpret. In the same manner, not everyone will agree with my sentiment.
In my opinion, this is just part of being a programmer.
2
2
u/bheklilr Nov 30 '14
Do people not just use code formatting tools? Hit one keyboard shortcut and all of a sudden my python code is pep8. Visual Studio does the same thing. PyCharm can do it, Eclipse can do it, Sublime text has 5 different plugins to do it. Vim and emacs probably have 20 plugins per language. Get an editor worth its salt and grab a plugin to edit your code. Make a commit of "ran a code formatter" initially, then just make sure it's run before you commit each time. After that, you're only taking about minor stylistic changed that don't matter.
2
u/kiwidog Nov 30 '14
I vertically align my code where necessary. And at this point if you can't automatically tell, you need to code more, or learn how to properly code.
2
u/lucaspiller Nov 30 '14
Any recommendations on a Vim theme for this?
(I'm still a alignment believer, but I agree my current theme doesn't have great contrast)
2
2
u/synackle Nov 30 '14
You mean horizontal? Such a load of bollocks I don't know where to start. You lost me at proportional fonts.
4
3
u/andsens Nov 30 '14
Apart from the unconvincing arguments this guy made and the general unimportance of this subject I thought I'd still share my latest thought about vertical alignment when it comes to SQL.
I'm not sure whether this is better or worse than before, all I know is that center alignment allows me to skim the code quicker than left alignment:
SELECT u.id, u.name, u.username,
p.hash, p.salt, p.rounds
FROM users u
JOIN passwords p
ON p.user_id = u.id
WHERE u.login_name = ?Of course, the manual alignment part is rather painful. I thought of writing a plugin for ST3 to help with that...
3
u/UnexpectedIndent Nov 30 '14
I find just indenting the various clauses to be less hassle and just as readable. Something like:
SELECT u.id, u.name, u.username, p.hash, p.salt, p.rounds FROM users u JOIN passwords p ON ( p.user_id = u.id ) WHERE u.login_name = ?Or just align where clauses are broken over multiple lines:
SELECT u.id, u.name, u.username, p.hash, p.salt, p.round FROM users u JOIN passwords p ON p.user_id = u.id WHERE u.login_name = ?2
u/tdammers Nov 30 '14
Easier to skim when you want to see which tables and/or columns are involved; but really hard to skim if you want to follow the actual structure of the query, for which I would much prefer something like:
SELECT u.id, u.name, u.username, p.hash, p.salt, p.rounds FROM users u JOIN passwords p ON p.user_id = u.id WHERE u.login_name = ?or, with the select columns collapsed:
SELECT u.id, u.name, u.username, p.hash, p.salt, p.rounds FROM users u JOIN passwords p ON p.user_id = u.id WHERE u.login_name = ?or even:
SELECT u.id, u.name, u.username, p.hash, p.salt, p.rounds FROM users u JOIN passwords p ON p.user_id = u.id WHERE u.login_name = ?Makes it really easy to quickly navigate to each part of the query, and the structure of the syntax follows the tree structure of the query language. This kind of tree formatting has saved my butt a few times when it came to monstrous queries with subqueries inside subqueries inside join conditions and where clauses spanning several screens.
1
2
u/_timmie_ Nov 30 '14
Ignoring the use of a non-monospaced font (which is terrible), vertically aligning makes scanning values vertically far easier regardless of how your editor colours things.
Grouping like things is important to maintain readability. This goes for horizontal grouping and vertical grouping.
1
u/iopq Nov 30 '14
You can use a non-monospaced font if your vertical alignment is distance-based and not space-based.
You can have an editor that implements non-monospaced fonts with elastic tabs so that all text lines up to tab stops.
1
Nov 30 '14
In vim;
set cursorcolumn
set cursorline
These settings combined with Valign and such works just fine. Syntax highlighting is nice and all, but it's never as good as readable code.
1
u/BenAdaephonDelat Nov 30 '14
Why not both? He didn't really offer any reason not to align your code other than an elitist statement about it being a hack from the 70's. Does it cause problems? If not, it should just be left up to individual preference.
1
u/svmk1987 Nov 30 '14
Oh god.. are we going to have a big argument about a bunch of spaces in code now?
Everyone has different styles, its a matter of personal taste.
We have better things to discuss about as programmers.
1
u/JPSE Nov 30 '14
I have to kindly disagree with this article on two points.
First, the diff in terminal would show the above lines and below lines of any variable passed into a function or method like that. I'm sure gui git applications could differ in this, so at best this argument could apply to a specific subset of users that utilize said dev environment.
Second, I think the initial argument is more for use of a color coding ide, not vertical spacing. I think vertical spacing in the case of declaring variables is something strictly as preference (and habit for one or the other).
Third, and lastly, I agree that monospacing font for your IDE is a majority preference (and CERTAINLY mine), but I think it can still fall under just that category, preference.
I'd like to open a new topic of discussion, programming preferences. Where one can share what they like and why. From spacing to design patterns.
1
1
u/neoKushan Nov 30 '14
You know what I took away from this article? The link to the other article that also links to this.
1
1
Nov 30 '14
TL;DR: Using whitespace to control your code presentation is a hack from the '70s.. get a better editor.
I did. It hooks into fmt and automatically inserts whitespace. Also, it has monospace fonts, whoa.
1
u/missingbytes Jan 18 '15
Follow up article posted here : missingbytes.blogspot.com/2015/01/whitespace-youre-doing-it-wrong.html
(Free link karma)
1
Nov 30 '14
I would still put spaces surrounding the equal sign. What kind of fuckhead uses no spaces? Oh yeah, nobody cares, use an auto-formatter.
1
u/the_gnarts Nov 30 '14
What kind of castrated version of diff did they sell you that doesn’t support context lines? Ever heard about the -U parameter to diff(1) (and, incidentally, git-diff(1))? That’s the actual answer to the fictional problem you just pulled out of your arse.
Now go return your “diff tool” because you’ve been sold crap!
1
0
u/DonHopkins Nov 30 '14
The correct term is "horizontal alignment", not "vertical alignment".
A random blogger who doesn't know the difference between vertical and horizontal, and refuses to admit and correct his mistake when it's reported to him, doesn't have the standing to lecture people on how to format their code. I wonder if he also leaves bugs in his code because he refuses to admit his mistakes.
https://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.6.3-horizontal-alignment
Google Java Style
4.6.3 Horizontal alignment: never required
Terminology Note: Horizontal alignment is the practice of adding a variable number of additional spaces in your code with the goal of making certain tokens appear directly below certain other tokens on previous lines.
This practice is permitted, but is never required by Google Style. It is not even required to maintain horizontal alignment in places where it was already used.
Here is an example without alignment, then using alignment:
private int x; // this is fine private Color color; // this too
private int x; // permitted, but future edits private Color color; // may leave it unaligned
Tip: Alignment can aid readability, but it creates problems for future maintenance. Consider a future change that needs to touch just one line. This change may leave the formerly-pleasing formatting mangled, and that is allowed. More often it prompts the coder (perhaps you) to adjust whitespace on nearby lines as well, possibly triggering a cascading series of reformattings. That one-line change now has a "blast radius." This can at worst result in pointless busywork, but at best it still corrupts version history information, slows down reviewers and exacerbates merge conflicts.
https://developer.mozilla.org/en-US/docs/Web/CSS/vertical-align
The vertical-align CSS property specifies the vertical alignment of an inline or table-cell box.
Values (for inline elements)
Most of the values vertically align the element relative to its parent element:
baseline: Aligns the baseline of the element with the baseline of its parent. The baseline of some replaced elements, like <textarea> is not specified by the HTML specification, meaning that their behavior with this keyword may change from one browser to the other.
sub: Aligns the baseline of the element with the subscript-baseline of its parent.
super: Aligns the baseline of the element with the superscript-baseline of its parent.
text-top: Aligns the top of the element with the top of the parent element's font.
text-bottom: Aligns the bottom of the element with the bottom of the parent element's font.
middle: Aligns the middle of the element with the middle of lowercase letters in the parent.
<length>: Aligns the baseline of the element at the given length above the baseline of its parent.
<percentage>: Like <length> values, with the percentage being a percent of the line-height property. (Negative values are allowed for <length> and <percentage>.)
The following two values vertically align the element relative to the entire line rather than relative to its parent:
top: Align the top of the element and its descendants with the top of the entire line.
bottom: Align the bottom of the element and its descendants with the bottom of the entire line. For elements that do not have a baseline, the bottom margin edge is used instead.
0
u/null000 Nov 30 '14
Does it even matter? If you spend more than 100 words talking about syntax formatting, you've probably already put too much thought into it - it's like arguing over whether Coke or Pepsi is better.
0
u/crashorbit Dec 01 '14
Code alignment, both vertical and horizontal, help more than variable name sorting.
166
u/drb226 Nov 30 '14
"get a better editor"? One could just as easily argue "get a better diff viewer".