Search code examples
javalistgenericscompatibilitylegacy

How to work with non generic lists


I have to work with an older Interface specifying methods with bare List parameter.

void updateParameter(List param1, List param2);

Obviously I need to implement them with the same signature.

@Override
public void updateParameter(List param1, List param2) {
    updateParam1( param1 );
    updateParam2( param2 );
}

But what about new code? Should I keep working with these old Lists. Should the new method's signature take generic Lists?

private void updateParam1( List<String> param1 ) { ... }

Should I explicitly convert/cast them?

What are the best practices here?


Solution

  • I personally stick to the philosophy of "Don't let defects get passed down stream". Somewhere, an unsafe type cast MUST happen (even if it is done under the hood by the compiler). Why not do it as early as possible? That way the code downstream can be clean and you only have the problem in one place instead of scattered throughout your code base. This also follows the principle of "fail fast".

    @Override
    public void updateParameter(List param1, List param2) {
    
      List<String> param1TypeSafe = (List<String>)param1;
      List<String> param2TypeSafe = (List<String>)param2;
      updateParam1( param1TypeSafe );
      updateParam2( param2TypeSafe );
      //now nowhere else in the codebase needs to deal with it.
    }