mercredi 25 février 2015

Is it better to pass a service as an argument in a constructor or pass it in each class method?


from government.powerSupply import power


Case 1: Should service object be initial zed in constructor of the class and same amont of energy be available to house at all times



class Home(object):
def __init__(self, rooms=4, people=2, services=None):
self._services = services or power.Service()
self.connectionType = 2 # MeghaWatts
self.roomLights = {1:False, 2:False: 3: False, 4: False}

def turnLightsOn(self, room=None, all=False):
voltage = self._services.voltage()
if all:
for light, _ in self.roomLights.iteritems():
self.roomLights[light] = True
return True
else:
if room:
self.roomLights[room]
return True


or


Case 2 it should be done like this that function being called outside should have option to pass in services so different amount of power can be given to room whose light being turned on.



class Home(object):
def __init__(self, rooms=4, people=2, services=None):
self._services = services or power.Service()
self.connectionType = 2 # MeghaWatts
self.roomLights = {1:False, 2:False: 3: False, 4: False}

def turnLightsOn(self, room=None, all=False, services=None):
# in this case service can be passed from outside when call to
# turnLights on is made, and service can have different voltage input
self._services = services or self._services
voltage = self._services.voltage()
if all:
for light, _ in self.roomLights.iteritems():
self.roomLights[light] = True
return True
else:
if room:
self.roomLights[room]
return True


today, I was working on updating Unittest at office and found it convenient to do the Case 2. Since in my case service can contain different amount of power voltage as well as more than one service i.e a bath room may have power service or water supply service !!


Aucun commentaire:

Enregistrer un commentaire