danvk / effective-typescript

Effective TypeScript 2nd Edition: 83 Specific Ways to Improve Your TypeScript
https://effectivetypescript.com
Other
1.56k stars 229 forks source link

Don't Write Traditional Getter and Setter Methods in JavaScript and TypeScript #40

Open utterances-bot opened 12 hours ago

utterances-bot commented 12 hours ago

Don't Write Traditional Getter and Setter Methods in JavaScript and TypeScript

Effective TypeScript: Don't Write Traditional Getter and Setter Methods in JavaScript and TypeScript

https://effectivetypescript.com/2023/12/31/getters-setters/

mqnc commented 12 hours ago

I've been bitten hard by getters and setters. https://stackoverflow.com/questions/79186930/leaky-abstraction-with-setters-and-getters-in-js-ts The problem is that they look like a function on the inside but like a simple property on the outside. If get x() returns a dynamically generated object instead of just a number, that looks like a simple field and pt.x.imag = 7 seems totally fine. If I have to call pt.getX() I would be more inclined to investigate whether this actually returns a real reference that I can mutate.

mqnc commented 12 hours ago

Another problem with TypeScript and getters/setters is, that it does not complain if an interface requires a field and the implementation only defines a getter or a setter and not the other one. This can introduce bugs that could have been captured during compile time but will actually emerge during runtime. Bottom line: I advise against setters and getters. They feel nice and practical and probably are in the simplest cases but they can also be tricky and it's hard to tell where the line is.