I have three C# methods that almost perform identically. More specifically there is a large amount of code repetition but at the end, they perform different functions.
This is obviously very inefficient, so what's the best way to cut down on code duplication? Should I place it all in one method and use a switch & enum for the different functionality at the end? Alternatively, is there some kind of way you can have 3 separate classes and inherit the shared bit from another? I've done a fair bit of reading about this and from what I can gather, this is only used to gain properties from a whole different class.
Duplication decreases your code quality : Have duplication is fine, as long as you plan to throw your software away soon. Code quality is a necessity to make your software survive for long. Having duplicate code will make your code smelly and increases technical debt associated with it.
What is duplicate code? Duplicate code as the name suggests is a repetition of a line or a block of code in the same file or sometimes in the same local environment. People might consider code duplication acceptable but in reality, it poses greater problems to your software than what you may have thought.
Using DRY or Do not Repeat Yourself principle, you make sure that you stay away from duplicate code as often as you can. Rather you replace the duplicate code with abstractions or use data normalization. To reduce duplicity in a function, one can use loops and trees.
The duplication is because the important difference is at the inner most level, so extracting a function to do the common code isn't immediately obvious. In time Function3, 4, 5, etc. may be added thereby exacerbating the duplication. Pointers-to-member-functions are used.
Without seeing the code its hard to give a concrete example, but it sounds like you want to pass a delegate instance into the method.
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