[英]How should I refactor/redesign my code
我正在用Python編寫游戲,並且正在尋找有關如何重新設計代碼的建議。 以下是游戲實體的移動組件的定義。
加載函數接受PropertyTree對象,並相應地設置self
的屬性。 save函數的作用與此相反:根據self
的屬性,生成並返回一個PropertyTree。
class Movement(EntityComponent):
def __init__(self):
# Default values
self.speed = 0
self.acceleration = 0
def load(self, properties):
self.speed = int(properties['Speed'])
self.acceleration = int(properties['Acceleration'])
def save(self):
pt = PropertyTree()
pt['Speed'] = str(self.speed)
pt['Acceleration'] = str(self.acceleration)
return pt
代碼的問題是,正在進行大量的信息重復。 首先,我復制了將PropertyTree中的鍵與self
屬性關聯的信息,並且還復制了鍵本身( 'Speed'
和'Acceleration'
字符串出現了兩次)。 顯然,錯誤的余地很大。
我該如何重構?
作為起點:
class Movement(EntityComponent):
def __init__(self):
# Default values
self.speed = 0
self.acceleration = 0
serializable_fields = [
('speed', int),
('acceleration', int)
]
def load(object, source):
for name, field_type in object.serialiable_fields:
settarr(object, name, field_type(source[name]))
def save(object):
target = PropertyTree()
for name, field_type in object.serializable_fields:
target[name] = str(getattr(object, name))
return target
基本上,可以在EntityComponent類中創建一個單獨的保存/加載系統。 只需提供字段的數據列表即可告訴系統如何序列化當前對象。
如果您不熟悉它,還可以查看Python的pickle模塊如何工作。 我不建議將其用於瑣碎的事,但它可能會給您一些想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.