How can refactoring help me improve my code

There are many reasons why bad interface or layout code happens to good programmers. Even a simple UI can require many lines to show all of its elements on the screen. Programmers often try to accomplish this using a single method, and the method quickly becomes long and hard to control. Furthermore, interface code is susceptible to being tweaked and changed constantly, which can wreak havoc unless you are disciplined about managing the changes. Because writing all the layout code can be tedious, an interface programmer will often use a design toolkit that generates code. The machine-generated code is notorious for being awkward and hard to make sense of without using the generation tool.

In principle, it's not hard to keep UI code under control. The key is refactoring, or continually improving the design and structure of existing code. The goal in refactoring is to keep the code in a state where it can be easily read and maintained in the future. Table 5.1 contains a description of some of the principles to keep in mind when refactoring. The most basic goal is to remember that somebody is going to have to read and understand your code in the future. Try to make that person's life easier—after all, it might be you.

Table 5.1 A listing of some important principles of refactoring



No duplication

You should avoid having multiple segments of code with the same functionality. This can become a maintenance headache when the functionality needs to change.

One thing at a time

A method should do one thing, and one thing only. Separate things should be moved into separate methods. Methods should be kept short.

Build shallow nests

Try to keep from nesting code more than two or three levels deep. Deeply nested code is also a good candidate for a separate method.

Avoid magic literals

String and numeric literals should be kept to a minimum. A good way to manage this is to separate literal data from the main portion of your code, and store it in a list or dictionary.

Some of these principles are particularly important in Python code. Because of Python's indentation-based syntax, small, compact methods are very easy to read. Longer methods, however, can be harder to decipher, especially if they are unable to fit on a single screen. Similarly, deep nesting in Python can make it tricky to trace the beginning and ending of code blocks. However, Python is a particularly good language for avoiding duplication, especially because of the ease with which functions and methods can be passed as arguments.

Was this article helpful?

0 0

Post a comment