--- title: Coding Tech 影片 - 『Writing Code You Won't Hate Tomorrow』 description: 如何編寫出編寫能夠經受住時間和自我判斷考驗的代碼? # image: https://hackmd.io/screenshot.png tags: Coding Tech,YouTube,Software Design # robots: noindex, nofollow langs: zh-Hant --- # Coding Tech 影片 - 『Writing Code You Won't Hate Tomorrow』 如何編寫出編寫能夠經受住時間和自我判斷考驗的代碼? > 影片連結 : https://www.youtube.com/watch?v=qjtMs7jQxEo > 活動: ConFoo Developer Conference 2019 > 講者: Rafael Dohms 主要在講[Object Calisthenics(物件健美操)](https://www.cs.helsinki.fi/u/luontola/tdd-2009/ext/ObjectCalisthenics.pdf),由Jeff Bay在他的書“The ThoughtWorks Anthology”中發明的9條規則。下方有[留言者整理](https://www.youtube.com/watch?v=qjtMs7jQxEo&lc=Ugy5vadkBYu0UjvjNKJ4AaABAg)。 ## 實行9個練習規則 1. **Only one indentation level per method** > 一個方法裡只有一個縮進級別 (讓方法只做一件事情) > SOLID 中的 **S**ingle responsibility 2. **Do not use else in a method. Return early** > 一個方法內不要使用`else`, 盡早`return` Example : ```python def notgood(v): if v == 1: print("... do `if` thing ...") # ... else: print("... do `else` thing ...") # ... #--- def good(v): if v != 1: print("... do `else` thing ...") # ..., then return print("... do `if` thing ...") # ... ``` 3. **Wrap primitive types if they contain behavior** > 如果原始型別包含行為,用物件包覆原始型別 Example : ```python # not good, no idea what `flase` means ... component.repaint(False) # good, an object wraps `false`. Clearly understand what `flase` means. component.repaint( Animate(False) ) ``` 4. **Only one property accessor ( a->b, a.b, ...) per line** > 一行只有一個屬性存取 5. **Name your variables and methods properly, no abbreviations** > 正確命名您的變量和方法,沒有縮寫 6. **Keep your classes small. Max 10 methods of 10 lines per method** > - 讓你的類別變小。最多10種方法,每種方法10行 > - Jeff Bay 原文 : 沒有超過50行的類別,沒有超過10個文件的package。 7. **Limit your instance variables to 2** > 將實例變量限制為2 8. **Use first class collections** > - 包含集合的類別都不應包含其他成員變數。 > - 每個集合都包含在自己的類別中。 > - 類別中方法的行為與集合相關。 9. **Don't use getters/setters** > - Getters & Setters are very generic. > - Use domain-driven approach. > - 使用方法來做為操作實例屬性值的介面,以確保物件隨著變化有一致性。 > - 本質上,定義好與物件溝通的介面是什麼,你可以用它來做什麼。 Example: ```python class Game(): def __init__(self): self.score = 0 def collectedCoin(self): # instead of have a coin, # actually control the score self.score += 1 game = Game() game.collectedCoin() ```