Reputation: 6563
I have the following problem. There's an interface called e.g UserExpactations
with a bunch of methods in a builder-style
to verify some logic.
Looks like this:
interface UserExpectations {
UserExpectations expectSuccessResponseFromApi;
UserExpectations expectFailResponseFromApi;
UserExpectations expectUserInDB;
// more user-specific methods
}
As you can each method return UserExpactations
so we can chain them together.
Now I need to add one more expectator class and there's some common logic, namely the first two methods.
So it's going to look like this:
interface OrderExpectations {
// these are common to UserExpectations
OrderExpectations expectSuccessResponseFromApi;
OrderExpectations expectFailResponseFromApi;
OrderExpectations expectOrderInCart;
OrderExpectations expectOrderInDB;
// some more order specific methods
}
I want to extract these common methods to abstract class or maybe another top level interface. And these methods should be implemented in one place. And each expectators
should be aware of their implementation. But the problem is that each common methods should return a specific *Expactations
type in order to keep that ability to chain methods.
Can't find a way how to implement this. Maybe is there a nice pattern which can help to facilitate this problem that I'm not aware of. Any ideas?
UPDATED:
So I wanted to create an abstract Expecations which will contain common methods:
Like this:
abstract class CommonExpactations<T> {
T expectSuccessResponseFromApi() {
// do some logic and then return T
}
T expectFailResponseFromApi() {
// do some logic and return T
}
}
And not each implementation of *Expectations specific interface should also extend CommonExpactations in order to get access to the common methods.
But java doesn't allow to create a new object of type T
in abstract class in order to chain some other methods in concrete implementations.
So for example,
UserExpectationsImpl implements UserExpectations extends CommonExpactations<UserExpectations>
Upvotes: 0
Views: 497
Reputation: 112
Try with anonymous object creation of abstract class.
abstract class CommonExpactations<T> {
T expectSuccessResponseFromApi() {
// do some logic and then return T
}
T expectFailResponseFromApi() {
// do some logic and return T
}
}
In Child interfaces of CommonExpectations, say UserExpectations
CommonExpectations ce = new CommonExpectations<UserExpectations>(){
//provide abstract method implementations
}
Upvotes: 0
Reputation: 14628
How about with generics?
public interface Expecations<T> {
T expectSuccessResponseFromApi();
T expectFailResponseFromApi();
....
}
public interface UserExcpectations extends Expecations<User> {
}
Upvotes: 1