开发者

Which identifier variable is better to pass as an argument to a method?

Suppose the following method:

public void ShareClassStuff(int shareClassId)
{
    var shareClass = _shareClassService.GetShareClassById(shareClassId);

    (if shareClass != null)
        var shareClassStat = _shareClassService.GetShareClassStat(shareClass.Id);

    //go on to do stuff with shareClass & shareClassStat 
}

Here, I get a shareClass by passing sh开发者_如何学CareClassId to a service which returns the object I need. Next, I have to pass an Id to another method to get some different data.

The question I have is whether in the second service call, it's better to use the shareClassId variable, e.g.

GetShareClassStat(shareClassId)

or the Id property of the shareClass object, e.g.

GetShareClassStat(shareClass.Id)

or does it even matter?


I don't think it matters from a performance perspective, however, I would pass shareClassId to the second method, and not shareClass.Id.

The reason is when you use shareClass.Id, you now have a dependency on the positioning of the code. _shareClassService.GetShareClassById must be called first before _shareClassService.GetShareClassStat. Also, you introduce a dependency on the implementation of _shareClassService.GetShareClassById to properly populate the Id property.


I don't think it matters much.


Shouldn't matter. It would only matter later on if for some reason your GetShareClassById() method stopped returning nulls and instead started returning an empty class. Now you have a class with an invalid id. Not that it would ever happen, just saying that it would cause issues.

If you care about gaining 0.0001 seconds in speed then pass the variable.


While one could probably argue both ways, there is a very tiny benefit to passing shareClassId:

shareClass.Id is a property, therefore a method call (which may or may not be inlined by optimization). shareClassId is a simple integer.

So there is a very small advantage to passing the parameter.

Updated

There's another reason one might prefer to use the parameter: It's consistant. You used the parameter for the first "lookup by ID", so use the parameter again the second time.

Neither of these reasons are terribly compelling, but since you asked, I assume that you are interested in any imaginable reasoning.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