Which identifier variable is best passed as an argument to a method?

Assume 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 shareClass , passing shareClassId to a service that returns the object I need. Then I have to pass the Id to another method to get some different data.

The question I have is whether the variable shareClassId will be used in the second service call, for example.

 GetShareClassStat(shareClassId) 

or Id properties of a shareClass object, for example

 GetShareClassStat(shareClass.Id) 

or does it even matter?

+4
source share
4 answers

I don't think this matters in terms of performance, however I would pass shareClassId to the second method, not shareClass.Id.

The reason is that you are using shareClass.Id, now you have a dependency on the positioning of the code. _shareClassService.GetShareClassById must be called first before _shareClassService.GetShareClassStat. In addition, you introduce an implementation dependency on _shareClassService.GetShareClassById to properly populate the Id property.

0
source

I do not think it matters a lot.

0
source

While both methods could be argued, there are very few advantages to passing shareClassId :

shareClass.Id is a property, so a method call (which can be optimized or cannot be inlined). shareClassId is a prime integer.

Thus, there is very little parameter to pass.

Update

There is another reason why the parameter could be used: It consistant. You used the parameter for the first "search by identifier", so use the parameter again again.

None of these reasons are terribly convincing, but since you asked, I assume that you are interested in any conceivable reasoning.

0
source

It does not matter. In the end, it will only matter if for some reason your GetShareClassById () method stops returning zeros and instead starts returning an empty class. Now you have a class with an invalid id. Not that this ever happened, simply saying that it would cause problems.

If you need to get a speed of 0.0001 seconds, pass the variable.

0
source

Source: https://habr.com/ru/post/1344302/


All Articles