When to use method over computed property setter and vice versa? - vue.js

When using Vue.js, when should you use a method or a computed property setter? There seems to be little distinction in the documentation, or numerous articles. Usually articles present computed property setters as little more than a footnote.
Given that both methods and setters accept parameters, is there a particular reason you'd use one or the other? As far as I can see methods would be all you need.
Edit:
This is literally not a repost because the linked SO answer contains the word setter once and only in vague passing:
computed properties are converted into a property of the Vue with a getter and sometimes a setter.
Great, so how does this elaborate on the subject of this post, when to use a SETTER vs a method?

Computed properties are cached so they can benefit you when it comes to performance. They do not work like methods, as they do not accept arguments.
I use them mostly to modify existing data or make it easier to access nested data.
The part about caching is something that can end up being a hassle. They will always cache unless their direct dependencies change. Properties within computed properties that are within controls blocks will usually not update the computed property(not seen as a direct dependency).
This is something you need to be aware of.
When using things like large v-for lists you will want to to take advantage of the caching ability of computed properties since unlike with a method you won't have to perform the logic inside of it over and over, unless the direct dependencies of the computed property change.

Computed properties should be used to display data relative to existing data. While methods should be used to do an action and/or change data.

Related

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.
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!
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.

What is the difference between watch and computed methods in vuejs

They both seem to do the same thing, and I can't tell when to use which
Computed properties are just like the data properties. The literal meaning of computed is 'calculated using given values'.
Just as the meaning suggests computed properties are a calculated result of its dependent values(in vuejs data properties, props)
for example:
data:{
lowerCase: 'abcd'
},
computed:{
uppercase(){
return this.lowerCase.toUpperCase();
}
}
in the above example the computed property uppercase is dependent on data property lowerCase. It converts(computes) the letters into uppercase.
whenever lowercase changes , so any template bindings using this computed property automatically update.
Watch properties are more general and in one way more powerful(bit expensive) to watch for changes in data properties.
You can perform complex functions, asynchronous tasks in watchers. The example given in the documentation is a good example of using a watcher.
Summarizing the differences:
Computed properties unlike watched properties should return a value.
computed properties are just like data properties and can be used
in template using {{ }} but watchers cannot be used. Watchers should perform logic to update the data properties which are used in the template.
Computed properties are basically “virtual” properties that are evaluated when they are first used. They will be automatically cached until changes in the component require a reevaluation of the property.
Watch properties are just a mechanism to detect changes in properties, allowing you to perform custom logic.
Since watchers are much more powerful, you can use them to do the same that computed properties do: Basically, you would watch all dependent properties and whenever a value changes, you would recompute the property and store it in the Vue instance’s data.
Unless you require complex logic, computed properties will already do this in a more declarative way: You do not need to listen explicitly on all dependent properties but rely on Vue to automatically detect which properties your computed property depends on. So you just declaratively state how to compute the computed property and don’t need to worry about something else. Computed properites also already come with a good caching mechanism, something you would have to do yourself with watchers.
See also the guide on computed properties and watchers. One example they give for watchers is a debounced service call that would load additional data.
In general though, the gist is: Try to use computed properties for everything. If it won’t work as a computed property, use a watcher.
Its difficult to express this more clearly than the doc
tldr; computed properties are reactive. Their output is cached, and automatically updates if anything used in the function changes. Changes flow out onto the page, without us needing to worry about when or why. watch is "imperative and repetitive". It runs when the thing you're watching changes, like a listener. You then are responsible for how the result is stored and used.
You can do everything with events, but you should try to move up the food chain if you can. Prefer computed to watch.

Simple setter function or set with a property?

Just curious to know what difference does it make if one uses a setter function or a property to set a value? Which of the above two should be preferred?
column.setWidth(10);
column.width = 10;
Well, that largely depends on what programming language you are using, or, in other words, whether it supports the concept of properties or not. However, lets look at the problem from a general perspective.
The very basic point of view is properties are just plain syntactic sugar, making reading and writing values to some assumed backing field easier and, which is the important point, defining a clear contract for your code's user. Assumed because there needs not be any backing field at all or they can be many.
The high-level semantic difference between a setter function and a native property setter can be thought as follows:
A setter function is primarily still a function, hence the reader assumes it executes certain action using its arguments; being actually a setter is then just a convention.
A native property setter is primarily a way to write a value into some assumed backing storage / into the backing object; there's no implied notion of executing an action even though the hidden implementation details of the setter may work like that.
Many practicle ramifications of using property accessors (getters and setter) were discussed in this question and its answers.
Prefer properties. Actually it depends on your language. If you develop Python that all attributes are public in Python.

