英文:
Can I set a generic argument as nullable or should I create two interfaces?
问题
I'm kinda new to generics in Java. I created an interface serving as a contract for all request handlers between my web layer and my domain layer (I'm trying to have one handler per use case instead of giant services). Here is the code of the interface:
public interface RequestHandler<TResponse, TRequest> {
Response<TResponse> Handle(TRequest request);
}
The "Response" type is a wrapper type that handles the state of any response from my domain (hasFailed, errorMessage, etc.). So my issue is that sometimes I'll have requests that might be empty (for instance a "GetAll"). Is it possible in Java to have a sort of constraint that will allow implementations to not have a TRequest or should I declare another interface for that?
Thanks!
英文:
I'm kinda new to generics in Java. I created an interface serving as a contract for all request handlers between my web layer and my domain layer (I'm trying to have one handler per use case instead of giant services). Here is the code of the interface:
public interface RequestHandler<TResponse, TRequest> {
Response<TResponse> Handle(TRequest request);
}
the "Response" type is a wrapper type that handles the state of any response from my domain (hasFailed, errorMessage,etc.).
So my issue is that sometimes I'll have requests that might be empty (for instance a "GetAll"). Is it possible in java to have a sort of constraint that will allow implementations to not have a TRequest or should I declare an other interface for that ?
Thanks !
答案1
得分: 1
我认为独立的接口是一个不错的主意。通过拥有一个独立的接口,你消除了返回类型应该是什么的不明确性。
我还会进一步强烈建议您不要听从@VGR的建议。不必要地使用java.lang.Void会使设计变得更加复杂,实际上,你只想表达没有返回类型。使用这种间接形式是引入难以发现的错误的好方法。
当你被迫遵循API约定而无法更改它时,Void是有意义的。但既然你现在正在主动创建终点,没有充分的理由在有机会变得更加清晰时引入它。
英文:
I think the separate interface is a good idea. By having a separate interface, you remove the haziness over what the return type should be.
I would also go further and strongly recommend that you do not follow the advice of @VGR. Using java.lang.Void needlessly complicates the design when really, all you want to say is that there is no return type. Using this form of indirection is a great way to introduce hard to find bugs.
Void makes sense when you are stuck with an API convention and have no way to change it. But since you are actively creating the endpoint now, there is no good reason to introduce it when you have the option to be even more clear.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论