Log Apex Right using Dependency Inversion Principle

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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store