Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid code duplication [closed]

Tags:

c#

code-reuse

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.

like image 263
Jonathan Avatar asked Dec 03 '10 09:12

Jonathan


People also ask

What are the disadvantages of duplication?

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 and how to avoid 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.

How do you avoid duplicates in a function?

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.

Why is there so much duplication in C++ code?

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.


1 Answers

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.

like image 79
Steven Keith Avatar answered Oct 21 '22 05:10

Steven Keith