Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I pass id or entities into my service

Tags:

c#

Considering I have a service to calculate a customer account balance with the interface

public interface ICustomerAccountCalculation
{
    Decimal Balance(int customerId);
}

is it better style to rather than pass in the customer id to pass the customer object like this

public interface ICustomerAccountCalculation
{
    Decimal Balance(Customer customer);
}
like image 901
Craig Avatar asked Sep 24 '10 01:09

Craig


2 Answers

I think it is really a question you need to answer because it depends. What is the cost vs benefit of passing the entity vs just passing the id? In the case of your service contract it looks like an id would be sufficient information (I know I am making an assumption) to get the account balance for a customer. Some other things to consider are the cost to serialize/deserialize your entity, etc...

But in another case it may make sense depending on the operation you are performing. Lets say the operation needs more information from the caller about the customer, it doesn't make sense to go to the database to get that information within the operation if you already have it loaded from within the caller...

So, it depends.

like image 144
Wil P Avatar answered Oct 26 '22 06:10

Wil P


Pass only the values that are going to be used in the function. If the customerid is enough for you to carry out further computation then pass only that much - if any other field is required pass it as a different parameter to the function.

It is a good practice to abstract the function from the object. A function should only be concerned with input VS output. For example if your function is float computeBalance(float, float) then it should be able to take any two float values and carry out the computation. Passing the object means you have read the object and extract the desired fields ... not a good thing to do :)

like image 26
Sagar V Avatar answered Oct 26 '22 07:10

Sagar V