1

Here is the problem:

I am migrating a big legacy application in Java and I need to make some use of a certain (rather big) amount of legacy APIs exposed as static methods. We can't just avoid using these methods for now and these are making the whole bunch of stuff such as requesting database and so on. Using such methods as they are makes my code quite difficult to test and I am wondering what pros and cons may be if I introduce some non-static proxies to these APIs?

Consider the following example:

package my.legacy.project.util;

class LegacyRulesUtil {
    ...
    public static IBusinessRules getRules(IQuery query) { ... }
    ...
}


package my.new.project.service.proxy;

@Service
class LegacyRulesProxyService {
    ...
    public IBusinessRules getRules(IQuery query) {
        return LegacyRulesUtil.getRules(query);
    }
    ...
}


package my.new.project.consumer;

@Component
class Consumer {

    private final LegacyRulesProxyService legacyRulesProxy;

    @Autowired
    public Consumer(LegacyRulesProxyService legacyRulesProxy) {
        this.legacyRulesProxy = legacyRulesProxy;
    }

    public void consume() {
        ...
        legacyRulesProxy.getRules(query);
        ...
    }
}

Or maybe you know some good alternatives for that?

My primary goal is to make code easily testable. While using proxies I can mock them off and make some assertions over the method calls or just return back some dummy data from them and assert the final results.

2 Answers2

3

That is absolutely the right way... partially.

Ideally you do not simply proxy your existing "Utility"-classes but make real Domain Objects. Those initially delegate to the statics but you can implement them the "new way" step by step.

That is, I would prefere a kind of facade pattern instead of the suggested proxy pattern.

M.F
  • 403
  • 2
  • 10
  • Good idea! I think I will initially turn some classes to proxies to keep things more convenient and later it will be easier to move towards facade instead. – Andrei Zhaleznichenka Feb 16 '18 at 11:47
0

PowerMockito can be used for mocking the static methods in your code. Instead of you creating proxies it would be done for you. PowerMockito mock single static method and return object

  • 1
    Yes, it is also a solution I was considering, but I find the usage of PowerMockito as quite complicated. Also I think it doesn't facilitate to create better code in the end – Andrei Zhaleznichenka Feb 16 '18 at 11:56