Читать книгу Introduction to Python Programming for Business and Social Science Applications - Frederick Kaefer - Страница 36

Good Programming Practice

Оглавление

Many references provide advice and recommendations for best practices in programming. We will discuss some basics that can influence your development practices as you learn more about Python. Best practices do not just apply to Python code, and in fact, there are entire books on the subject (i.e., Martin, 2009).

To begin, consider who else will be reading your code. Is it a coworker or classmate with whom you might work on the same project? Is it someone grading your homework or project? On the other hand, is it your future self, as you may be working on a long-term project? Consider whether your code will be easy to follow and understand to whomever may be reading your code after you write it (Kaefer, 2018).

To facilitate easy-to-understand code, be sure to use descriptive variable names. While variable names like a, i, or x may be simple to type and illustrate concepts, consider naming your variables after what they represent or their use. For example, customer_name is better than c, and survey_respondant_age is better than x. Be sure to add plenty of helpful comments in your code. Leave comments before functions to explain what they do. Include comments throughout code that may be complex or counterintuitive on a first glance. Above all, be consistent. Avoid using different styles throughout your code and follow any style guidelines that may be in place in your organization.

Good programming practice is not simply about the readability of your code. A programmer should always consider whether there is a better way to do something. Does your code require doing the same thing repeatedly? A loop is a logical response (we cover loops in Chapter 4). Also, consider breaking the code into functions and having a loop call the function. These are the basics of writing modular code. As the number of lines of code increases, you may want to break it up into modules. The more you interact with code from different sources and read code written by different people, the more clear it will be why following good practices results in better communication among programmers and fewer headaches when trying to debug problems (Martin, 2009; van Rossum, Warsaw, & Coghlan, 2001).

Lessons learned: In this section, we learned about some practices to follow when developing code, which becomes very important when you work with other people on programming projects.

Introduction to Python Programming for Business and Social Science Applications

Подняться наверх