0

I know that changing private method's sign with public ignore encapsulation principle. In addition, private method is an implementation detail. But I wonder that if the method does not effect or break other part of system, can i make the method's signature public?

For instance;

I have a method which contains switch-case block;

private Object foo(Object object, MyTypeEnum type) {
    ....
    switch(type) {
      case type.x:
         return "a";
     case type.y:
         return "b";
     case type.z:
         return "c";
     .
     .
     .
  }
  ..
 }

In addition;

  • Moving the method in utils class to be able to make its sign public is bad practise since the method is not generic and reusable
  • Testing a public method which calls the private method(foo) is one of solutions. However, my codebase has a lot of legacy and untested code so i have to change other classes and methods. Furthermore, I have no enough time refactor other part of my codebase.

What do you advice to me for this case ?

burak isik
  • 395
  • 5
  • 6
  • Of course you can, with the caveat that once it's public, it's public. It's already a suspect method because it returns `Object`. The questions are 1) *should* you, 2) are there *other* tests (unit or integration) that already test this behavior, and 3) is the ROI of testing this worth it. There are no general-purpose answers to those questions; it depends highly on context. (Unrelated, but a `break` after a `return` is redundant and pointless.) https://www.artima.com/suiterunner/private.html – Dave Newton Aug 18 '20 at 18:27

1 Answers1

2

You already know this isn't good form but trying to test working but untested legacy code is not a good investment of time generally because of these exact reasons. You don't want to spend ages remodelling the old stuff just to add tests; It actually increases risk of something unexpected happening in production. See Adding unit tests to legacy code

In such circumstances I always try to test at a higher level rather than individual methods in individual classes.

drekbour
  • 2,895
  • 18
  • 28
  • Totally agree. Is that a monetized link to Amazon? – drekbour Aug 19 '20 at 14:21
  • Turns out it is! Just not your money. https://meta.stackoverflow.com/questions/388746/links-to-amazon-com-are-converted-to-rads-stackoverflow-com – drekbour Aug 19 '20 at 14:48
  • I have now removed that link. And here is my message: and make sure you always have this a copy of "working with legacy code" within reach when you need to work with legacy code – Jocke Aug 19 '20 at 15:12