python - Good design for arguments that relate to a single configuration -


suppose have class represents box:

class box:     pass 

it's constructor may take arguments represent object, example length, width , height:

class box:      def __init__(self, length, width, height):         self.length = length         self.width = width         self.height = height 

now want add possibility add shadow box, has optional, suppose shadow can described shadowcolor , shadowstrength. there 3 ways how add arguments describe shadow constructor:

class box:      def __init__(self, ..., drop_shadow=false, shadowcolor=none, shadowstrength=none):         if drop_shadow:             pass 

this explicit way, drop_shadow here bit redundant, because can check if shadowcolor , shadowstrength not none , set shadow box:

class box:      def __init__(self, ..., shadowcolor=none, shadowstrength=none):         if shadowcolor , shadowstrength:             pass 

we dropped redundant argument possibility of adding shadow more implicit.

another approach have single argument - shadow tuple of 2 arguments, first 1 shadowcolor , other shadowstrength:

class box:      def __init__(self, ..., shadow=none):         self.shadowcolor = shadow[0]         self.shadowstrength = shadow[1] 

now have single argument, level of implicitly higher.

i care because used in opensource package , want make make usage of class easy possible.

how recommend deal sort of 'in-constructor' configuration of object?

have function accept dictionary of params. example

create:

parameters =  {"dropshadow": true, "shadowcolor": "#019201"} 

pass through

def __init__(self, length, width, height, params):         self.length = length         self.width = width         self.height = height          key, value in params.items():           if key == "dropshadow":             self.dropshadow = value           elif key == "shadowcolor"             self.shadowcolor = value 

if don't want use hardcoded string (which wouldn't suggest) create shape model class defines of properties static variables. example

class shapemodel:   drop_shadow = "dropshadow"   shadow_color = "shadowcolor" 

then replace above code

      def __init__(self, length, width, height, params):         self.length = length         self.width = width         self.height = height          key, value in params.items():           if key == shapemodel.drop_shadow:             self.dropshadow = value           elif key == shapemodel.shadow_color:             self.shadowcolor = value 

Comments

Popular posts from this blog

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

python Tkinter Capturing keyboard events save as one single string -

sql server - Why does Linq-to-SQL add unnecessary COUNT()? -