Hey guys, sorry for my English fist, I make this post for core team of Babylon.js with the request to refactor most of the code of Babylon.js base classes to keep functions uniform and minimize duplicate code (so it can let Babylon weigh less).
For example look at this code, we have 3 almost the same functions:
/** * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2 * @param otherVector defines the other vector * @returns a new Vector2 */ public subtract(otherVector: Vector2): Vector2 { return new Vector2(this.x - otherVector.x, this.y - otherVector.y); } /** * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates. * @param otherVector defines the other vector * @param result defines the target vector * @returns the unmodified current Vector2 */ public subtractToRef(otherVector: DeepImmutable<Vector2>, result: Vector2): Vector2 { result.x = this.x - otherVector.x; result.y = this.y - otherVector.y; return this; } /** * Sets the current Vector2 coordinates by subtracting from it the given one coordinates * @param otherVector defines the other vector * @returns the current updated Vector2 */ public subtractInPlace(otherVector: DeepImmutable<Vector2>): Vector2 { this.x -= otherVector.x; this.y -= otherVector.y; return this; }
that’s all functions that make subtract operation of Vector2, but if we look at another operations, we’ll find more combinations. For example:
/** * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats * @param x defines the first coordinate * @param y defines the second coordinate * @returns a new Vector2 */ public multiplyByFloats(x: number, y: number): Vector2 { return new Vector2(this.x * x, this.y * y); }
But we don’t have a function subtractByFloats
I suggest using a method of generating functions to create repeating logic in functions of the same type:
For example it may looks like this (the code is not working and is provided for understanding only.)
subtract(otherVector: Vector2): Vector2 { return new Vector2(this.x - otherVector.x, this.y - otherVector.y); }
subtractToRef(otherVector, result) = makeToRefFunc(subtract, otherVector, result)
subtractInPlace(otherVector) = makeInPlaceFunc(subtract, otherVector)
I think it’s better keep ToRef
function as base, from it is easiest to do all the rest.
Look at the code of TWGL
it was made almost the same way.