質問

Consider the following example.

I need to check if a CouponModel has a unique serial key.

I have two choices:

CouponModel model = GetFromSomewhere();

if (!CouponHasUniqueKey(model))
{
}

//or

if (!CouponHasUniqueKey(model.SerialKey))
{
}

Of course in the method where I pass in the whole object I would have to access the string property instead of working directly with the string.

Which option is better and why?

役に立ちましたか?

解決

I believe the performance will be the same.

I'd also prefer to give the responsibility to the object itself:

CouponModel coupon = GetFromSomewhere();
if (!coupon.HasUniqueKey()) {
  // ...
}

他のヒント

1.Answer has already been posted ,though there is hidden "issue" in author's mind :

"Shall I pass entire object" ? When he says like that , he thinks that some giant globe needs to be passed to the method.

Well that's not the case with most of the object oriented programming languges (C# , java , c++ ..)

When you pass instance of the object to method you are passing just a reference and nothing else.

2.Mind you , property of an object itself can be a entire object and may be that property is of bigger size than object's size.

So answer to your question is for the performance benefit it does not matter what you pass.

The second option is better. As stated by the Law of Demeter. In this case not from an optimization stand point, but rather from a design stand point.

http://en.wikipedia.org/wiki/Law_of_Demeter

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top