By this point, you have probably experienced and written, code sketches that are;
The type of code just described is hard to deal with, understand, or change. Really, it is poorly written code. You must be saying to yourself… “There’s gotta be a better way!”
Well, there is… but first, let’s review the above problem in more detail.
Let’s create a specific problem. What would be the best way to write a sketch that contains 10 circular ellipses spread across a canvas?
You might be thinking to yourself, that we should write 10 lines of code to draw each ellipse. The following does this, it defines and draws 10 ellipses. Each ellipse’s position is set as a ratio of the windowWidth
.
[ Code Download ] | [ View on GitHub ] | [ Live Example ] |
The above code is fine, in that;
However, what if you wanted to draw 100 circles, or 1000, circles, or tens-of-thousands of circles? Do you really want to copy and paste 10,000 of the same lines of code? And what if you need to change something in one of the lines after the fact? Are you going to change each line? OBVIOUSLY NO!
If we want to eloquently accomplish the above, we are going to need to use a more efficient structure for our code.