Created
June 20, 2021 20:01
-
-
Save ArisAgnew/98ec3cd6c7831b5c20622abe49911ca0 to your computer and use it in GitHub Desktop.
Refactoring If-Else to Table-Driven Approach
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //If-Else Approach | |
| public static class ParserFactory | |
| { | |
| public static IFileParser Create(string filename) | |
| { | |
| var extension = Path.GetExtension(fileName); | |
| if (extension == ".json") | |
| { | |
| return new JsonParser(); | |
| } | |
| else if (extension == ".xml") | |
| { | |
| return new XmlParser(); | |
| } | |
| else if (extension == ".yaml") | |
| { | |
| return new YamlParser(); | |
| } | |
| else | |
| { | |
| throw new NotSupportedException(); | |
| } | |
| } | |
| } | |
| //Table-Driven Approach | |
| public static class ParserFactory | |
| { | |
| private static Dictionary<string, Func<Parser>> _parsers = | |
| new Dictionary<string, Func<Parser>>(); | |
| static ParserFactory() | |
| { | |
| _parsers[".json"] = () => new JsonParser(); | |
| _parsers[".xml"] = () => new XmlParser(); | |
| _parsers[".yaml"] = () => new YamlParser(); | |
| } | |
| public static IFileParser Create(string filename) | |
| { | |
| var extension = Path.GetExtension(fileName); | |
| _parsers.TryGetValue(extension, out Parser parser); | |
| if(parser == null) | |
| throw new NotSupportedExtension(); | |
| return parser; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment