It is often possible to replace nested if statements with a single if statement that has a more complex condition. You should take this option as long as the condition does not become too complex itself.
Sometimes, in using a loop to position multiple things on the screen, we end up using a calculation based on the loop variable. It is often possible to adjust the way that loop variable progresses instead. You end up with more meaningful coe because the loop variable is taking exactly the values you need - it is a little-bit of documentation and the code is simpler.
Note that the following examples show cases where new functions could be created but in practical cases, we would be more likely to create a new function if:
it has a reasonable size or complexity
it will be used (or is likely to be used) in multiple places in the code
You might have similar code in two (or more) place in your program. For example
and replace the other places with calls to this function.
Common code but with one troublesome variation
Imagine you have, in one place in the code:
1
2
3
stroke(0)fill(255,0,0);ellipse(150,200,40,40);
and at another place in the code:
1
2
3
stroke(0)fill(255,0,0);rect(300,250,40,40);
The structure is the same, the numbers are the same, the intent is very similar, it would be great to have one place to put this code.
To achieve this, you should introduce a parameter that can be used to indicate which version of the major variation should be used. Create a new function and constants for the new parameter:
scanning the array to find the (first) element that is closest the average
We could create two functions to do these two tasks. The first function can calculate the average and the second function can be slightly generalised so that it will scan an array and find the (first) element that is closest to a particular value.
We now have two functions that are more likely to be used elsewhere in our programs than the original.
if returns true and false
If you end up with returntrue or returnfalse in the body of an if, then the condition probably contains all the information you need.
1
2
3
4
5
if(x){returntrue;}else{returnfalse;}
Dead code removal
You might have mutliple code paths in a function and you end up with mutliple return statements. Make sure you don’t have any redundant ones.