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?

C++17 has updated the best answer for this question: T const & f() const { return something_complicated(); } T & f() { return const_cast<T &>(std::as_const(*this).f()); } This has the advantages that it: Is obvious what is going on Has minimal code overhead — it fits in a single line Is hard to get wrong (can … Read more