How to: Write elegant code

View all subject updates

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?

Subject Update How To Write Elegant Code Figure 1

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.

activity age bookmark-fill icon bookmark boy-girl calendar chevron-down icon close icon compass cross icon download encounter-live facebook gallery icon instagram icon Instagram icon linkedin links icon location mail icon map next play previous professional-development right-arrow icon search share single image social-media speaker spinner icon students subject-update teacher-resources tick icon time twitter user video-lesson video youtube