Usually, classes in JavaScript are presented like this:
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return this.calcArea();
}
calcArea() {
return this.height * this.width;
}
}
As a fan of functional programming and as someone who want to make code scalable, I am tempted to have like this for the whole app instead:
calcArea({height, width}) {
return height * width;
}
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
get area() {
return calcArea(this);
}
}
Basically transform classes into structures and make all methods with related functions abstracted. This way I can easily export the calcArea
function
Does this make sense, I would like to hear some thoughts on this, are there good articles about these architectures approaches?
Thank you
FP facilitates code sharing because it clearly separates the state from its transition logic. I'd suggest to think about whether you really need to add all this supporting code, or you could just work with state
and transitions
?
Wouldn't the following be just as fine? And possibly clearer?
const rect = { width: 100, height: 500 };
const toRectArea = (rect) => rect.width * rect.height;
const toTriagleArea = (triangle) => toRectArea(trianle) / 2;