effective-typescript icon indicating copy to clipboard operation
effective-typescript copied to clipboard

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

Open utterances-bot opened this issue 1 year ago • 2 comments

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/

utterances-bot avatar Nov 15 '24 10:11 utterances-bot

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 avatar Nov 15 '24 10:11 mqnc

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.

mqnc avatar Nov 15 '24 10:11 mqnc