簡體   English   中英

檢查參數值是否為null,然后初始化對象。 這是個好主意嗎?

[英]check parameter values if its null or not, and then initialize the object. is it good idea?

目前,我正在維護一個不是由我開發的程序,在我們的代碼的很多部分我們有類似的東西

public BookingItemResponse(BookingItem[] BookingItems,Currency="USD", string bookingName=null, string passengerEmail =null)
{
    Request.BookingItem[]=BookingItems;
    if(bookingName!=null) Request.BookingName=bookingName;
    if(passengerEmail!=null) Request.PassengerEmail=passengerEmail;

    return BookingItemResponse
}

是否有必要檢查參數是否為null,然后初始化我的目標對象?

如果我只是刪除ifs並只寫下面的內容會怎么樣?

Request.BookingName=bookingName;

請注意,請求對象將在最后序列化。 並且響應將被反序列化並返回為BookingItemResponse。

哪一個更加性能優化?

public BookingItemResponse(BookingItem[] BookingItems,Currency="USD", string bookingName=null, string passengerEmail =null)
{

    Request.BookingItem[]=BookingItems;

    //If the default value is null you can remove the ifs
    Request.BookingName=bookingName;
    Request.PassengerEmail=passengerEmail;

    //else you can use the ?? operator
    Request.BookingName=bookingName ?? "Your default value";
    Request.PassengerEmail=passengerEmail ?? "Your default value";

    return BookingItemResponse;
}

在任何情況下,您都不必擔心代碼中if語句的性能(除非該代碼被調用數百萬次)

我的建議是不檢查null 相反 - 在沒有bookingNamepassengerEmail情況下為此方法創建重載。 這將使您的代碼更靈活,更清晰。

至於我,在你的情況下,你不會在任何情況下獲得任何性能提升。

您將始終需要if語句,任何調用者仍然可以將null傳遞給您的方法。 僅在省略參數時才使用默認值。

BookingItem[] items = null; // From somewhere...
new BookingItemResponse(items, Currency: null);

這仍將為Currency參數的BookingItemResponse傳遞null值,而bookingNamepassengerEmail將被分配其默認值。

暫無
暫無

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

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