patternpythonMinor
Alternative to multiple if statements
Viewed 0 times
statementsalternativemultiple
Problem
I have a function that needs to evaluate some parameters to determine if they're valid or not. They all need to be evaluated individually, so I have some code like below.
This code works, but is kind of ugly. I'm using the multiple
I'm not sure if there is a better way of evaluating command line arguments or not, but I would like to make the above code seem prettier. At the moment, it seems a little inefficient
#Configure widgets held in a layout
def layoutConfigurer(name, widgetType, minW, minH, maxH, maxW, flat, focus, image, position=False):
widgetType.setObjectName(_fromUtf8(name))
if minW or minH is not None:
widgetType.setMinimumSize(QtCore.QSize(minW, minH))
if maxH or maxW is not None:
widgetType.setMaximumSize(QtCore.QSize(maxH, maxW))
if flat:
widgetType.setFlat(True)
if focus:
widgetType.setFocusPolicy(QtCore.Qt.NoFocus)
if image:
widgetType.setPixmap(QtGui.QPixmap(_fromUtf8(image)))
if position:
widgetType.setAlignment(QtCore.Qt.AlignCenter)This code works, but is kind of ugly. I'm using the multiple
if statements, because I need them all to be evaluated and not just the first true statements.I'm not sure if there is a better way of evaluating command line arguments or not, but I would like to make the above code seem prettier. At the moment, it seems a little inefficient
Solution
I don't see any simple way to generalize your
What concerns me, though, is the length of the parameter list: 10 parameters, of which 9 are mandatory. The caller is certainly going to look ugly. A quick improvement might be to accept keyword arguments. A deeper analysis might reveal that those parameters should belong in an object instead.
if statements, since they result in very different actions. You might be able to push that complexity into the widgetType instead, if that code is under your control, but it won't reduce the total amount of code.What concerns me, though, is the length of the parameter list: 10 parameters, of which 9 are mandatory. The caller is certainly going to look ugly. A quick improvement might be to accept keyword arguments. A deeper analysis might reveal that those parameters should belong in an object instead.
Context
StackExchange Code Review Q#40902, answer score: 6
Revisions (0)
No revisions yet.