I am trying to reduce cylomatic complexity of code, because according to pylama my definition is 'too complex' and suggested solution includes calling functions with dictionary mappings.
So I tried it on my object oriented code but failed miserably.
class trial:
def __init__(self):
self.a = 'a'
self.b = 'b'
def a(self):
return self.a
def b(self):
return self.b
def select_one(self, option):
map_func = {
1 : self.a,
2 : self.b
}
return map_func[option]()
t = trial()
print(t.select_one(1))
If this is not possible what are the other possible solutions to reduce cyclomatic complexity.
first, the dictionary should be defined in __init__
or you have O(n)
complexity each time you enter your select_one
function (dictionary is built each time, which makes the example in your link wrong)
second, your methods have the same name as your attributes. Change that:
class trial:
def __init__(self):
self.a = 'a'
self.b = 'b'
self.map_func = {
1 : self.f_a,
2 : self.f_b
}
def f_a(self):
return self.a
def f_b(self):
return self.b
def select_one(self, option):
return self.map_func[option]()
t = trial()
print(t.select_one(1))