Search code examples
pythonmaintainability

What data structures can be used to enhance code maintainability?


The following python code works but the maintainability is quite poor.

However I'm failing to see a better way to implement the code to improve maintainability.

extraval = ""
if aline[0:1] == "-":
    extraval = '"expanded":true, '
    aline = aline[1:] 
if aline[0:1] == "+":
    extraval = '"expanded":false, '
    aline = aline[1:] 

When I need to work in extra parameters, the code keeps doubling.


Solution

  • You can use a dict to map the target keys to their associated values. It would then be trivial to check if a specific key exists and return the associated values of matching keys.

    For example:

    m = { 
      "-" : '"expanded":true, ',
      "+" : '"expanded":false, ',
    }
    
    if aline[0] in m:
      extraval = m[aline[0]]
      aline = aline[1:]