A.3 Semantic Errors
237
The best way to correct your mental model is to break the program into its compo-
nents (usually the functions and methods) and test each component independently.
Once you find the discrepancy between your model and reality, you can solve the
problem.
Of course, you should be building and testing components as you develop the pro-
gram. If you encounter a problem, there should be only a small amount of new code
that is not known to be correct.
A.3.2
I’ve Got A Big Hairy Expression and It Doesn’t Do What I Expect
Writing complex expressions is fine as long as they are readable, but they can be
hard to debug. It is often a good idea to break a complex expression into a series of
assignments to temporary variables.
For example:
self.hands[i].addCard(self.hands[self.findNeighbor(i)].popCard())
This can be rewritten as:
neighbor = self.findNeighbor(i)
pickedCard = self.hands[neighbor].popCard()
self.hands[i].addCard(pickedCard)
The explicit version is easier to read because the variable names provide additional
documentation, and it is easier to debug because you can check the types of the
intermediate variables and display their values.
Another problem that can occur with big expressions is that the order of evaluation
may not be what you expect. For example, if you are translating the expression
Chia sẻ với bạn bè của bạn: