The Welder
The Welder

Reputation: 1062

External library for which I have no implementation

I need to write a piece of code which checks a string coming back from a method call. The problem is, that I have no information or implementation about this method apart from its interface as below:

package com.company.name.library;

public interface FooService {
    String getBar(String fooBar) throws NotKnownBarException, NotKnownFooException;
}

In a completely separate package I want to write some code that uses this method. (Essentially I need this code to compile, not necessarily run)

Since I don't have the implementation, I can't instantiate the object on which to invoke the method call. Is it even possible to make this compile with such limited information? Or is there something that has to be done such that I can make the code compile and at runtime some kind of injection is performed so that the correct method call can be made when there will be an implementation available.

Upvotes: 1

Views: 138

Answers (1)

Bruce Adams
Bruce Adams

Reputation: 5589

All you should need to use this functionality is the interface definition. At some point the client for your piece of code has to pass in an object which implements this interface which you then use.

That you don't have to depend on a particular implementation is generally a good thing from a decoupling point of view. You do need one for running your code and unit testing it of course. For that you may need to create a mock implementation of your own.

Pseudo-Java-code as below (Disclaimer: Java is not my main language)

package com.company.name.yourpackage

class UsesFoo {
   // constructor
   UsesFoo(FooService giveMeAnImplementationPlease)
   {
   }

   String DoSomethingWithFoo()
   {
       return anImplementationIWasGiven.getBar()   
   }

   // state
   FooService anImplementationIWasGiven;
}

Depending on what the library is for it might be intended that you create your own implementation. In which case you can turn the example around and assume the library has classes like UsesFoo which need you to provide the implementation.

If the usage isn't clear then you should complain to whoever provided the library without sufficient documentation. If that is not possible for some reason you may also consider adding to it yourself so that others don't have to suffer.

Upvotes: 1

Related Questions