Alex Rivera | Logout

Should I pass id or entities into my service

Asked 2010-09-24T01:49:00.250
14

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);
}
c#
Edit
Report

2 Answers

5

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 :)

answered 2010-09-24T01:56:25.037
1

If the purpose of the function is to calculate the account balance of the customer, I am going to assume that the customer is already created and contains an account balance. I am also going to assume that customerId is unique for each customer, so the account balance can be calculated (retrieved) by just using the customerId. Having said all this, if all you need is the customerId to create the balance, then just passing the id in is fine, but if you need other properties on the customer object, then passing in the whole customer may be a better idea or you may pass in multiple parameters instead.

As an example, if you were to create the balance solely based on the customerId, you might do something like this in your Balance() method (this looks more like a retrieval than a calculation though):

decimal balance = from c in Customers
                  where c.CustomerId == customerId
                  select c.Balance;

As shown above in the linq query, if all you need is customerId, then go ahead and just pass that in, but if you need other properties, pass in the whole customer or pass in more parameters. Looking at it further, you mentioned that this is for calculating the balance, so that would tell me that you might need more than just the customerId, so maybe passing more parameters or the whole object would be better in that case.

answered 2010-09-24T02:13:59.363

Your Answer