In TypeScript app, we may have to process data in JSON form. Let's say we have following data structure.
{ "x": 5, "y": 20 }
We want to have distanceFromOrigin
function on above data. I think we can do it in two approach.
Approach 1
class Point {
x: number = 0;
y: number = 0;
constructor(init?: Partial<Point>) {
Object.assign(this, init);
}
distanceFromOrigin() {
return Math.hypot(this.x, this.y);
}
}
const jsonFromReqest1 = { "x": 5, "y": 20 };
const point = new Point(jsonFromReqest1);
console.log(point.distanceFromOrigin())
Above implementation looks nice. Downsides are:
- Needs constructor, which takes JSON and creates object. This will become complex when object has nested object and array.
- Every place we retrieve JSON object we need to make sure we call constructor and convert it into object.
Approach 2
interface IPoint {
x: number;
y: number;
}
const PointService = {
distanceFromOrigin(point: IPoint) {
return Math.hypot(point.x, point.y);
}
}
const jsonFromReqest2 = { "x": 5, "y": 20 };
console.log(PointService.distanceFromOrigin(jsonFromReqest2));
Above approach doesn't have downsides of Approach 1
. But,
- It doesn't feel object oriented.
- It is verbose, like we need to write
PointService.distanceFromOrigin
, a very long string.
Are there any other convenience
and/or downsides
apart from which I have mentioned, which indicates whether Approach 1
or Approach 2
is better.
Aucun commentaire:
Enregistrer un commentaire