2

Currently I'm coding a Vector class in C# and I'm coming to the point, where I've to figure out, how I want to implement a function/method to interpolate between two vectors. The (obvious) and also my first solution was to simply implement it as a method in the vector class itself:

public class Vector3D
{
    public static Vector3D LinearInterpolate(Vector3D vector1,
        Vector3D vector2, double factor) { ... }

    public Vector3D LinearInterpolate(Vector3D other, double factor { ... }
}

(I decided to offer both a static method with two vectors as parameters and one non-static, with only one vector as the parameter)

But then I got the idea to use extension methods (defined in a separate class called e.g. Interpolation for example), since interpolation isn't really limited to vectors only. So this might be another approach:

public class Vector3D { ... }

public static class Interpolation
{
    public static Vector3D LinearInterpolate(this Vector3D vector,
        Vector3D other, double factor) { ... }
}

And here is an example showing how one would use the different implementations:

{
    var vec1 = new Vector3D(5, 3, 1);
    var vec2 = new Vector3D(4, 2, 0);
    Vector3D vec3;

    vec3 = vec1.LinearInterpolate(vec2, 0.5); //1
    vec3 = Vector3D.LinearInterpolate(vec1, vec2, 0.5); //2

    //or with extension-methods

    vec3 = vec1.LinearInterpolate(vec2, 0.5); //3 (same as 1)
    vec3 = Interpolation.LinearInterpolation(vec1, vec2,
    0.5); //4
}

I can't really decide on which design is preferable. Is there a rule of thumb on how to implement methods/functions similar to the one above or is it rather a matter of preference? I really would like to hear your opinions on what's better and - if possible - why.

16
  • Only use extension methods when you want to extend a class where you do not have access to the source.
    – Wilbert
    Nov 11, 2013 at 9:22
  • @Wilbert: Yeah, thought that too, at first... But why don't use them? They seem to be a bit like syntactic sugar for me... Use the static helper method in the different class if you want and use it as an extension method if you like that more... Or would you say, that helper functions shouldn't be implemented in a seperate class? Would you implement them directly in the class it should offer the helper function? For exmaple: "Vector" class with "Normalize" helper method: Would you make a class maybe called "VectorMath" and implement it there or directly in the vector class?
    – user108376
    Nov 11, 2013 at 19:19
  • *if you're the designer of the library... Otherwise it could be difficult to implement them directly as members.
    – user108376
    Nov 11, 2013 at 19:57
  • 1
    But this article is saying something else: drdobbs.com/cpp/how-non-member-functions-improve-encapsu/… ... In fact it's C++ but I think this is also convertible to C# . This article say's, that every method, that can be implemented by only using the public interface of the class (and this works with "Normalize()") should be implemented as a non-member function. And this would be a reason to implement them static in a helper class. Now it's either about refuting this opinion (which i think i really estimable) or deciding if it would be "legal" to nake them extension methods...
    – user108376
    Nov 12, 2013 at 12:49
  • 1
    @Wilbert: In what sense is an extension method "essentially" a global? You import it like any other behavior, it's tied to only the types for which it makes sense, and there's no greater danger of introducing global state than with a regular method--and if you did, at least it would be better contained!
    – Phoshi
    Nov 12, 2013 at 13:36

3 Answers 3

0

Maybe it is that I come from Java, but I really don't like extension methods unless there is a good reason for it.

If you want to reuse the operation code, the solution should be composition. Create an Interpolator that operates over an IEnumerable<double> (unluckily, it seems that C# lacks an equivalent to java.lang.Number, so you can't make the class generic easily). I don't think it is a bad idea that your Vector class implements it, too.

For bonus points, make the class an interface that defines the operation and inject an instance of the interface in the object, so you can change the implementation (or even use other types of interpolations, if they match the method signature) at will.

4
  • Yeah, the MS-Documentation says that developers should use them rarely... But in fact, i think the extension-methods like I use them here, function as a kind of helper methods. So you may implement those functions as helper methods in a seperate class (and eventually namespace, to prevent "IntelliSense-Spam") and if you want, you can use them as member methods or instead as static helper functions. But it's kinda hard for me to figure out, if I should implement them as members inside of the class or as extension-methods... Is it right to misuse extension methods as helper methods?
    – user108376
    Nov 11, 2013 at 15:15
  • There's less emphasis on generic constraints on specific types in C#. You're more likely to want to constrain on things like IComparable and IEquatable, which will allow you to use both numbers and your own classes which implement the required behaviour.
    – Phoshi
    Nov 12, 2013 at 13:41
  • @Phoshi But IComparable or IEquatable do not force the instances to have defined the + or - operators, which are necessary for the interpolation logic. So using IEnumerable<IComparable> would not let the code to compile.
    – SJuan76
    Nov 13, 2013 at 12:45
  • @SJuan76 True enough in this case, though C# 4.0 brought the "dynamic" keyword type which is about what you'd expect. This sort of flexibility, but you're giving up some type safety. Constrain as far as you can with constraints and use dynamic typing and you can achieve what you want, but god help you if you make a class that fits the constraints and doesn't implement the operators.
    – Phoshi
    Nov 13, 2013 at 13:04
0

Don't use static classes, static methods (including extension methods) unless you really need them (maybe because of legacy code, or because you extend a .Net framework object).

A in-depth explanation of why static is bad can be found here.

For your Vector3 class, why don't you simply write a (non-static) class?

public interface ILinearInterpolation
{
     void Interpolate(Vector3 a, Vector3 b, double factor);        
}

Now you can write an implementation against that interface.

The alternative is to make Interpolate a member method - but you should try to keep the class interface simple, and small. Now, I agree that Vector and Matrix classes are a bit of an exception, because they have a larger inherent feature set than most other classes, as there are a lot of math things that you might need that a vector should be able to do; you mentioned Normalize() as an example in comments. Still, I feel that Interpolate should be in it's own class.

7
  • Ok, now I get what you want to tell me. This is also a quite interesting article.. And at the end, I agreed with the author that -5.abs() should be really another way to get the absolute value of a value.. But in fact another . Because someone is maybe more thinking like "Hm, I want the abs OF a value" . And with the "OF" I more likely connect a method like *.abs(int i) with an int as parameter and not a call onto an int like i.asb() . You could say "I want the "absolute valued" integer" ... That's why I want to offer both: A static and a non-static version of those "helper-methods"
    – user108376
    Nov 12, 2013 at 14:37
  • I know this tendency to want to make convenience versions of methods to use, I used to do this a lot. But now I feel that's bad - make a decision, do it a single way and use the one single way everywhere.
    – Wilbert
    Nov 12, 2013 at 16:23
  • So, it's me again and now I thought a long time about that article you linked in your answer. And now I got that "little" Question in my head, why it's then bad to use extension methods for my purpose. The author want's to write int1.abs() ? Could do that with extension methods... Sure, it's still kinda static, even if you call it onto an object, but Math.abs(int1) is too, and so I can't see any great disadvantage here. Essentially not, if you place the class with the extension methods in a different namespace..
    – user108376
    Nov 18, 2013 at 16:54
  • One of the main reasons why static is bad is because it makes the code that uses it untestable (or makes it much harder and uglier to test that code). If you use Math.* (a function of the .Net framework), it's different because you really don't want to write unit tests for Microsoft-provided classes. But you should write them for your own classes. And as soon as you do that, extensions methods and other statics are bad.
    – Wilbert
    Nov 18, 2013 at 17:16
  • In my opinion it's not about if microsoft does this, it's more about a clear style of code... Why should I implement e.g. "Normalize()" directly into the vector class, while the integer class doesn't implement "Abs()" as a member method? Maybe I don't get that really, because I'm still not sure if a vector is responsible for delivering his own normalization... In my opinion this is more suitable for another class (e.g. VectorMath) . And in fact you do need this class very often and at different places, so this would be a candidate for static. Generally I agree with you, that static should be
    – user108376
    Nov 18, 2013 at 18:50
0

I would use interface and generics (Vector2, Vector4 etc. should be able to use the same implementation) for the interpolation implementation class and then add an extension method to make the usage more clean.

public class Vector3
{
    //Implementation
}

public interface IInterpolation<T>
{
    T Interpolate(T first, T second, double factor);
}

public class LinearInterpolation<T> : IInterpolation<T>
{
    T Interpolate(T first, T second, double factor)
    {
        return first + ((second - first) * t);
    }
}

public static Vector3Helper
{
    public static Vector3 LinearInterpolation(this Vector3 vector, Vector3 other, double factor)
    {
        var interpolation = new LinearInterpolation<Vector3>()
        return interpolation.Interpolate(vec1, vec2, 0.5);
    }
}

Usage:

Vector3 vec1 = new Vector3(1, 1, 2);
Vector3 vec2 = new Vector3(3, 1, 2);

var interpolation = new LinearInterpolation<Vector3>()
var result interpolation.Interpolate(vec1, vec2, 0.5);

or with the extension method:

var result = vec1.LinearInterpolation(vec2 0.5);
1
  • Ok, this is an interesting concept too. But in fact maybe i wouldnt use generics, so you can avoid compiler errors and so on (e.g. a string couldnt be multiplied with another) and so i would clearly define which data types are able to be interpolated... For example you could let Vector2, Vector3, ... derive from a abstract vector class and implement a basic interpolation method for the abstract class.. But in my opinion a linear interpolation isn't really a class. It's more like an action (method) performed on a vector or an integer... So personally I wouldn't make an own class for it
    – user108376
    Nov 12, 2013 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.