In what cases should public fields be used instead of properties? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Public Data members vs Getters, Setters
In what cases should public fields be used, instead of properties or getter and setter methods (where there is no support for properties)? Where exactly is their use recommended, and why, or, if it is not, why are they still allowed as a language feature? After all, they break the Object-Oriented principle of encapsulation where getters and setters are allowed and encouraged.
If you have a constant that needs to be public, you might as well make it a public field instead of creating a getter property for it.
Apart from that, I don't see a need, as far as good OOP principles are concerned.
They are there and allowed because sometimes you need the flexibility.
That's hard to tell, but in my opinion public fields are only valid when using structs.
struct Simple
{
public int Position;
public bool Exists;
public double LastValue;
};
But different people have different thoughts about:
http://kristofverbiest.blogspot.com/2007/02/public-fields-and-properties-are-not.html
http://blogs.msdn.com/b/ericgu/archive/2007/02/01/properties-vs-public-fields-redux.aspx
http://www.markhneedham.com/blog/2009/02/04/c-public-fields-vs-automatic-properties/
If your compiler does not optimize getter and setter invocations, the access to your properties might be more expensive than reading and writing fields (call stack). That might be relevant if you perform many, many invocations.
But, to be honest, I know no language where this is true. At least in both .NET and Java this is optimized well.
From a design point of view I know no case where using fields is recommended...
Cheers
Matthias
Let's first look at the question why we need accessors (getters/setters)? You need them to be able to override the behaviour when assigning a new value/reading a value. You might want to add caching or return a calculated value instead of a property.
Your question can now be formed as do I always want this behaviour? I can think of cases where this is not useful at all: structures (what were structs in C). Passing a parameter object or a class wrapping multiple values to be inserted into a Collection are cases where one actually does not need accessors: The object is merely a container for variables.
There is one single reason(*) why to use get instead of public field: lazy evaluation. I.e. the value you want may be stored in a database, or may be long to compute, and don't want your program to initialize it at startup, but only when needed.
There is one single reason(*) why to use set instead of public field: other fields modifications. I.e. you change the value of other fields when you the value of the target field changes.
Forcing to use get and set on every field is in contradiction with the YAGNI principle.
If you want to expose the value of a field from an object, then expose it! It is completely pointless to create an object with four independent fields and mandating that all of them uses get/set or properties access.
*: Other reasons such as possible data type change are pointless. In fact, wherever you use a = o.get_value() instead of a = o.value, if you change the type returned by get_value() you have to change at every use, just as if you would have changed the type of value.
The main reason is nothing to do with OOP encapsulation (though people often say it is), and everything to do with versioning.
Indeed from the OOP position one could argue that fields are better than "blind" properties, as a lack of encapsulation is clearer than something that pretends to encapsulation and then blows it away. If encapsulation is important, then it should be good to see when it isn't there.
A property called Foo will not be treated the same from the outside as a public field called Foo. In some languages this is explicit (the language doesn't directly support properties, so you've got a getFoo and a setFoo) and in some it is implicit (C# and VB.NET directly support properties, but they are not binary-compatible with fields and code compiled to use a field will break if it's changed to a property, and vice-versa).
If your Foo just does a "blind" set and write of an underlying field, then there is currently no encapsulation advantage to this over exposing the field.
However, if there is a later requirement to take advantage of encapsulation to prevent invalid values (you should always prevent invalid values, but maybe you didn't realise some where invalid when you first wrote the class, or maybe "valid" has changed with a scope change), to wrap memoised evaluation, to trigger other changes in the object, to trigger an on-change event, to prevent expensive needless equivalent sets, and so on, then you can't make that change without breaking running code.
If the class is internal to the component in question, this isn't a concern, and I'd say use fields if fields read sensibly under the general YAGNI principle. However, YAGNI doesn't play quite so well across component boundaries (if I did need my component to work today, I certainly am probably going to need that it works tomorrow after you've changed your component that mine depends on), so it can make sense to pre-emptively use properties.

Explain to me what is a setter and getter

What are setters and getters? Why do I need them? What is a good example of them in use in an effective way? What is the point of a setter and getter?
Update:
Can I get some coding examples please?
A getter is a method that gets the value of a property. A setter is a method that sets the value of a property. There is some contention about their efficacy, but the points are generally:
for completeness of encapsulation
to maintain a consistent interface in case internal details change
More useful is when you need to add some logic around getting or setting, like validating a value before you write it.
A getter/setter is used to hide a private field from the publicity (you can avoid direct access to a field).
The getter allows you to check a provided value before you use it in your internal field. The setter allows you for instance to apply a different format or just to restrict write access (e.g. to derived classes).
A useful application of a getter can be some kind of lazy loading: The backing field (the private field that is hidden by the getter) is initialized to null. When you ask the getter to return the value, it will check for null and load the value with a more time consuming method. This will happen only the first call, later the getter will provide the already loaded value all the time.
Getters & setters separate interface (getter/setter functions) from implementation (how the data is actually stored).
Getters and Setters allow you to control how data members of an object can be accessed or changed.
In contrast, if you expose your data members directly to the user of the object, the user can change them at will, and the object wouldn't even know that they had been changed.
Don't want people to read a data member? Make the data member private, and don't write a getter that gives the value back. Don't want people to modify a data member? Make the data member private, and don't write a setter for it. Want to control the range of allowed values? Put that in the setter.
One question which might pop out of this is if using a method instead of a direct field access might decrease performance.
Answer is not really as compilers optimize code so that if your method is only doing return field;, where field is the field in your class that you hide with the setter/getter, it will actually access the field directly. Thus you get in most cases the same performance, at the same time keeping the option of later on change what set/get methods do.
Effective Java Programming of Joshua Block is a great book with tips on how to write good code, and explains why as well. Why using setter/getter is one of the hints.
Note: You might notice that in some books/documentation fields that present a setter/getter instead of being directly accessible are called 'properties' instead of fields. E.g. in C#, you can even specify that a field is a property and you don't need to define set/get anymore (nice feature I think).
public accessors(getter and setter) make sometimes sense.
(I'm annoyed that I have not only to document the member variable of a class but also the 2 mostly meaningless accessor methods. )
It usually doesn't help with encapsulation except in cases mentioned by Jason S.
An java example for some char loaded from a database but should be represented as a boolean value
char boolFromDb;
public boolean getBoolFromDb() {
return boolFromDb == 'T';
}
public void setBoolFromDb(boolean newValue) {
boolFromDb = newValue ? 'T' : 'F';
}