The simple act of using a better name (instead of applying a better comment) can reduce the difficulty of working with the code we write.
What is the purpose of this python code?
Why is it hard to tell what this code is doing? Clearly there are no complex expressions. Spacing and indentation are reasonable. There are only three variables and two constants mentioned at all. There aren't even any fancy classes or overloaded operators, just a list of lists (or so it seems).
list1 = []
for x in theList:
if x[0] == 4:
list1 += x;
return list1
The problem isn't the simplicity of the code but the implicity of the code (to coin a phrase): the degree to which the context is not explicit in the code itself. The code requires me to answer questions such as:
- What kinds of things are in
theList? - What is the significance of the zeroeth subscript of an
item intheList? - What is the significance of the value
4? - How would I use the list being returned?
theList. Let's rename that to theBoard.Each cell on the board is represented by a simple array. We further find that the zeroeth subscript is the location of a status value, and that a status value of 4 means 'flagged'. Just
by giving these concepts names we can improve the code considerably:
Notice that the simplicity of the code is not changed. It still has exactly the same number of operators and constants, with exactly the same number of nesting levels.
flaggedCells = []
for cell in theBoard:
if cell[STATUS_VALUE] == FLAGGED:
flaggedCells += cell
return flaggedCells
We can go further and write a simple class for cells instead of using an array of ints. It can include an intention-revealing function (call it isFlagged) to hide the magic numbers. It results in a new version of the function:
or more tersely:
flaggedCells = []
for cell in theBoard:
if cell.isFlagged():
flaggedCells += cell
return flaggedCells
Even with the function collapsed to a list comprehension, it's not at all difficult to understand.
return [ cell for cell in theBoard if cell.isFlagged() ]