bucker
9/17/2014 - 3:28 AM

Android Code Style cheatsheet.md

Android Code style guidelines

Java Rules

  1. 正確處理 Exceptions: 不要直接 catch generic Exception

  2. 不要使用Finalizer (try-finally)

  • Effective Java 2nd - Item 7
  • JLS 規格書不保證 finalizer 會被及時執行,也不保證一定會被執行。
  • 在 finalizer 執行跟時間相關的操作,就可能發生錯誤。
  • ex: 在 finalizer 裡關閉檔案,再用另一支程式來存取檔案,此時finalizer不保證及時關閉。

Java Style Rules

  1. Write short methods
  2. Define Fields in Standard Places: defined at top of the file, or before the methods that use them.
  3. The scope of local variables should be kept to a minimum (Effective Java Item 29).
  4. Use spaces for indentation: 不要用 tab
  5. PSF rule: private static final; public abstract final ...
Follow Field Naming Conventions
  • Non-public, non-static field names start with m.
  • Static field names start with s.
  • Other fields start with a lower case letter.
  • Public static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.

For example:

public class MyClass {
  int mPackagePrivate;
  private int mPrivate;
  protected int mProtected;

  private static MyClass sSingleton;

  pubilc int publicField;

  public static final int SOME_CONSTANT = 42;
}

Javatests Style Rules

Follow Test Method Naming Conventions

When naming test methods, you can use an underscore to seperate what is being tested from the specific case being tested. This style makes it easier to see exactly what cases are being tested.

For example:

testMethod_specificCase1 testMethod_specificCase2

void testIsDistinguishable_protanopia(){
ColorMatcher colorMatcher =newColorMatcher(PROTANOPIA)
    assertFalse(colorMatcher.isDistinguishable(Color.RED,Color.BLACK))
    assertTrue(colorMatcher.isDistinguishable(Color.X,Color.Y))
}

References