簡體   English   中英

Java接口-普通接口中的常量和靜態類

[英]Java Interface - constants and static class in normal interface

考慮以下接口。

public interface ThirdPartyApiHandler {

    public OperationResult doOperation(OperationInput input);

    public static class OperationResult {
         //members of OpeationResult. metrics after file processing
         private int successfulRecords;
         private int failedRecords;
    }  

    public static class OperationInput {
         //implementations call third party API to process this file.
         private String inputBatchFile; 
    }  

    //Constant which would be same across all implementations.
    public static final int GLOBAL_CONSTANT = 1;
}

上面的接口設計不好嗎?

  1. OperationResultOperationInput定義為靜態類。 它們只能由實現使用,而不能在其他任何地方使用。 我在這里看到的優點是-我不必為這兩個類創建單獨的文件。 他們還獲得父類的名稱空間。

  2. 我已經閱讀了有關常量接口的信息。 但是在這種情況下,我要在普通接口中定義常量,這些常量在所有實現中都必須相同,並且將在這些實現中使用。

我第一次使用此模式,因此想獲得建議。

OperationResult和OperationInput定義為靜態內部類。 它們不會在其他任何地方使用。

可以,因為它們不會在其他任何地方使用。 如果它們比我長,我寧願將它們放在單獨的班級中。

我已經閱讀了有關常量接口的信息。 但是在這種情況下,我要在普通接口中定義常量,這些常量在所有實現中必須相同,並且將在這些實現中使用。

那是聲明這樣一個字段的好地方。

在接口中具有嵌套類僅是其他名稱空間的問題。 當創建小的接口來支持簡單的數據結構時,這種方法有助於組織代碼。

我向您推薦此講座: Java技巧75:使用嵌套類可以更好地進行組織

請注意,在這種情況下, publicstatic是多余的,因此您不需要它們。 您需要記住的是,擁有此類並不限制其他開發人員在代碼的其他部分中使用它們。

從我的角度來看,這是一個很好的設計,但是,我將擴展並用接口替換該類。

public interface ThirdPartyApiHandler {

    OperationResult doOperation(OperationInput input);

    interface OperationResult {
         int getSuccessfulRecords();
         int getFailedRecords();
    }  

    interface OperationInput {
         String getInputBatchFile(); 
    }  

    final int GLOBAL_CONSTANT = 1; //This could be replaced by enum but no need 
}
Is above interface a bad design?

那將取決於您的實現設計及其在項目中的可用性。 邏輯對我來說看起來合法。 這種設計的可能用例如下

public interface A {
    static class B {
        public static boolean verifyState( A a ) {
            return (true if object implementing class A looks to be in a valid state)
        }
    }
}

public static class OperationResult {
     //members of OpeationResult. metrics after file processing
     private int successfulRecords;
     private int failedRecords;
} 

在上面的類中,您具有實例變量successRecords和failedRecords。 為什么不將這些靜態類的實例變量也設置為靜態,以便可以使用ThirdPartyApiHandler.OperationResult.successfulRecords訪問它們。 您甚至可以為變量使用靜態的getter和setter方法。


OperationResult and OperationInput are defined as static inner class.

與流行的看法相反,沒有“靜態內部類”這樣的東西:這根本沒有道理,當嵌套類是靜態的時,沒有“內部”類和“外部”類,因此它不能是“靜態內部類”。

從上面這樣的問題中挑選出來。 閱讀第一個答案。 我認為這將回答您的所有問題。

Is above interface a bad design?

很簡單,是的。

interface放置任何邏輯在語義上都是錯誤的。 接口向使用者公開了功能-這是其單一目的,不應被稀釋。

考慮在基本實現類中實現任何常用功能,並在不同的接口實現中使用繼承,或在一個或多個服務中使用組成。

編輯 -約書亞·布洛赫(Joshua Bloch)的《 有效Java》引述

當類實現接口時,該接口充當可用於引用該類實例的類型。 因此,類實現接口應該說明客戶端可以使用該類實例執行的操作。 為其他目的定義接口是不合適的。

暫無
暫無

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

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