What is elegant code?
Remember that code is a set of instructions for your computer. When you write code for your computer, it’s like writing a recipe and you need to be very clear. If you had to follow the instructions on a messy, long and confusing recipe for making a cake, you might miss an important step, need extra time, or even give up on completing the cake!
You might not think efficiency is a big deal, but when considering programs for driverless cars, every second can count.
Elegant code should be clean, concise and easy to understand. It’s not about showing how clever you are or how complicated you can make your code, it’s about finding the simplest way possible of making your idea work. As the famous writer Antoine de Saint-Exupery said, "perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away."
Look at the two examples of code to make a car drive in a square below. Both programs make the car do the exact same thing, but which solution would be easier to type out and faster to explain?
The piece of code on the right is easier to type and would be quicker to explain. Also, when you need to drive in a pentagon or a hexagon in the future, it will be much easier to modify the code on the piece on the right.
There are many cases, where multiple solutions might achieve the same goal, but one program may be a lot more efficient. For example, if a driverless car is using a camera to read the traffic lights one program might constantly scan the whole screen for traffic lights. However, another program might only scan at street junctions and only scan the sides of the screen because that is where we know traffic lights will be. Both programs would have the same result, but the second one is more efficient and can save time, memory, and energy. You might not think efficiency is a big deal, but when considering programs for driverless cars, every second can count. Having an efficient program could be the difference between stopping in time and crashing.
Computing | Ages 7-11
Code Smart is a computing and robotics education programme based on driverless car technologies. Code Smart takes students on a journey from complete beginners to code creators.