Log Apex Right using Dependency Inversion Principle
1 min readOct 15, 2021
The Dependency Inversion Principle says:
Depend in the direction of abstraction. High level modules should not depend upon low level details.
An example of a higher level module depending on lower level details is this logger
public class RulesEngine {
public RulesEngine(){}
public void processRule(string rule){
Log_Message__e logMessage = new Log_Message__e();
logMessage.Message__c = 'Processing rule: ' + rule;
EventBus.publish(logMessage);
}
}
It shouldn’t care how the log is logged, so we want to refactor by extracting the function for logging, so the higher functionality doesn’t need the details.
public class Logger {
public Logger(){}
public void log(string message){
Log_Message__e logMessage = new Log_Message__e();
logMessage.Message__c = message;
EventBus.publish(logMessage);
}
}
Now the higher level module can let the lower deal with the details and just care about the abstraction of logging.
public class RulesEngine {
Logger lgr;
public RulesEngine(){
lgr = new Logger();
}
public void processRule(string rule){
lgr.log('Processing rule: ' + rule);
}
}