Java: Is there use to refactoring/decoupling if only one class will use the new class?

234 views Asked by At

Code:

public class Name {

private String[] name;
private String first;
private String middle;
private String last;
private String suffix;


public Name (String fullName) {
    //Name is parsed in constructor 
    parse1();
    parse2();
    parse3();
    //invoking more parse methods...
}

private void parse1() {}
private void parse2() {}
private void parse3() {}
//more parse methods...

Those methods below the constructor help parse the fullName. I want to move these parse#() methods to another class, say NameHelper.class and make everything there public static but something inside me says that it's useless to refactor like that since not other class but Name will use it.

I do want to refactor because later on, this would be really difficult to unit test. But I don't want to sacrifice testing with ease vs. bad code refactoring because I could always use PowerMockito to test privates.

2

There are 2 answers

0
GhostCat On BEST ANSWER

One thing that always helps is looking into responsibilities. A Name is first of all ... a Name.

Parsing strings to create a Name to me looks like a responsibility that doesn't necessarily belong into that Name. It is actually more of a associated "helper" or maybe "Service" functionality.

In that sense, just create that package protected additional class and move the parsing code in there.

But for the record: I would not make things private to then turn to the Powermock hammer in order to get it tested. Especially code that is really so input/output based; why would you need mocking in the first place?

What I mean: this sounds like you have ingoing strings, and as a result of that, you receive some Name object. Thus: your unit tests have some test input data, instantiate that NameParserService; and then check for correct output. No need for any kind of mocking/stubbing in that!

0
Jackson Thompson On

If you feel that makes your code is better, refactor. No reason I can see not to put them in another class. It may make it more readable as well. If you are not trying to get to the instance variables there is no need to put these methods in there. You might want to make them protected and put them in the same package or default (packet-private) access.