Luis Rodriguez
Luis Rodriguez

Reputation: 277

When to use getters

So I know getters are primarily used to return state data that is manipulated in some way but is it best practice to create a getter if you just want to return the state value itself without mutating or anything?

I don't think it necessarily saves any code, if anything creates more, by creating a getter to return all the values I need.

Upvotes: 1

Views: 77

Answers (2)

Ramin Zaghi
Ramin Zaghi

Reputation: 81

Where I have the option, I personally always prefer getters (and C#-style properties) over direct memeber variable accesses be it internally from within the same class or externally from outside the class for two different reasons:

1- They are great when debugging “access points” (for example if you had to monitor who accesses a member variable and when then you just put a print or a breakpoint in the getter instead of doing loads of searching in your code)

2- If in the future you need to change the way a member variable is defined and/or used then getters give you a single point of focuse/change which can be changed to reflect changes in the definitions and meanings of the actual backing member variable

Note the same applies to setters too. In C++ it is not that common practice but I don’t remember the last time I did not use getter/setters for something!

Hope this helps!

Upvotes: 2

mika
mika

Reputation: 1451

Getters are essentially good for derived states: https://vuex.vuejs.org/guide/getters.html

It's also a good practice to maintain your getters in the same place and use mapGetters in your reactive components.

Upvotes: 1

Related Questions