Behzad
Behzad

Reputation: 877

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

Currently, I am maintaining a program which is not developed by me, in so many parts of our code we have something like

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
}

is it necessary to check the parametes if they are null or not and then initialize my target object ?

what if i simply remove the ifs and just write something like below

Request.BookingName=bookingName;

note that, request object will be serialized at the end. and the response will be deserialized and return as BookingItemResponse.

which one is more performance optimized ?

Upvotes: 1

Views: 811

Answers (3)

sisve
sisve

Reputation: 19781

You will always need the if-statements, any caller can still pass null to your method. Default values are only used if the parameters are omitted.

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

This will still pass a null value to BookingItemResponse for the Currency parameter, while bookingName and passengerEmail will be assigned their default values.

Upvotes: 0

frankie
frankie

Reputation: 728

My suggestion is not to check for nulls. Instead - create overload for this method without bookingName and passengerEmail. This will make your code more flexible and more clear.

As for me, in your case you will not get any performance rise in any case.

Upvotes: 1

George Vovos
George Vovos

Reputation: 7618

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;
}

In any case you don't have to worry about the performance of an if statement in your code (unless that code is called millions of times)

Upvotes: 2

Related Questions