如何寫出有效率、好讀、可維護的 Java / Android 程式

How to write quality code in Java/Android


講者:曾冠諭

簡介:在軟體公司工作最痛苦的一件事情就是看到前人留下來的程式碼像本天書——看也看不懂、改也改不動,跑起來卻健步如飛,不僅一切正常,甚至連重構後的程式都跑得不如舊程式順暢。這個 Session 就是要討論有哪些技巧及心法可以避免寫出這樣難讀、難懂也難維護的程式,不僅可用於改善自己的程式品質,也適用於 Code Review 時給別人建議。


What is Quality?

  • Readable
  • Maintainable
  • Raliable
  • Performant
  • Reasonable
  • Scalable
  • Consistent
  • Fool-proof
  • Not scalable code example
    • use of View.getParent().getParent()
    • Typecast Context to Activity

3 Phases for Pragram

  • See the Mountain as a Mountain 見山是山
    • 直白 直接看得懂
    • 見山不是山
    • 見山又是山
  • A progamer try to learn more and more

    • design pattern
    • SetUp
  • 許多programmer會使用callback或抽象化技巧來達成彈性化的程式設計,但這樣其實不利於接手的人開發與理解

Simplicity needs delibable

  • 讓程式更簡潔

immutability

  • assign each variable only once

  • a single equation that functionally computes the result

POJO(Plain Old Java Object)

Why POJO? Because it’s simple.

No magic on the data itself.

Counter-example: Listeners inside a data class

Single Source Of Truth

  • Solving data inconsistency issues
  • Implementation
    • ShoppingCartActivity.ProductDetailsActivity
  • Single way of doing things

  • Ikea

    • single path from extrance to exit
  • Single Main Control Flow

The Beauty Of Vanilla Library/Api

  • Everyone knows what it means and its implication
  • Most common non-vanilla API
  • It's a nightmare if you modify Android support library
    • Customizes changes are surprising
    • Not scalable

Variable Naming

  • Suffix the name with the measure unit mTimestampMs, mDistancePx
  • Avoid misleading name getTotal() vs. updateAndGetTotal()
  • No two function with similar names 不要讓函式名稱類似
void setDataInternal(Data data){
        mData = data;
        }

void setDataAndNotifyChange(Data data){
        setData(data);
        notifyChange();
        }

Separation of Concerns

  • Don't do fake decoupling
  • One data/state can't be controlled by multiple classes/controllers
    • Two controllers controlling the sane view
  • Separating the core functionality from product business logic
    • Plugins
  • Use different decision variables if the decision is independent

    • if background color is green, show dollar sign icon
  • Separating UI from data fetching and caching

  • Separating data from view model

Composition Over Inheritance

results matching ""

    No results matching ""