diff --git a/_naming_for_clarity.qmd b/_naming_for_clarity.qmd index 73643af..04160c3 100644 --- a/_naming_for_clarity.qmd +++ b/_naming_for_clarity.qmd @@ -1,60 +1,73 @@ ## Naming For Clarity {.smaller} -::: {style="font-size: 90%;"} - It may seem inconsequential, but carefully naming variables and methods can improve the -readability of code massively and can help to make code self documenting. +readability of code massively and can help to make code self-documenting. A few naming tips and conventions: ::: {.incremental} - The name should show the intention, think about how someone else might read it (this could be future you) -- Use pronounceable names e.g. `mass` not `ms`, `stem` not `stm` +- Use pronounceable names e.g. +- ``` + ms --> mass + chclt --> chocolate + stm --> stem + ``` - avoid abbreviations and single letter variable names where possible -- One word per concept e.g. choose one of `put`, `insert`, `add` in the same code base - Use names that can be searched -- Describe content rather than storage type -- Naming booleans, use prefixes like `is`, `has` or `can` and avoid negations like `not_green` -- Plurals to indicate groups, e.g. a list of dog objects would be `dogs`, not `dog_list` -- Keep it simple and use technical terms where appropriate -- Use explaining variables -::: - +- One word per concept e.g. choose one of `put`, `insert`, `add` in the same code base ::: ## Naming For Clarity {.smaller} -Some examples: - -- Pronounceable names without abbreviations: \ -``` - ms --> mass - chclt --> chocolate - stm --> stem - ``` -- Naming for the content, not the type: \ -``` +::: {.incremental} +- Plurals to indicate groups, e.g. a list of dog objects would be `dogs`, not `dog_list` +- Describe content rather than storage type e.g. +- ``` array --> dogs age_int --> age country_set --> countries ``` -- Naming booleans: \ -``` +- Naming booleans, use prefixes like `is`, `has` or `can` and avoid negations like `not_green` e.g. +- ``` purple --> is_purple not_plant --> is_plant sidekick --> has_sidekick ``` +- Keep it simple and use technical terms where appropriate +::: + +## Explaining Variables + +Without explaining variable: \ + +```python + +def calculate_fare(age): + if (age < 14): + return 3 + ... +``` + +With explaining variable: \ +```python +def calculate_fare(age): + is_child = age < 14 + if (is_child): + return 3 + ... +``` ## Explaining Variables -Without explaining variables, it is hard to see what this code is doing: +Without an explaining variable, it is hard to see what this code is doing: ```python import re -re.match("^\\+?[1-9][0-9]{7,14}$", "+12223334444") +re.search("^\\+?[1-9][0-9]{7,14}$", "Sophie: CV56 9PQ, +12223334444") ``` ## With explaining variables: @@ -64,8 +77,8 @@ It is easier to see the intention. The code is more self-documenting. ```python import re -validate_phone_number_pattern = "^\\+?[1-9][0-9]{7,14}$" -re.match(validate_phone_number_pattern, "+12223334444") +phone_number_regex = "^\\+?[1-9][0-9]{7,14}$" +re.search(phone_number_regex, "Sophie: CV56 9PQ, +12223334444") ``` ## Exercise 3 {.smaller} diff --git a/index.html b/index.html index b2e14ce..8554e6a 100644 --- a/index.html +++ b/index.html @@ -5813,7 +5813,7 @@ font-size: 2.5em; } - + RSE Skills @@ -7115,64 +7115,70 @@

Exercise 2

Naming For Clarity

-
-

It may seem inconsequential, but carefully naming variables and methods can improve the readability of code massively and can help to make code self documenting.

+

It may seem inconsequential, but carefully naming variables and methods can improve the readability of code massively and can help to make code self-documenting.

A few naming tips and conventions:

  • The name should show the intention, think about how someone else might read it (this could be future you)
  • -
  • Use pronounceable names e.g. mass not ms, stem not stm
  • +
  • Use pronounceable names e.g.
  • +
  •  ms    --> mass
    + chclt --> chocolate
    + stm   --> stem
  • avoid abbreviations and single letter variable names where possible
  • -
  • One word per concept e.g. choose one of put, insert, add in the same code base
  • Use names that can be searched
  • -
  • Describe content rather than storage type
  • -
  • Naming booleans, use prefixes like is, has or can and avoid negations like not_green
  • -
  • Plurals to indicate groups, e.g. a list of dog objects would be dogs, not dog_list
  • -
  • Keep it simple and use technical terms where appropriate
  • -
  • Use explaining variables
  • +
  • One word per concept e.g. choose one of put, insert, add in the same code base
