Spaces for readability in code

25 views (last 30 days)
K E
K E on 8 Nov 2012
Which of following lines of code do you think is more readable:
plot(rand(1,1,1)+17/2,'r*');%No spaces
plot(rand(1, 1, 1) + 17/2, 'r*') ; % Space after commas, around arithmetic, before semicolons
I code with convention #2, which feels closer to the spacing of written text, but #1 seems to be more standard among Matlab programmers.
EDIT: Too much space is hard to parse, so I am going stop leaving space before commas. Personal preference seems to be the rule. Thanks everyone.
plot(rand(1,1,1) + 17/2, 'r*') ;
  2 Comments
John Petersen
John Petersen on 8 Nov 2012
I mostly use a combination of that where I condense with commas, but use more spacing for arithmetic, e.g.
plot(rand(1,1,1) + 17/2, 'r*')
Evan
Evan on 8 Nov 2012
Edited: Evan on 8 Nov 2012
I generally don't put spaces between commas, semicolons, colons and parenthesis. I use spaces for arithmetic (except for exponents, for some reason :P) and logical operators. For some reason I've always found code with no spaces after equals signs, addition, etc. to be messy and hard to read.
So I would type your example like this:
plot(rand(1,1,1) + 17/2,'r*');
EDIT: I would say I prefer your convention #2 over #1.

Sign in to comment.

Answers (4)

Daniel Shub
Daniel Shub on 9 Nov 2012
I recently found out that spacing can matter. I generally go with no spaces between operators, but always spaces after commas and surrounding equal signs
plot(rand(1, 1, 1)+17/2, 'r*')
A = (rand(1, 5)-3)+bsxfun(@(x, y)x+y, Z, U)-cellfun('length', M{:})
At one point I thought that it might be cleaner to do
A = minus(plus(minus(rand(1, 5), 3), bsxfun(@(x, y)plus(x, y), Z, U)), cellfun('length', M{:}))
but that was a short lived experiment.

Sean de Wolski
Sean de Wolski on 8 Nov 2012
Edited: Sean de Wolski on 8 Nov 2012
#
My eyes don't like having to parse an entire monitor. Though I do like spaces and commas in concatenations:
function [x, y, z] = foo(Q)
x = [Q, Q, Q];
y = ismember(Q,pi);
z = 17+5;
end

Matt Fig
Matt Fig on 8 Nov 2012
Edited: Matt Fig on 8 Nov 2012
Here is how I do it:
plot(rand(1,1,1) + 17/2,'r*')
A = (rand(1,5) - 3) + bsxfun(@(x,y) x+y,Z,U) - cellfun('length',M{:})
No spaces around commas, spaces B&A: =+-*/ unless the operands are easily seen by my eye and not between paranthesis or function calls. So for example, the two operands to the plus are not easily picked out, so I put a space B&A. The operands to the division are, so no space. Commas stick out like sore thumbs to me, so I never space them or semicolons.
Yep, I make my own spacing rules and I like them!

David Chorlian
David Chorlian on 9 Nov 2012
Readability is key; use spaces as you would in English prose.

Categories

Find more on Introduction to Installation and Licensing in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!