Currently I\'m working on a vector class in C# and now I\'m coming to the point,
ID: 644183 • Letter: C
Question
Currently I'm working on a vector class in C# and now I'm coming to the point, where I've to figure out, how i want to implement the functions for interpolation between two vectors. At first I came up with implementing the functions directly into the vector class...
public class Vector3D
{
public static Vector3D LinearInterpolate(Vector3D vector1,
Vector3D vector2, double factor) { ... }
public Vector3D LinearInterpolate(Vector3D other, double factor { ... }
}
(I always offer both: a static method with two vectors as parameters and one non-static, with only one vector as parameter)
...but then I got the idea to use extension methods (defined in a seperate class called "Interpolation" for example), since interpolation isn't really a thing only available for vectors. So this could be another solution:
public class Vector3D { ... }
public static class Interpolation
{
public static Vector3D LinearInterpolate(this Vector3D vector,
Vector3D other, double factor) { ... }
}
So here an example how you'd use the different possibilities:
{
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
}
So I really don't know which design is better. Also I don't know if there's an ultimate rule for things like this or if it's just about what someone personally prefers. But I really would like to hear your opinions, what's better (and if possible why ).
Explanation / Answer
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.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.