有没有办法阻止客户端通过实例调用静态方法?

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

Is there a way to prevent clients from calling static methods from instances?

问题

基本上,我希望阻止我的工厂方法被链接调用。

也就是说,我不希望出现这样的情况:

> Circle.createCircle(x,y).createCircle(y,z).createCircle(1,2)

因此,我希望我的工厂方法只能从类中调用,而不能从实例中调用。

英文:

Basically, I would want to prevent my factory methods being chained.

Ie, I don’t want something like

> Circle.createCircle(x,y).createCircle(y,z).createCircle(1,2)

So I would like to have my factory method to be able to called from a Class only, not from instances.

答案1

得分: 2

不可能的;它已经内置在语言规范中,您可以从与静态方法所在类型相同的表达式中调用静态方法。

然而,不要担心这个问题。这是每个静态检查工具都会警告的事情。如果您试图使您的 API 防呆,宇宙将会合谋反对您并发明一个更好的白痴。您无法在这场斗争中取胜。要担心会导引您的用户误入歧途或需要不必要的复杂操作的 API 设计。不要担心试图阻止任何经过3周大学学习的程序员在随意一瞥中就能确定为显然不符合API意图或明确是粗糙代码的用法。

英文:

Not possible; it's built into the language spec that you can invoke static methods off of expressions of the type the static method is in.

However, don't worry about it. This is a thing every linter under the sun will warn about. If you try to make your API idiot-proof, the universe will conspire against you and invent a better idiot. You can't win that fight. Worry about API designs that lead your users astray or are needlessly convoluted to work with. Don't worry about attempting to stop usages that any coder 3 weeks out of uni can identify at a casual glance as clearly not how the API is intended or straight up crud code.

huangapple
  • 本文由 发表于 2020年10月16日 10:58:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/64382314.html
匿名

发表评论

匿名网友

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

确定