In a discussion about static and instance methods, I always think, that Sqrt()
should be a instance method of number types instead of a static method. Why is that? It obviously works on a value.
// looks wrong to me
var y = Math.Sqrt(x);
// looks better to me
var y = x.Sqrt();
Value types obviously can have instance methods, as in many languages, there is an instance method ToString()
.
To answer some questions from the comments: Why should 1.Sqrt()
not be legal? 1.ToString()
is.
Some languages do not allow to have methods on value types, but some languages can. I am talking about these, including Java, ECMAScript, C# and Python (with __str__(self)
defined). The same applies to other functions like ceil()
, floor()
etc.
Best Answer
It is entirely a choice of language design. It also depends on the underlying implementation of primitive types, and performance considerations due to that.
.NET has just one static
Math.Sqrt
method that acts on adouble
and returns adouble
. Anything else you pass to it must be cast or promoted to adouble
.On the other hand, you have Rust which exposes these operations as functions on the types:
But Rust also has universal function call syntax (someone mentioned that earlier), so you can choose whatever you like.