重构技巧 引入Null对象
描述:有两个类,学生类和导师类,学生的导师类可能不存在,因此在获取学生导师名字等信息时都要先判断导师名字是否为空。重构后通过一个空导师类来处理导师为空的相应逻辑。
Before
1 # introduce null object 2 3 class Master: 4 def __init__(self): 5 pass 6 7 def setValue(self, name, major, age): 8 self.name = name 9 self.major = major 10 self.age = age 11 12 def getName(self): 13 return self.name 14 15 def getMajor(self): 16 return self.major 17 18 def getAge(self): 19 return str(self.age) 20 21 22 class Student: 23 def __init__(self, name): 24 self.master = None 25 26 def setMaster(self, masterName): 27 self.master = masterName 28 29 def getMaster(self): 30 return self.master 31 32 def getMasterNameByStudent(student): 33 master = student.getMaster() 34 if master is not None: 35 print master.getName() 36 else: 37 print "Not exist" 38 39 def getMasterMajorByStudent(student): 40 master = student.getMaster() 41 if master is not None: 42 print master.getMajor() 43 else: 44 print "Not exist" 45 46 def getMasterAgeByStudent(student): 47 master = student.getMaster() 48 if master is not None: 49 print master.getAge() 50 else: 51 print "Not exist"
After
1 # introduce null object 2 3 class Master: 4 def __init__(self): 5 pass 6 7 def setValue(self, name, major, age): 8 self.name = name 9 self.major = major 10 self.age = age 11 12 def isNull(self): 13 return False 14 15 def getName(self): 16 return self.name 17 18 def getMajor(self): 19 return self.major 20 21 def getAge(self): 22 return str(self.age) 23 24 25 class NoneMaster(Master): 26 def isNull(self): 27 return True 28 29 def getName(self): 30 return "Not exist" 31 32 def getMajor(self): 33 return "Not exist" 34 35 def getAge(self): 36 return "Not exist" 37 38 class Student: 39 def __init__(self, name): 40 self.master = None 41 42 def setMaster(self, master): 43 self.master = master 44 45 def getMaster(self): 46 if self.master is None: 47 return NoneMaster() 48 else: 49 return self.master 50 51 def getMasterNameByStudent(student): 52 master = student.getMaster() 53 print master.getName() 54 55 def getMasterMajorByStudent(student): 56 master = student.getMaster() 57 print master.getMajor() 58 59 def getMasterAgeByStudent(student): 60 master = student.getMaster() 61 print master.getAge()
测试:
1 master_1 = Master() 2 master_1.setValue("zhang liang", "computer", 40) 3 4 foo_1 = Student("wang gang") 5 foo_1.setMaster(master_1) 6 7 foo_2 = Student("li ming") 8 9 getMasterNameByStudent(foo_1) 10 getMasterNameByStudent(foo_2) 11 print 12 13 getMasterMajorByStudent(foo_1) 14 getMasterMajorByStudent(foo_2) 15 print 16 17 getMasterAgeByStudent(foo_1) 18 getMasterAgeByStudent(foo_2)
参考:重构 Martin Fowler 人民邮电出版社