簡體   English   中英

傳遞參數,Java / OOP編程中的好與壞做法

[英]Passing arguments, good and bad practice in Java/OOP programming

我最近開始用Java編寫android應用程序,我對Java完全陌生,我在大學時就使用c ++進行了面向對象編程的基礎知識。
我的問題是,將變量數據傳遞給Java中的不同方法時,什么是好與壞的做法? 例如,我在代碼中一直在做的事情是:

String one;
String two;
String three;
String four;

exampleOne(one, two, three, four);

exampleOne(String one, String two, String three, String four) {
      // do something
      exampleTwo(one, two, three, four);
}

exampleTwo(String one, String two, String three, String four) {
      // do something
      exampleThree(one, two, three, four);
}

exampleThree(String one, String two, String three, String four) {
      // do something
}

在我的代碼中,我做了這樣的事情,我最多將參數傳遞5次,這樣做是不好的做法嗎? 什么是更清潔,更環保的選擇?

如果有很多參數並且它們將被多次傳遞,那么我將使用DTO對象。

創建一個封裝這些參數的Pojo類,並在方法之間傳遞實例。 您還可以在DTO中添加一些輔助函數/方法,以簡化某些處理。

好吧,當您想調用帶有某些屬性的方法時,需要傳遞參數,但是對於大量相同類型的參數,您可以使用following。

您可以改用VarArgs

public void Method(String.. str) {
   //Here you will have Array  str[](Of String)  
  if(str!=null)
   for (String s: str) 
    System.out.println(s);//Iterate through Array for More Processing

}

如果您也想通過其他參數

 Method(int i, String... Other) {
    //VarArgs Must be Last
  }

注意:傳遞不同類型的參數,並使用轉換方法將String轉換為Double,Int等。 (嗯,不建議這樣做,但可以這樣做,因為您需要確保在哪一個地方通過了double,int等。)

您所做的事情沒有錯,但是您可以使用varargs(如TAsk所述)或通過創建一個小的容器類(例如ac struct,通常稱為bean)來闡明事情,以表示一組參數。

這使您可以整理事物並使代碼更具可讀性。 請注意,在創建類時,由於進行了新的分配,您會引入一些開銷,而對於c-struct而言,這不是正確的,因為由編譯器管理對struct成員的引用。

參數像在c中一樣在堆棧中傳遞,並且在java中沒有by-reference-arguments的概念,使用bean可以克服此限制。

聲明這樣的類可能很有用:

public class YourClass{

    private String one;
    private String two;
    private String three;
    private String four;

    public YourClass(String one, String two, String three, String four){
        this.one = one;
        this.two = two;
        this.three = three;
        this.four= four;
    }

    public void exampleOne() {
          // do something
          exampleTwo();
    }

    public void exampleTwo() {
          // do something
          exampleThree();
    }

    public void exampleThree() {
          // do something
    }

}

並使用它:

YourClass c = new YourClass(one, two, three, four);
c.exampleOne();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM