I am parsing an array of values with two properties (Key and Value).
Based on the keyword Key certain functions are called which test the Value.
The trouble is, I am tasked with modifying the keywords for some projects for a new project. They share like 90% of the keywords but some are unique to each project and some others are common but other functions need to be called.
At the moment the code looks like:
Public Structure Options
Public Property Key
Public Property Value
End Structure
Public Sub CheckPresentation(OptionsList as List(of Options))
for each Elem in Optionslist
select case elem.key
case 1
if elem.Value<>"bla" then
logger.info("bla")
end if
case 2
...
case 99
...
end select
next
End Sub
I first wanted to simply build a new class and inherit the old class. But since all of the logic is in the select cases, that would require complete rebuilding with huge code overlap. Does anybody have an idea how to build this better?
You should create a method for each of your keywords.
e.g. for your
case 1, create the following method:Do this for every keyword.
Then, create a mapping which maps each keyword to its handler using a dictionary:
and instead of your gigantic
Select Case, simply use a lookup to call the right method:Now you can alter the behaviour in two ways:
Overriding:
Mark the methods
overridableand overwrite them in a subclass:Reconfiguration
Alter the
handlerdictionary to call other methods on specific keywords: