2

Hi we're trying to loosely couple our codebase and is implementing dependency injection via Force-DI. It's my first time working with dependency injection and would like some clarity on how to approach the scenario below. I'd like to know if I should be passing records on the constructor.

Lets say we have an interface and an implementation as below

public interface IDiscount {
    Decimal calculateDiscount(Id orderlineId);
}

public class DiscountService implements IDiscount{

    public Decimal calculateDiscount(){
        //some calculations
    }
}

Can you tell me which of the two below implementation would be appropriate? I'm having this issue now since most of our classes, the records are being passed on the constructor.

public class OrderLineCalculator1{
    private IDiscount discountService;

    public OrderLineCalculator1(IDiscount discountService){
        this.discountService = discountService;
    }

    public decimal process(Id orderlineId) {
        return discountService.calculateDiscount(orderlineId);
    }
}

public class OrderLineCalculator2{
    private IDiscount discountService;
    Id recordId

    public OrderLineCalculator2(IDiscount discountService, Id recordId){
        this.discountService = discountService;
        this.recordId = recordId;
    }

    public decimal process() {
        return discountService.calculateDiscount(orderlineId);
    }
}

This is how I imagine it would look like on the triggerhandler. 2nd implementation looks tricky as somehow I would need to pass the records on the di module. Is this even possible?

public class OrderLineItemTriggerHandler {
    //some logic
    //implementation 1
    OrderLineCalculator1 oliCalculator = di_Injector.Org.getInstance('Some Module Binding');
    orderlineItem.Discount__c = oliCalculator1.process(orderLineItem.Id);

    //implementation 2
    OrderLineCalculator2 oliCalculator2 = di_Injector.Org.getInstance('Some Module Binding'); //would be tricky to pass record id through the module
    orderlineItem.Discount__c = oliCalculator2.process();
}
4
  • 1
    i think you have a typo in the arg names for each constructor - discount v discountService
    – cropredy
    Aug 12, 2021 at 17:32
  • How do you determine what's appropriate
    – identigral
    Aug 12, 2021 at 18:39
  • @cropedy good catch!
    – jema
    Aug 13, 2021 at 7:59
  • @identigral, probably the one that would work with Force-DI module. Right now Im not sure how I can pass some records or variables to the Di Module
    – jema
    Aug 13, 2021 at 8:00

0

You must log in to answer this question.

Browse other questions tagged .