[英]What do you call this?
該技術是否有名稱(方法調用返回對象,並在同一行上對其進行另一個方法調用)?
String pAID = commonAssets.getApplicationServerSettings().getSetting("plivoAuthID");
代替
ApplicationServerSettings applicationServerSettings = commonAssets.getApplicationServerSettings();
String pAID = applicationServerSettings.getSetting("plivoAuthID");
另外,當我執行第一個時,Eclipse不會提示我導入類ApplicationServerSettings
,但是如果我使用第二個代碼樣式,則會提示我。
另外,這兩種樣式僅僅是偏好嗎?
該技術稱為方法鏈接 。
String pAID = commonAssets.getApplicationServerSettings().getSetting("plivoAuthID");
來自維基的定義:
方法鏈接,也稱為命名參數慣用語,是用於在面向對象的編程語言中調用多個方法調用的常用語法。 每個方法都返回一個對象,使調用可以在單個語句中鏈接在一起,而無需使用變量來存儲中間結果。[1] 局部變量聲明是語法糖,因為人類難以深入地嵌套方法調用。[2] [3] 方法鏈也被稱為火車殘骸,原因是在同一行中接連出現的方法數量增加,這是因為將更多方法鏈接在一起[4],即使方法之間經常添加換行符也是如此。
您的第二個問題:
同樣,當我執行第一個操作時,Eclipse不會提示我導入類ApplicationServerSettings,但是如果我使用第二個代碼樣式,則會提示我。
ApplicationServerSettings
。 另一個看起來更簡單的示例(除了要介紹的示例):
看一下Wiki示例:
class Person {
private String name;
private int age;
// In addition to having the side-effect of setting the attributes in question,
// the setters return "this" (the current Person object) to allow for further chained method calls.
public Person setName(String name) {
this.name = name;
return this;
}
public Person setAge(int age) {
this.age = age;
return this;
}
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
// Usage:
public static void main(String[] args) {
Person person = new Person();
// Output: Hello, my name is Peter and I am 21 years old.
person.setName("Peter").setAge(21).introduce();
}
}
它通常被稱為流利的語法 。
恕我直言,這是風格問題,沒有對與錯。
流利的語法更加簡潔,這有時是一件好事。
另一個變體對於源代碼級調試更方便。 您可以單步執行這些語句並檢查中間結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.