Should I pass id or entities into my service

Viewed 1800

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);
}
6 Answers

Today I was thinking about this and thought of the following solution. It's just an idea, but it may be useful.

The idea is to always have entity/object parameters, to unify the service methods. If the caller doesn't have the object, it would pass a new "dummy" object with just the ID set. That object is marked as "not loaded", so you know only the id is available. If the service needs other fields from the object, it would check if it's loaded, and if not it will load it from the database.

Example code:

// caller with the object already loaded
productService.process(product);
// caller without the object loaded
productService.process(new Product(productId));

// service method
void process(Product product) {

    // Ensure product is loaded, only if we need more fields.
    // We could extract this to a helper method (e.g. ensureLoaded).
    if (!product.isLoaded()) {
        product = database.getProduct(product.getId());
    }

    ...
}

Pros and cons I see:

Pros

  • The service methods are unified (not sometimes entity and sometimes id, or both).
  • Service methods are clearly typed with the entity, not just String or Long identifier.
  • Easy to refactor if we later need (or not need) more fields from the entity. The caller code won't have to be changed.

Cons

  • The services have to call the helper method ensureLoaded if they need more fields.
Related