英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论