论代码优化的艺术
if-else代码优化(卫语句)
1.原代码
age = 30
sex = 'man'
educatoion = 'school'
if age <= 30:
if sex == 'man':
if educatoion == 'school':
print("Pass")
else:
print("eduction not pass")
else:
print("sex not pass")
else:
print("age not pass")
2.优化后
age = 30
sex = 'man'
educatoion = 'school'
while True:
if age <=30:
pass
else:
print("age not pass")
if sex == 'man':
pass
else:
print("sex not pass")
break
if educatoion == 'school':
print("pass")
break
else:
print("school not pass")
break
使用卫语句让代码更加条理化、清晰化,此处并不明显,但是在真实情况下是很实用的
if语句优化(条件合并)
1.原代码
user_dict = {"name":"yifang","id":"123123123","userdata":"123"}
def GetUserInfo(user_dict):
if user_dict['userdata'] == 'vaild':
return "Invalid data received!"
if user_dict['userdata'] == '':
return "Invalid data received!"
if user_dict['id'] == '':
return "User Id Data is not normal!"
if int(user_dict['id']) <= 0:
return "User Id Data is not normal!"
return ('Welcome '+user_dict['name'])
print(GetUserInfo(user_dict))
2.优化后
user_dict = {"name":"yifang","id":"123","userdata":"123"}
def GetUserInfo(user_dict):
if IsDataVaild(user_dict):
return "Invalid data received!"
if user_dict['id'] == '':
return "User Id Data is not normal!"
if int(user_dict['id']) <= 0:
return "User id is not normal!"
return ('Welcome '+user_dict['name'])
def IsDataVaild(user_dict):
if (user_dict['userdata'] =='vaild') or (user_dict['userdata'] ==''):
return True
return False
def IsUserVaild(user_dict):
if (int(user_dict['id']) <=0) or (user_dict['id'] ==''):
return True
return False
print(GetUserInfo(user_dict))
代码并非越简单越好,而是越方便越好,函数条件的提炼
if语句优化(表驱动)
1.原代码(案例1)
def FormatDay(strDay):
if strDay == 'Mon':
return "MonDay"
if strDay == 'Tue':
return "TuesDay"
if strDay == 'Wed':
return "Wednesday"
if strDay == 'Thur':
return "ThursDay"
if strDay == 'Fri':
return "FriDay"
if strDay == 'Sat':
return "Saturday"
if strDay == 'Sun':
return "SunDay"
return "other"
print(FormatDay("Tue"))
2.优化后
Week = {
"Mon":"MonDay",
"Tue":"TuesDay",
"Wed":"Wednesday",
"Thur":"ThursDay",
"Fri":"FriDay",
"Sat":"Saturday",
"Sun":"SunDay",
"Other":"UnKown"
}
def FormatDay(day):
if (day != None) and (day in Week):
return Week[day]
return Week['Other']
print(FormatDay("Tue"))
1.原代码
def calc(command,num1,num2):
if command=='add':
return num1+num2
if command=='sub':
return num1-num2
if command=='mul':
return num1*num2
if command=="div":
return num1/num2
return 0
print(calc('add',1,1))
2.优化后(使用了匿名函数)
cal = {
"+":lambda a,b:a+b,
"-":lambda a,b:a-b,
"*":lambda a,b:a*b,
"/":lambda a,b:a/b,
}
def calcucation(command,num1,num2):
if (command != None) and (command in cal):
return cal[command](num1,num2)
return 0
print(calcucation('0',1,2))
if语句优化(策略结构) [面向对象]
1.原代码
def calc(command,num1,num2):
if command=='add':
return num1+num2
if command=='sub':
return num1-num2
if command=='mul':
return num1*num2
if command=="div":
return num1/num2
return 0
print(calc('add',1,1))
2.优化后
class Add:
def execute(self,num1,num2):
return num1+num2
class Sub:
def execute(self,num1,num2):
return num1-num2
class Mul:
def execute(self,num1,num2):
return num1*num2
class Div:
def execute(self,num1,num2):
return num1/num2
class Calculation:
def setStrategy(self,straget):
self.strategy = straget
def CalcResult(self,num1,num2):
return self.strategy.execute(num1,num2)
add = Add()
calc = Calculation()
calc.setStrategy(add)
print(calc.CalcResult(2,8))
if语句优化(工厂模式)
1.原代码
class TeacherUser:
def __init__(self):
self.name = "teacher"
self.permissionList = ["upload","modify","notify"]
def showPermission(self):
print(self.permissionList)
class StudentUser:
def __init__(self):
self.name = "student"
self.permissionList = ["query","comment"]
def showPermission(self):
print(self.permissionList)
class visitorUser:
def __init__(self):
self.name = "visitor"
self.permissionList = ['browse']
def showPermission(self):
print(self.permissionList)
loginUserType = "student"
if loginUserType == 'teacher':
user = TeacherUser()
if loginUserType == 'student':
user = StudentUser()
if loginUserType == 'visitor':
user = visitorUser()
user.showPermission()
2.优化后
class TeacherUser:
def __init__(self):
self.name = "teacher"
self.permissionList = ["upload","modify","notify"]
def showPermission(self):
print(self.permissionList)
class StudentUser:
def __init__(self):
self.name = "student"
self.permissionList = ["query","comment"]
def showPermission(self):
print(self.permissionList)
class visitorUser:
def __init__(self):
self.name = "visitor"
self.permissionList = ['browse']
def showPermission(self):
print(self.permissionList)
class loginUserType:
def GetInstance(self,usertype):
while True:
if usertype == 'teacher':
user = TeacherUser()
break
if usertype == 'student':
user = StudentUser()
break
if usertype == 'visitor':
user = visitorUser()
break
return user
loginUserType = loginUserType()
logintype = 'visitor'
usersimple = loginUserType.GetInstance(logintype)
usersimple.showPermission()