簡體   English   中英

檢查對象是否為空以准備映射的最佳方法

[英]Best way to check if an object is null to prepare for mapping

我正在嘗試將一個對象映射到另一個對象,我無法確定最好的做法是檢查要映射的對象是否為null

1-

public DTOIntIdentityDocument mapIdentityDocument(Identitydocument in) {
        if (in == null) {
            return null;
        } else {
            DTOIntIdentityDocument out = new DTOIntIdentityDocument();
            out.setDocumentType(this.mapDocumentTypeÇ(in.getDocumenttype()));
            out.setDocumentNumber(in.getDocumentnumber());
            return out;
        }
    }

2-

public DTOIntIdentityDocument mapIdentityDocument(Identitydocument in) {
        DTOIntIdentityDocument out = null;

        if (in != null) {
            out = new DTOIntIdentityDocument();
            out.setDocumentType(this.mapDocumentTypeÇ(in.getDocumenttype()));
            out.setDocumentNumber(in.getDocumentnumber());
        }

        return out;
    }

¿關於什么是最佳做法的任何想法?

顯然,這歸結為樣式,因此沒有硬性規定可以告訴我們哪個版本是“最佳”版本。 如果您的團隊編寫的所有代碼都遵循方案1,則這是最適合您的代碼。

話雖如此,我更喜歡一個簡單的初始防護,然后是計算“真實”結果的代碼,如下所示:

 if (in == null) 
     return null;

DTOIntIdentityDocument out = new DTOIntIdentityDocument();
out.setDocumentType(this.mapDocumentTypeÇ(in.getDocumenttype()));
out.setDocumentNumber(in.getDocumentnumber());
return out;

您想編寫易於閱讀和理解的代碼。 您的第一個版本具有else塊……實際上不需要在其自身的塊中帶有其他縮進。 另一方面,您的第二個片段使用了三個不同的抽象層:一個簡單的賦值,一個if塊,一個簡單的返回。 這肯定比選項1或我上面使用的修改代碼“更復雜”。 但請注意:選項2也有其優點。 如果要/必須跟蹤/記錄該方法的結果,請使用選項2,可以在return語句之前添加一個trace(out)

作為記錄:當您使用“硬核”清晰代碼時,該方法最終將顯示為:

if (in == null) 
     return null;

return createDocumentFrom(in);

或類似的東西。 含義:將實際創建和配置結果對象的代碼推送到其自己的私有方法中。 而且該方法無需擔心會傳入null參數!

最后: 理想的解決方案無需擔心空參數。 只是因為您避免像瘟疫一樣避免使用null。 並非總是可能,但總是可取!

if(in != null) 
   mapIdentityDocument(in)

public DTOIntIdentityDocument mapIdentityDocument(Identitydocument in) {
        DTOIntIdentityDocument out = new DTOIntIdentityDocument();
        out.setDocumentType(this.mapDocumentTypeÇ(in.getDocumenttype()));
        out.setDocumentNumber(in.getDocumentnumber());
        return out;

 }

暫無
暫無

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

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