你可以将一个通用参数设置为可空,还是应该创建两个接口?

huangapple go评论73阅读模式
英文:

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&lt;TResponse, TRequest&gt; {
Response&lt;TResponse&gt; 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.

huangapple
  • 本文由 发表于 2023年4月4日 18:16:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/75928169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定