Teaching “Sexy Code”

It is possible to write in a way that is a joy to read.  Then again it is also possible to write in way that is just painful to read.  For example, when asked, Jonny wrote this about his weekend.

I was at home.  It was nice.  I ate food.

When prompted, he re-wrote it:

I stayed at home with my family over the weekend.  It was lovely, we had a great time together.  The best part was the food.  We ate a delicious fish pie.  My favourite!

It is also true that some pictures are considered works of art – but certainly not mine!  So it is true with poems and films – and so it is the case with code.

I use the term “Sexy Code” because it sticks in the minds of students – mostly because they are wierded out by a teacher using this word, but hey, they remember it!

They know there is a difference between writing code and writing good code.

“Sexy Code” is:

  • readable code
  • maintainable code

Readable code is paramount when working in a development team.  Others have to be able to read your code and understand what you are doing and how.  On a personal note, it is easier to spot bugs (see “Sexy Code #1” video below).

Maintainable / re-usable code makes development more efficient.  Why write more code than necessary?  Why, for example, write code that asks for your age, then later on more code that asks for how many brothers or sisters you have.  Both require a number.  So simply write a function that asks for a number and call that function twice!

Also, if a change is required then it can be done in one place rather than many (see “Sexy code #2 and #3 videos below).

“Sexy Code” rules

Sexy Code is very simple.  There are just x3 [edit: x4] rules:

  1. Use descriptive names for all sprites, variables and sub-routines
  2. Convert repeating instructions into loops
  3. Convert repeating functionality into sub-routines

After discussion with Sandra Davis at Godolphin School I will add another important rule which will make code more readable:

4. Comment the code

I had not considered comments as a rule as they can become out of date should the code develop and the coder forgets to update them, but Sandra is absolutely correct in that they are an excellent way to make code more readable and for students to structure their code during the development process.  Sandra encourages her students to write their pseudocode design as comments first, then convert the pseudocode into code.  I think this is an excellent approach.

Here are some examples of how “Sexy Code” is used to improve code development:

Sexy Code #1: Readable and Maintainable: Use descriptive names

Sexy Code #3: Readable and Maintainable: Use sub-routines

Sexy Code #2: Readable and Maintainable: Use loops

Next: Getting the ball rolling