C# – Instance vs Static methods for multiple variable methods

cnet

If you have a Point3 class and have a method called Distance, should you have it static like this:

Point3.Distance ( p1, p2 );

or an instance method like:

this.Distance ( p );

I realize using static methods hinders inheritance and overriding, right?

Which one is better, and why?

Best Answer

I prefer the static version. (And this is what we've done across the board in SlimDX, save for a few "special" operations.) The reasoning is that Distance is conceptually a function that processes two points, and has a result. You're not running the "Distance" operation on p1, with p2 as the value.

In short, I prefer that instance methods are conceptually an operation bound to a specific instance. For some, it goes either way. For example, SlimDX includes both static and non static versions of the Vector3 Normalize function, because both constructs are pretty handy. The instance one modifies its object, and the static one returns a new one.

[Edit] Another answer mentions a "DistanceTo" function that would be an instance function. While that's not necessarily unreasonable, it's a design direction that makes me uneasy. The problem is orthogonality. Once you add more of these overloads -- some static, some instance, maybe some in a MathHelper class, who knows -- you end up with more and more ways to do the same thing. This is bad news for library complexity, test complexity, bug surface area, etc. We've chosen to do it in places in SlimDX, but that's in just a select few places across a lot of classes (and every single one's been team reviewed). It can help usability of a library to an extent, but it's really dangerously easy to end up on the wrong side of the line.