Clean Code in a Python Algorithm

 The practice of writing clean code is one that exists no matter the language, framework or tool you use. When you write code that will be read or altered by any other developer, you will want that code to be easily readable and understandable, and easy to edit. Recently I've been working on some algorithms for an assignment at school, but I wanted to show off some of the things I might try to do to write clean code. The algorithm is in Python, which I have found can be easy to write cluttered code, but not difficult to write clean code either. I'll cover a couple of the things I chose to do to keep my code clean.

The first thing I do here that is worth mentioning is the Python Typing library. It allows you to describe the types for a variable. It doesn't make your code immutable but it makes your code more readable. By specifying the type of data the function expects, a reader doesn't need to go searching through the code to understand what to give the function. Typing also allows us to specify the output of the function.

Testing is extremely important when writing readable code. Some have said 'legacy code is any code without a test', and to some extent that is true. In cases of larger applications your code may run fine until it hits that untested portion, and you might be surprised with the outcome. I didn't quite follow the test driven development cycle to a tee, but I started by writing a test that asserted that my method returned what I expected. I used pytest, a great simple testing framework for Python. Each test contained only one assert statement which is also a common practice.

I use naming conventions that are relatively clear and concise. Rather than using something like i for a variable, I use neighbor which is a more descriptive term to describe the neighboring galaxies. At one point when building my flatten_list method I named the list that was passed in 'boop', which was not very descriptive. Instead I named it fat_list which I felt was a better way to describe a list that needs to be flattened.

Other than these things I've mentioned, I feel like the code is clean are readable. I give a description of the algorithm at the start, provide adequate spacing and I try to keep logic to one line at a time, even when it may be possible to combine multiple statements into a single line. I chose to favor readability over brevity and eloquence. There's more work to done, there always is, but I'm happy with how this code turned out.

Comments

Popular posts from this blog

Reviewing WPF and MVVM

Using WebRTC to build a videophone in React and TypeScript

Learning Flutter