Functions’ good practices
Here’s a list of good practices that you can follow to improve the robustness and readability of your code:
- (a) be tight: keep your function small. If it’s getting to big, split it in multiple functions.
- (b) use meaningfull names: instead of write long comments of what a function does, take a moment to give a meaningfull and informative name to your function. For example:
def p_0_or_1(bool p)
pass
This is not a good name for the function since it does not inform us about its content, it does not clearly describe what the function does or what it is used for. A good function name should be descriptive, easy to understand, and should clearly convey the purpose of the function.
def print_on_intersection(bool isIntersected)
pass
This is not a good name for the function since it does not inform us about its content, it does not clearly describe what the function does or what it is used for. A good function name should be descriptive, easy to understand, and should clearly convey the purpose of the function.
- (c) one function should do one thing only (Single Responsibility Principle or SRP): do not hide actions or code that modify or produce effects in addition to what announced in the function name. Let always one function do one thing.
- (d) use docstrings: docstrings are strings that are written at the beginning of a function to describe what the function does. They are very useful to understand what a function does without reading its code. For example:
def calculate_beam_volume(length, width, height):
"""
This function calculates the volume of a beam
"""
volume = length * width * height
return volume
- (e) use type hints: type hints are a way to specify the type of the parameters and the return value of a function. They are very useful to understand what a function does without reading its code (NB: This only worky in CPython!). For example:
def calculate_beam_volume(length: float, width: float, height: float) -> float:
"""
This function calculates the volume of a beam
"""
volume = length * width * height
return volume