Search code examples
javaarraylistloose-coupling

java Loose Coupling avoid using implemnetation types like 'ArrayList'; Use the interface instead


WE have this app for coding standards called Sonar. I have this one function that returns an ArrayList and sonar is says "java Loose Coupling avoid using implemnetation types like 'ArrayList'; Use the interface instead"

For example if i do this, sonar gives that error.

    public ArrayList<String> test()
       {
       ArrayList<String> testing = new ArrayList<String>();
        return testing;
        }

I am not sure how to correct the sonar message to use an interface instead.

Any suggestions would help.


Solution

  • You return a List<String> instead of ArrayList<String> :

    public List<String> test()
    {
        List<String> testing = new ArrayList<String>();
        return testing;
    }
    

    The advantage of this approach is that users of the test() method won't have to know which implementation of List<String> you are actually using, and you'll be able to switch to a different implementation without changing the API of your method.