# -*- coding: utf-8 -*-
'''Please let code becomes much simpler and easier to maintain.
'''
def process(pet, action, target):
'''
>>> process('dog', 'eat', 'bone')
ok
>>> process('dog', 'eat', 'ball')
faild
>>> process('dog', 'play', 'ball')
yes
>>> process('dog', 'play', 'bone')
ok
>>> process('dolphin', 'play', 'ball')
good
>>> process('dolphin', 'play', 'bone')
faild
>>> process('dolphin', 'eat', 'bone')
faild
>>> process('dog', 'play', 'mouse')
opps
>>> process('cat', 'catch', 'mouse')
Traceback (most recent call last):
...
Exception
'''
if pet == 'dog':
if action == 'eat':
if target == 'bone':
print 'ok'
elif target == 'ball':
print 'faild'
else:
raise Exception()
elif action == 'play':
if target == 'bone':
print 'ok'
elif target == 'ball':
print 'yes'
else:
print 'opps'
else:
raise Exception()
elif pet == 'dolphin':
if action == 'eat':
if target == 'bone':
print 'faild'
elif target == 'ball':
print 'faild'
else:
raise Exception()
elif action == 'play':
if target == 'bone':
print 'faild'
elif target == 'ball':
print 'good'
else:
raise Exception()
else:
raise Exception()
else:
raise Exception()
if __name__ == '__main__':
import doctest
doctest.testmod()
上面是段示例代码、但它 是不是
上面是一些示例代码,但是写的很难看,不易维护,不易扩展-添加新的宠物,动作,目标。 我需要写很多代码;如何重建它,使它看起来非常简单,非常容易修改和扩展?你知道吗
也许这样的事情能帮上忙。虽然它不处理“失败”的案子。你知道吗
下面是一种不用类的方法,可以处理“失败”的情况,尽管它的时间更长:
相关问题 更多 >
编程相关推荐