Posts match “ java ” tag:

Android AsyncTask 裡面可以看到有一個傳入的參數型態是 ...,像是

protected Long doInBackground(URL... urls) 

其實他是 Java 的 Varargs,以下有一段精闢的解釋。

The underlying type of a variadic method function(Object... args) is function(Object[] args). Sun added varargs in this manner to preserve backwards compatibility.
-- StackOverflow Can I pass an array as arguments to a method with variable arguments in Java?

所以如果是上面的例子,我可以如以下這樣做。其他例子可以參考 integer array static initialization.

URL[] urls = new URL[]{ "your_url_1", "your_url_2", "your_url_3" };

Clean coding-practices - Wakaleo Consulting

  • Choose names well

    • 愛他就不要拋棄他Choose 1 and stick to it
    • Use Meaningful names
    • 若即若離Don't talk in code, but don't state the obvious
    • Don't make me think!
    • Explicit method name
    • Clear parameter name
    • What are we counting?
    • Encapsulate boolean expressions: Method call rather than boolean expression
  • Let your code tell story

    • Methods should be small
    • Methods should only do one thing, stop mixing what & how
    • Choose what to do
    • The how is the responsibility of another class
    • Encapsulate boolean expressions
    • Avoid unclear/ambiguous class name
    • Avoid deep nesting
  • Code should communicate fluently

    • Use fluent APIs: Method chaining/cascading (return this;),
    • P32 :builder + abstract class + override
    • Replace constructors with creation methods
    • Encapsulate classes with factory
    • Functional Programming

Ref: Interview: Can we instantiate abstract class?

事實上,這個標題是有問題的。不過為了方便搜尋起見,所以還是這樣保留。

為什麼會說有問題呢?因為 abstract class 不能被 instantiate

You can't instantiate your abstract class, however you can instantiate a concrete subclass of your abstract class.

My my = my() {};   // 這樣是 anonymous implementation

My my = my();       // 這樣才是 instantiate 

今天突然在想一個問題:

this.mainObject.getA().getAB().getABA().getABAC().doSomething();

像這樣的 Method chaining / chain of getters 是好的作法嗎?

討論串

Drawback

  • NullPointerException: 這很直觀,如果中間有誰回傳 null 就炸了。
  • Law of Demeter

a.b.Method()違反了此定律,而a.Method()不違反此定律。一個簡單例子是,人可以命令一條狗行走(walk),但是不應該直接指揮狗的腿行走,應該由狗去指揮控制它的腿如何行走。

不過其中一段我蠻贊同的

the law of demeter doesn't apply in purely data/structural (ie "struct like") relationships. IE Student.GetAddress().GetStreetName() is perfectly acceptable.

也就是說,如果這只是一連串的 getters 的話,那沒有什麼問題;但如果涉及到 mutators 如 Student.GetLastTest().ChangeGradeToA(),那就不行了。

the Law only applies when mutators are involved.

Benefit

this.mainObject.getA().getAB().getABA().getABAC().doSomething();

v.s.

A A = this.mainObject.getA();
AB AB = A.getAB();
ABA ABA = AB.getABA();
ABAC ABAC = ABA.getABAC();
ABAC.doSomething();

其它

Copyright © 2013 Andro Chen
Powered by Logdown and Greyshade
Favicon from The Noun Project