In Apex, is it possible to use Polymorphism and Overloading to mitigate the need for conditional logic?
Yes, I would say there is a much better way. Use the Id.getSObjectType
method.
public String getAddress(Id recordId)
{
if (recordId == null) return null;
SObjectType idType = recordId.getSObjectType();
// further logic
}
Now, if you can set up your helper classes to just use an empty constructor, you could dynamically instantiate them based on this information. Just have them implement a common interface.
Helpers
public interface AddressHelper
{
String getAddress(Id recordId);
}
public class AccountHelper implements AddressHelper
{
public String getAddress(Id recordId) { /*implementation*/ }
}
public class ContactHelper implements AddressHelper
{
public String getAddress(Id recordId) { /*implementation*/ }
}
Dynamic Instantiation
static Map<SObjectType, Type> sObjectToHelper = new Map<SObjectType, Type>
{
Account.sObjectType, AccountHelper.class,
Contact.sObjectType, ContactHelper.class
};
public String getAddress(Id recordId)
{
if (recordId == null) return null;
SObjectType idType = recordId.getSObjectType();
if (!sObjectTypeToHelper.containsKey(idType)) return null;
Type helperType = sObjectTypeToHelper.get(idType);
AddressHelper helper = (AddressHelper)helperType.newInstance();
return helper.getAddress(recordId);
}
The above is a bit more verbose than strictly necessary, but I believe it will be more instructive as such.
Hope this example will help you
With condition:
public class exec{
public void execute(String procType){
if(procType='PROC1'){
//do this
}
if(procType='PROC2'){
//do that
}
}
}
With polymorphism:
public class exec{
public void execute(IProcess proc){
proc.execute();
}
}
public interface IProcess{
void execute();
}
public class Process1 implements IProcess{
public void execute(){
// do this
}
}
public class Process2 implements IProcess{
public void execute(){
// do that
}
}