[英]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
。 相反 - 在没有bookingName
和passengerEmail
情况下为此方法创建重载。 这将使您的代码更灵活,更清晰。
至于我,在你的情况下,你不会在任何情况下获得任何性能提升。
您将始终需要if语句,任何调用者仍然可以将null传递给您的方法。 仅在省略参数时才使用默认值。
BookingItem[] items = null; // From somewhere...
new BookingItemResponse(items, Currency: null);
这仍将为Currency
参数的BookingItemResponse
传递null值,而bookingName
和passengerEmail
将被分配其默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.