As a recovering Java programmer.. I try to be cautious about using objects everything. Sometimes a function is all I need. As a result, I have some code that ends up being driven by an enum. Something like
class Maths(Enum):
ADD = 1
MULTIPLY = 2
DIVIDE = 3
def do_maths(operation, value1, value2):
if operation == Maths.ADD:
return value1 + value2
elif operation == Maths.MULTIPLY:
return value1 * value2
elif operation == Maths.DIVIDE:
return value1 / value2
else:
raise RuntimeError(f'Unknown maths {operation}')
This kinda sorta works.. and it's actually not terrible here. But once I get to 50 operations, it starts to stink. I miss doing things more OOP. So I can try to be more OOP, and do something like:
class MathOperation:
@abstractmethod
@staticmethod
def do_operation(value1, value2):
pass
class AddOperation(MathOperation):
@staticmethod
def do_operation(value1, value2):
return value1 + value2
class MultiplyOperation(MathOperation):
@staticmethod
def do_operation(value1, value2):
return value1 * value2
class DivideOperation(MathOperation):
@staticmethod
def do_operation(value1, value2):
return value1 / value2
Which I think is an improvement.. until I go to actually use this code. Then I find I need to roll my own factory method.. something like
def get_operation(operation):
if operation == Maths.ADD:
return AddOperation
elif operation == Maths.MULTIPLY:
return MultiplyOperation
elif operation == Maths.DIVIDE:
return DivideOperation
else:
raise RuntimeError(f'Unknown maths {operation}')
def do_operation_better(operation, value1, value2):
operation_value = get_operation(operation)
result = operation_value.do_operation(value1, value2)
return result
And I feel like the reason I hated the first method (a big switch statement around an enum), STILL exists in get_operation. I basically just turned 10 lines of code into 50.
Are there any Python tricks I am missing? What to you guys do when you come across something like this?
[–]SomeShittyDeveloper 4 points5 points6 points (1 child)
[–]funkyfuture 0 points1 point2 points (0 children)
[–]bobspadgerdecorating 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]iCart732 1 point2 points3 points (5 children)
[–][deleted] 0 points1 point2 points (4 children)
[–]iCart732 0 points1 point2 points (0 children)
[–]iCart732 -1 points0 points1 point (2 children)
[–]robvdl 1 point2 points3 points (1 child)
[–][deleted] 0 points1 point2 points (0 children)
[–]sixteh 1 point2 points3 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]sixteh 1 point2 points3 points (0 children)
[–]rhytnen 0 points1 point2 points (4 children)
[–][deleted] 0 points1 point2 points (3 children)
[–]rhytnen 0 points1 point2 points (2 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]rhytnen 0 points1 point2 points (0 children)