The Scenario
I'm creating a dynamic query builder to send to another component (a report builder).
Some parts of the query have placeholders. For example:
SELECT DISTINCT ID, NAME AS VALUE FROM EVENTS
WHERE {{ESTABLISHMENTFILTER.ID}} IS NULL OR ESTABLISHMENT_ID = {{ESTABLISHMENTFILTER.ID}}
The data to be replaced in the where clause can be an Integer, a String, a Date, and each one has a different behavior (for example: include single quote around the value in a string case).
My first approach was to create a Enum:
public enum FilterType
{
Integer,
String
}
and use it like this (in business layer for example)
switch (filter.Type)
{
case FilterType.Integer:
//Do replace logic for an integer
break;
case FilterType.String:
//Do replace logic for a string
break;
default:
break;
}
I'm also applying SOLID principles to my code, and I figured out that this could break OCP. So I refactored to use a base class
public abstract class FilterType
{
public abstract string Replace(string baseString, string oldValue, string newValue);
}
and each Type has its own implementation:
public class FilterTypeInteger : FilterType
{
public override string Replace(string baseString,string oldValue, string newValue)
{
//Do logic to replace for an Integer type
}
}
The problem
The SOLID solution worked for my tests, but in production code there's an int column in Database to determine the type. So I'm basically transferring the 'switch-case' logic to the datalayer, which will have to check this column to instantiate the correct FilterType (the code below is a pseudo-code because I have not implemented it yet):
if (dataReader["FILTERTYPE"] == 1)
filter.Type = new FilterTypeInteger();
else if (dataReader["FILTERTYPE"] == 2)
filter.Type = new FilterTypeString();
The Questions
1) The method implementing the 'if-else' logic above is breaking the OCP? Because if a new Type is created, a new else clause must be implemented
2) Is there another approach to keep the SOLID OCP principle to both database and business code without using the switch ou if-else clauses?