Apress Beginning Python From Novice to Professional
Gather what belongs together. If a function manipulates a global variable, the two of them might be better off in a class, as an attribute and a method.
Don’t let objects become too intimate. Methods should mainly be concerned with the attributes of their own instance. Let other instances manage their own state.
Go easy on the inheritance, especially multiple inheritance. Inheritance is useful at times but can make things unnecessarily complex in some cases. And multiple inheritance can be very difficult to get right and even harder to debug.
Keep it simple. Keep your methods small. As a rule of thumb, it should be possible to read (and understand) most of your methods in, say, 30 seconds. For the rest, try to keep them shorter than one page or screen.
When determining which classes you need and which methods they should have, you may try something like this:
- Write down a description of your problem (what should the program do?). Underline all the nouns, verbs, and adjectives.
- Go through the nouns, looking for potential classes.
- Go through the verbs, looking for potential methods.
- Go through the adjectives, looking for potential attributes.
- Allocate methods and attributes to your classes.
Now you have a first sketch of an object-oriented model. You may also want to think about what responsibilities and relationships (such as inheritance or cooperation) the classes and objects will have. To refine your model, you can do the following:
- Write down (or dream up) a set of use cases – scenarios of how your program may be used. Try to cover all the functionality.
- Think through every use case step by step, making sure that everything you need is covered by your model. If something is missing, add it. If something isn’t quite right, change it. Continue until you are satisfied.
When you have a model you think will work, you can start hacking away. Chances are you’ll need to revise your model or revise parts of your program. Luckily, that’s easy in Python, so don’t worry about it. Just dive in.