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

Viewed 40

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 Answers

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.

Related