Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
utterances-bot opened this issue Nov 15, 2024 · 2 comments

Comments

@utterances-bot
Copy link

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/

Copy link

mqnc commented Nov 15, 2024

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.

Copy link

mqnc commented Nov 15, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants