4

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?

Only Bolivian Here
  • 35,719
  • 63
  • 161
  • 257
  • 2
    this is really nothing to do with performance (which would be a micro-optimisation anyway). You pass the minimum the method needs to complete its contract. See @Jordao's answer: it is possibly better that the object has this responsibility – Mitch Wheat Apr 08 '12 at 03:10

3 Answers3

5

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()) {
  // ...
}
Jordão
  • 55,340
  • 13
  • 112
  • 144
  • With this in mind, this is for an MVC3 application where Models are prefered to be lightweight. Would it be good practice to access the database via a Repository from within a model? I would need to do that to run the HasUniqueKey method from within the object. – Only Bolivian Here Apr 08 '12 at 03:12
  • As long as the view and controller never see those database access methods then I'm guessing that would be fine. Don't try to optimise before you have basic operation, remember KISS - Keep it short, simple. – benjgorman Apr 08 '12 at 03:16
  • Repositories are part of the model, so your model can use it. Although, it should be an interface inside the model, so it can be better tested. Look [here](http://stackoverflow.com/questions/5582982/in-a-mvc-tiered-architecture-a-repository-class-is-part-of-the-business-layer-or) for some general info. – Jordão Apr 08 '12 at 03:16
3

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.

Dhananjay
  • 3,673
  • 2
  • 22
  • 20
2

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

Jimmy2Saints
  • 41
  • 1
  • 2