Android筆記(1)使用annotation取代enum

在寫程式時為了避免魔術數字,常常會使用enum來取代魔術數字用來增加程式的可讀性,
但是呢,雖然有良好的做法,但後面接手的人,如果沒有同樣的認知,一樣會寫出含有魔術數字的程式,使用Android中的support-annotations,就可以用較好的方式解決這問題。

使用此作法的好處




  1. 較好的效能(enum其實比較耗資源)
  2. 較好的約束性
以Android Toast舉例說明
在時間的設定上,如果直接使用數字會有錯誤提示











來看看Toast如何實作,這邊採用了@Duration定義參數














採用了今天提到的做法,增加了提示














看完了今天的介紹,是不是迫不及待的想讓自己的程式碼更好了呢?

參考

https://developer.android.com/reference/android/support/annotation/StringDef.html
http://tedforum.blogspot.tw/2015/06/android-annotation-enum.html
https://noobcoderblog.wordpress.com/2015/04/12/java-enum-and-android-intdefstringdef-annotation/
http://asce1885.gitbooks.io/android-rd-senior-advanced/content/shen_ru_qian_chu_android_support_annotations.html
http://aiur3908.blogspot.tw/2015/06/android-annotation.html
http://seniorzhai.github.io/2015/08/03/Android-Support-Annotations/

留言