-

Naming For Clarity

-

Some examples:

- -
 ms    --> mass
- chclt --> chocolate
- stm   --> stem
+
-
array       --> dogs
+
  • Plurals to indicate groups, e.g. a list of dog objects would be dogs, not dog_list
  • +
  • Describe content rather than storage type e.g.
  • +
  • array       --> dogs
     age_int     --> age
    -country_set --> countries
    -
      -
    • Naming booleans:
      -
    • -
    -
    purple    --> is_purple
    +country_set --> countries
  • +
  • Naming booleans, use prefixes like is, has or can and avoid negations like not_green e.g.
  • +
  • purple    --> is_purple
     not_plant --> is_plant
    -sidekick  --> has_sidekick
    +sidekick --> has_sidekick
  • +
  • Keep it simple and use technical terms where appropriate
  • + +

    Explaining Variables

    -

    Without explaining variables, it is hard to see what this code is doing:

    -
    import re
    -
    -re.match("^\\+?[1-9][0-9]{7,14}$", "+12223334444")
    +

    Without explaining variable:
    +

    +
    
    +def calculate_fare(age):
    +    if (age < 14):
    +        return 3
    +        ...
    +

    With explaining variable:
    +

    +
    
    +def calculate_fare(age):
    +    is_child = age < 14
    +    if (is_child):
    +        return 3
    +    ...
    +
    +
    +

    Explaining Variables

    +

    Without an explaining variable, it is hard to see what this code is doing:

    +
    import re
    +
    +re.search("^\\+?[1-9][0-9]{7,14}$", "Sophie: CV56 9PQ, +12223334444")

    With explaining variables:

    It is easier to see the intention. The code is more self-documenting.

    -
    import re
    -
    -validate_phone_number_pattern = "^\\+?[1-9][0-9]{7,14}$"
    -re.match(validate_phone_number_pattern, "+12223334444")
    +
    import re
    +
    +phone_number_regex = "^\\+?[1-9][0-9]{7,14}$"
    +re.search(phone_number_regex, "Sophie: CV56 9PQ, +12223334444")

    Exercise 3

    @@ -7217,14 +7223,14 @@

    PEP8 & Formatting - PyLint

    -
    (myvenv) $ pip install pylint
    -(myvenv) $ pylint myfile.py
    -(myvenv) $ pylint mydirectory/
    +
    (myvenv) $ pip install pylint
    +(myvenv) $ pylint myfile.py
    +(myvenv) $ pylint mydirectory/
    -
    (myvenv) PS> pip install pylint
    -(myvenv) PS> pylint myfile.py
    -(myvenv) PS> pylint mydirectory/
    +
    (myvenv) PS> pip install pylint
    +(myvenv) PS> pylint myfile.py
    +(myvenv) PS> pylint mydirectory/
    @@ -7233,46 +7239,46 @@

    PEP8 & Formatting - PyLint

    PEP8 & Formatting - PyLint - Example

    -
    def long_func(
    -    x,
    -    param_one,
    -    param_two=[],
    -    param_three=24,
    -    param_four=None,
    -    param_five="Empty Report",
    -    param_six=123456,
    -):
    -    val = 12 * 16 + (24) - 10 * param_one + param_six
    -
    -    if x > 5:
    -        print("x is greater than 5")
    -
    -    else:
    -        print("x is less than or equal to 5")
    -
    -    if param_four:
    -        print(param_five)
    -
    -    print("You have called long_func.")
    -    print("This function has several params.")
    -
    -    param_2.append(x * val)
    -    return param_2
    +
    def long_func(
    +    x,
    +    param_one,
    +    param_two=[],
    +    param_three=24,
    +    param_four=None,
    +    param_five="Empty Report",
    +    param_six=123456,
    +):
    +    val = 12 * 16 + (24) - 10 * param_one + param_six
    +
    +    if x > 5:
    +        print("x is greater than 5")
    +
    +    else:
    +        print("x is less than or equal to 5")
    +
    +    if param_four:
    +        print(param_five)
    +
    +    print("You have called long_func.")
    +    print("This function has several params.")
    +
    +    param_2.append(x * val)
    +    return param_2
    -
    (myvenv) $ pylint long_func.py
    -************* Module long_func
    -long_func.py:1:0: C0116: Missing function or method docstring (missing-function-docstring)
    -long_func.py:1:0: W0102: Dangerous default value [] as argument (dangerous-default-value)
    -long_func.py:1:0: R0913: Too many arguments (7/5) (too-many-arguments)
    -long_func.py:24:4: E0602: Undefined variable 'param_2' (undefined-variable)
    -long_func.py:25:11: E0602: Undefined variable 'param_2' (undefined-variable)
    -long_func.py:4:4: W0613: Unused argument 'param_two' (unused-argument)
    -long_func.py:5:4: W0613: Unused argument 'param_three' (unused-argument)
    -
    -------------------------------------------------------------------
    -Your code has been rated at 0.00/10
    -
    -(myvenv) $
    +
    (myvenv) $ pylint long_func.py
    +************* Module long_func
    +long_func.py:1:0: C0116: Missing function or method docstring (missing-function-docstring)
    +long_func.py:1:0: W0102: Dangerous default value [] as argument (dangerous-default-value)
    +long_func.py:1:0: R0913: Too many arguments (7/5) (too-many-arguments)
    +long_func.py:24:4: E0602: Undefined variable 'param_2' (undefined-variable)
    +long_func.py:25:11: E0602: Undefined variable 'param_2' (undefined-variable)
    +long_func.py:4:4: W0613: Unused argument 'param_two' (unused-argument)
    +long_func.py:5:4: W0613: Unused argument 'param_three' (unused-argument)
    +
    +------------------------------------------------------------------
    +Your code has been rated at 0.00/10
    +
    +(myvenv) $
    @@ -7485,19 +7491,19 @@

    Docstrings

  • Key references
  • -
    """
    -Short one-line description.
    -
    -Parameters
    -----------
    -name : type
    -    description of parameter
    -
    -Returns
    --------
    -name : type
    -    description of return value
    -"""
    +
    """
    +Short one-line description.
    +
    +Parameters
    +----------
    +name : type
    +    description of parameter
    +
    +Returns
    +-------
    +name : type
    +    description of return value
    +"""
    @@ -7512,40 +7518,40 @@

    Docstrings

    -
    def calculate_gyroradius(mass, v_perp, charge, B, gamma=None):
    -    """
    -    Calculates the gyroradius of a charged particle in a magnetic field
    -
    -    Parameters
    -    ----------
    -    mass : float
    -        The mass of the particle [kg]
    -    v_perp : float
    -        velocity perpendicular to magnetic field [m/s]
    -    charge : float
    -        particle charge [coulombs]
    -    B : float
    -        Magnetic field strength [teslas]
    -    gamma : float, optional
    -        Lorentz factor for relativistic case. default=None for non-relativistic case.
    -
    -    Returns
    -    -------
    -    r_g : float
    -        Gyroradius of particle [m]
    -
    -    Notes
    -    -----
    -    .. [1]  Walt, M, "Introduction to Geomagnetically Trapped Radiation,"
    -       Cambridge Atmospheric and Space Science Series, equation (2.4), 2005.
    -    """
    -
    -    r_g = mass * v_perp / (abs(charge) * B)
    -
    -    if gamma:
    -        r_g = r_g * gamma
    -
    -    return r_g
    +
    def calculate_gyroradius(mass, v_perp, charge, B, gamma=None):
    +    """
    +    Calculates the gyroradius of a charged particle in a magnetic field
    +
    +    Parameters
    +    ----------
    +    mass : float
    +        The mass of the particle [kg]
    +    v_perp : float
    +        velocity perpendicular to magnetic field [m/s]
    +    charge : float
    +        particle charge [coulombs]
    +    B : float
    +        Magnetic field strength [teslas]
    +    gamma : float, optional
    +        Lorentz factor for relativistic case. default=None for non-relativistic case.
    +
    +    Returns
    +    -------
    +    r_g : float
    +        Gyroradius of particle [m]
    +
    +    Notes
    +    -----
    +    .. [1]  Walt, M, "Introduction to Geomagnetically Trapped Radiation,"
    +       Cambridge Atmospheric and Space Science Series, equation (2.4), 2005.
    +    """
    +
    +    r_g = mass * v_perp / (abs(charge) * B)
    +
    +    if gamma:
    +        r_g = r_g * gamma
    +
    +    return r_g