Are there any best approaches for refactoring a programming project that has previously been written with the static reference anti-pattern (the majority of classes refer at some point to a static bean, where all of it's variables are public.

Half-way through a class, for instance you'll see something like:

EvilClass.Variable = returnsABoolean().

Then in a different class, you'll see something like:

if(EvilClass.Variable == foo){

Up until recently, I've been working with this pattern as I don't want to mix the styles and get things confused between the styles. But I want to slowly but surely 'fix' this project.

I'm the only dev on this, and I don't have the time to just sit down and refactor it (otherwise, I'd push for a full rewrite!).

Are there any best practices to be aware of when working with/fixing this kind of project/problem?

  • If you don't have the time to fix it, aren't sure how to approach fixing it, and it isn't broken and works, why do you need to 'fix' it? I mean is this something you want to do to teach yourself, or the project needs expanding or are you just fixing it for something to do?
    – user78252
    Apr 16 '13 at 9:52

I would probably approach this with the following multi-step approach:

Phase 1:

  1. If possible, isolate the static class.
    • In C# I would move the static class to its own assembly, or an isolated assembly, and make all its public members internal so that only a class in the same isolated assembly can use it.
  2. Then, create a non-static class that exposes the static class.
  3. Inject this non-static class into all other bits of code that required the static class.

Phase 2:

  1. Make the non-static class a singleton (only temporarily) so that it throws an exception if instantiated more than once
  2. Move all the static code into the non-static class.
  3. Delete the static class

Phase 3:

  1. Run your entire set of tests with this new setup (if you're lucky enough to have any)
    • Or, make a list of all code paths that use the new non-static class, and try to cover all of them with manual testing.
  2. If you encounter singleton exceptions, then you're accidentally instantiating your non-static class more than once. See why, and fix it
  3. If you don't encounter any exceptions, you're safe.

Phase 4:

  1. Refactor any code that uses your new non-static class so that it respects the Single Responsibility Principle. This will be a lot of work, but should help prevent accidentally using the wrong instance of the non-static class won't happen.
  2. Remove the Singleton pattern from the non-static class
  3. Keep refactoring until all dependencies are injected everywhere :) (easier said!)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.