Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Currently I am working on C++ project, which can be classified as \"legacy\" pro

ID: 655037 • Letter: C

Question

Currently I am working on C++ project, which can be classified as "legacy" project. A lot of poor written code was committed because of lack of experience and under the pressure of deadlines. When I try to fix bugs I eventually make the new one.

Recently I got some more free time and I want to make this project better. To be exact I want to begin using TDD. However, it turned out not so easy. I faced the problem that I can't write test for any class. Singletons are everywhere. Even basic classes uses static members.

For instance, in project we widely use "Numeric" class (which is wrapper for decNumber C library for decimal computation). This class has static member to keep a context (precision, rounding mode, etc.). It is obvious that I need to refactor this class to avoid static fields.

Immediately I thought about dependency injection and a factory pattern. The factory will keep the single context, every user class should create Numeric instances only using that factory. But the code is going to be messy because the factory should be injected in every class which wants to construct "Numeric" instance.

Which pattern I can use for this case? Which one makes me sure that every instance of "Numeric" class uses single shared state?

Explanation / Answer

I really like the book Working Effectively with Legacy Code, by Michael Feathers, for this purpose. I'll go ahead and disagree with gbjbaanb here; testing is very useful for legacy code, but you may need to approach it at a higher level than individual classes at first. Start by writing functional tests: mock out an object, send it through the system, and see if it comes out as expected on the other end. This process is painful, but necessary.

Once you have this sort of testing around the portions of the code that you want to refactor, you can begin making large-scale refactors, like taking static methods out of the classes you're testing, and then begin expanding the scope of your refactoring.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote