Formatting with Indentations, White spaces, and New Lines obviously fit into the coding style category.
if (a == b) {
foo();
}
// vs
if (a == b)
{
foo();
}
On the other hand, something that changes the run time of a program is no longer a matter of coding style, and becomes a matter of algorithm.
for (var i = 0; i < a.length; i++) {
// Remove first element of the array.
a.shift();
}
// vs
for (var i = 0; i < a.length; i++) {
// Remove last element of the array.
a.pop();
}
However, at what point does a matter of coding style turn into a matter of algorithm?
In other words, when comparing two possible methods to write the same program, when can we objectively determine whether the choice between the two methods is a preference in coding style or a difference in algorithm?
Is comparing to true
a matter of coding style or algorithm?
if (a == true) {
// a is true.
}
// vs
if (a) {
// a is true.
}
Is returning true
a matter of coding style or algorithm?
function isA(b) {
return this.a == b;
}
// vs
function isA(b) {
if (this.a == b) {
return true;
}
return false;
}
What about merging conditions into one if
statement?
if (a > 0) {
return foo();
}
if (b == 0) {
return foo();
}
// vs
if (a > 0 || b == 0) {
return foo();
}
Loop conditions?
// Loop 10 times.
for (var i = 0; i < 10; i++);
// vs
// Loop 10 times.
for (var i = 1; i <= 10; i++);
Nested if
statements?
function foobar() {
if (a) {
return foo();
}
if (b) {
return bar();
}
return barfoo();
}
// vs
function foobar() {
if (a) {
return foo();
} else {
if (b) {
return bar();
} else {
return barfoo();
}
}
}
These examples don't exactly change the run time of a program, yet isn't exactly just indentations, white spaces, or new line changes either. They are also typically not mentioned in coding style guides for most languages.
Given these examples above and other similar examples, is the difference a matter coding style or algorithm? Or is there a completely different term for it?
For example, if I am someone who uses for (var i = 0; i < 10; i++)
, do I simply have a different preference for coding style compared to someone who uses for (var i = 1; i <= 10; i++)
? Or is there something more to it besides just coding style? At what point is it no longer just coding style and start becoming part of the algorithm?