1

I have a class that process a string and does many actions on it turn by turn.

Those actions need to be done in a specific order.

Example:

public String process(String stringToProcess) throws Exception {

    processedString = process1(processedString);
    processedString = process2(processedString);
    processedString = process3(processedString);
    processedString = process4(processedString);
    ...
    processedString = process10(processedString);
    ...

    return processedString;
}

I'm sure there is a better way to refactor this to make it cleaner, but most of all, I want to be able to unit test process1, process2 etc.

Note that process1, 2 etc... can be whether 2 line methods or big ones.

I would need the process methods to be somehow public to test them. Is there a design pattern that would achieve this?

I thought about using enums to achieve this, but I thought it was somehow making it more confusing. This implementation is not the best for sure, but at one glance, you know what's happening.

Edit: This approach is not too bad to me, but all the process methods should be private. And I want to unit test them. I saw this question, so I can test them even if private, but the first step is to make sure it couldn't be done better.

Community
  • 1
  • 1
dyesdyes
  • 1,147
  • 3
  • 24
  • 39

2 Answers2

1

You may take a look at http://www.codeproject.com/Articles/455228/Design-Patterns-3-of-3-Behavioral-Design-Patterns#Chain But maybe it's a kind of overkill for your task.

What I would do is to extract process1, process2 etc to separate classes. Then you can a) test them with unit tests separately b) inject them into your class and use them in process method in necessary order.

Take a look also to this post: Design Pattern for a multi-step algorithm Maybe you will get some ideas from there.

Community
  • 1
  • 1
Andrej Istomin
  • 2,527
  • 2
  • 15
  • 22
0

you can specify your "private" methods as package protected. Only classes on same package (but from different source folders, like src/main/java and src/test/java or ... from different projects) can access to theses methods.

private void myPrivateMethod(){}

would becomes

/*no visibility keyword for declaring a method package protected*/
void myPrivateMethod(){}
Max
  • 511
  • 8
  • 18