class Foo {
constructor(value) {
this.value = value;
}
addOne() {
this.value++;
}
getValue() {
return this.value;
}
}
const foo = new Foo(1);
any worse than this POJO: const foo = {
value: 1,
addOne() {
this.value++;
},
getValue() {
return this.value;
}
}
Besides, what are models and controllers in React codebases, and why is using classes for one of these groups any better than for the other?I want move past the “bad OOP” stuff shoved down my throat 30 years ago, into a style that is more FP oriented.
I use [serializr](https://github.com/mobxjs/serializr) to convert json to my classes, and afterwards I can have all the deligtful methods I want. :-) I love the code clarity this gives, methods are where they are most logical, instead of on some helper object.
[1] https://github.com/typestack/class-transformer [2] https://github.com/typestack/class-validator
A few years ago there was a dilemma between ES6 and TypeScript. A lot of JS developers chose to stay away from TS in order to follow the ES6 path instead. Then TS harmonized with ES6. But it retained a reputation for being an incompatible alternative to ES6 rather than just JS+type annotations. However, if you write classes, they look just like ES6 classes plus type annotations, allaying concerns.
Could you elaborate on why you think that classes should be used when implementing controllers? I tend to think of controller classes as singletons, which kind of contradict using classes in the first place.
Why would you somehow pass objects around that are not "final"?
I mean the objects that get pinned here and there are specifically designed to serve as wrappers for some state, hence they encapsulate that state, and thus they are mutable. (For example a DB connection/manager object, a service registry, a cookie/localStorage repository.)
Where the immutability usually helps is with shuffling data around, parallel computing (concurrent access, no need to lock), etc.
If you’re used to classes, it’s really tempting to create classes for your models. But in Typescript, which gets compiled down to plain old JavaScript, you spend a lot of your time dealing with JSON and plain old JavaScript objects (POJO). These don’t have methods. These don’t have private members. These don’t have constructors.
You actually don’t need any of that. You just want type safety around your JSON and POJO. That’s why more often than not, you’re going to be using interface.
I’m not saying never use classes. But don’t use classes to define models. Use classes for controllers.