I know a little bit about Object Oriented design, but I'm not sure how to go about using those principles in my code. Here's what I'm working on:
public void Query(Agency agency, Citation queryCitation) {
queryCitation.AgencyCode = agency.AgencyCode;
switch (agency.ClientDb.Type) {
case "SQL":
QueryOracle(agency, queryCitation);
break;
case "PIC":
QueryPick(agency, queryCitation);
break;
}
}
(Most of these are objects from NHibernate. I'm working with a legacy database system and am refactoring parts of it into a code library.) Clearly, I could do something differently here so that I don't need duplicate functions for different database queries that have the same input. It should just know based off of the agency object whether to use an Oracle database or a Pick database connection. (If you've never heard of a Pick database, well I hadn't either until I started working here. We make queries to it through HTTP requests, so it's not SQL.)
Should I make an interface, for example called "ClientDbConnection" and then make two classes that implement that interface, move the code to query the database to those and then have something like "agency.clientDb.Query(queryCitation)" replace this whole function? I guess I'm thinking aloud here, but any input on this would be appreciated.
Here are some alternatives to switch statement : lookup table. polymorphism. pattern matching (especially used in functional programming, C++ templates)
Nested switch structures are difficult to understand because you can easily confuse the cases of an inner switch as belonging to an outer statement. Therefore nested switch statements should be avoided.
In this case, you could also use std::array<int, 5> , which, unlike std::vector<int> , can be constexpr . This worked perfectly, thank you so much! Switch statement can be removed!
Switch case variables can have only int and char data type. So float or no data type is allowed. In this ch can be integer or char and cannot be float or any other data type.
You will likely want to implement the strategy pattern here. Basically, each of your possible "types" in your switch statement would become a class of its own that implements the same interface.
Applying the Strategy Pattern
You can then use a factory method that takes a "type" value as its parameter. That method would return the correct class (its return type is the interface mentioned above).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With