Welcome, this site is dedicated to explaining code samples I've personally come across during my time programming and teaching programming. These samples are intended to help beginner programmers understand best practices and avoid common mistakes.
The use of if
and else
does not add meaning to the below code and should be avoided.
Avoid this:
if (max < y && y > min) {
between = true;
} else {
between = false;
}
Choose this instead:
between = max < y && y > min;
The exception to these rules is when one of the code paths has an additional statement. e.g.
if (max < y && y > min) {
between = true;
} else {
between = false;
++y; // this could be any statement, in either the true or false path.
}
Very similar to the above situation.
Avoid this:
if (max < y && y > min) {
return true;
} else {
return false;
}
Choose this instead:
return max < y && y > min;
In most instances, a variable is not needed.
Avoid this:
int doSomething(int param) {
int result;
result = (param + 1) / 2;
return result;
}
Choose this instead:
int doSomething(int param) {
return (param + 1) / 2;
}
There is an exception to the above rule - a variable may be used for debugging, however it is better to do an assignment from where the function/method is called, for debugging purposes.
e.g.
int result = doSomething(7);
The ternary operator is best avoided in most cases. Here are a few examples of how to not use it:
positive = (x > 0)? true : false;
simplifies to:
positive = x > 0;
Java specific:
object2 = (object1 != null) ? object1 : null;
simplifies to:
object2 = object1;
This is relatively rare, but very much wrong.
Don't do this:
int count;
for (int i = 0; i < array.length; ++i) { // where 'array' is an array reference
count++;
}
Use this:
int count = array.length;
The below example is from a text book, however I'd personally advise against it.
void string_copy(char *dest, const char *source) {
int i;
for (i = 0; (dest[i] = source[i]) != '\0'; ++i);
}
The use of a while loop is far better suited.
void string_copy(char *dest, const char *source) {
int i;
while ((dest[i] = source[i]) != '\0')
i++;
}
The use of pointer notation makes this a more efficient implementation.
void string_copy(char *dest, const char *source) {
while ((*dest = *source) != '\0') {
++dest;
++source;
}
}