Question

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.

Was it helpful?

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:]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top