How can I use multiple constructors to remove duplicated code while maintaining readability?

As an alternative to calling an initialization method from all constructors (which prevents you from using readonly fields) or factory methods (which introduce additional complexity when you have derived classes), you can use a parameter object: int a, b, c; public Constructor() : this(new ConstructorParameters()) { } public Constructor(int x, int y) : this(new ConstructorParameters(x, … Read more

How to reduce code duplication when dealing with recursive sum types

Congratulations, you just rediscovered anamorphisms! Here’s your code, rephrased so that it works with the recursion-schemes package. Alas, it’s not shorter, since we need some boilerplate to make the machinery work. (There might be some automagic way to avoid the boilerplate, e.g. using generics. I simply do not know.) Below, your recurseAfter is replaced with … Read more

How much duplicated code do you tolerate? [closed]

Refactoring: Improving the Design of Existing Code The Rule of Three The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor. Three strikes and you refactor. Coders … Read more

Is duplicated code more tolerable in unit tests?

Readability is more important for tests. If a test fails, you want the problem to be obvious. The developer shouldn’t have to wade through a lot of heavily factored test code to determine exactly what failed. You don’t want your test code to become so complex that you need to write unit-test-tests. However, eliminating duplication … Read more

How do I remove code duplication between similar const and non-const member functions?

For a detailed explanation, please see the heading “Avoid Duplication in const and Non-const Member Function,” on p. 23, in Item 3 “Use const whenever possible,” in Effective C++, 3d ed by Scott Meyers, ISBN-13: 9780321334879. Here’s Meyers’ solution (simplified): struct C { const char & get() const { return c; } char & get() … Read more

techhipbettruvabetnorabahisbahis forumueduedusedusedusedusedusedueduedusedus