15: Why are Methods Important-I don't quite get it


#1

I read through this post and I didn't quite understand why methods are important. The explanation states:

  1. They can be used to change object property values. The method setAge on line 4 allows us to update bob.age.
  1. They can be used to make calculations based on object properties.
    Functions can only use parameters as an input, but methods can make
    calculations with object properties. For example, we can calculate the
    year bob was born based on his age with our getYearOfBirth method (line 8).

I understand how these situations work. What I don't quite get is how these benefits/uses are specific to methods.

I played around with the code and I was able to replicate the effects of benefits 1 without using the method setAge. Can't one simply input
bob.age=X;
to change his age. Why is a method required for this?

For the 2nd one, I see that getYearOfBirth can be more convenient, but I didn't think this was necessarily a great example of how methods can be used for calculations using object properties as in this instance, one could also say
console.log(2014-bob.age);
instead of console.log(getYearOfBirth);

I was wondering if anyone could suggest a more poignant example(s) of how a method can calculate the object properties. I'm trying to think how this might come into play effectively, but not quite seeing the bigger picture.


#2

The idea with methods is that an object should handle its own internals.
This means that other code that uses the objects doesn't need to know how they work, only how they can be used - much easier! It also means that it's easy to change the internals of the object, because no other code will be relying on it working in a certain way internally.

For example, a Circle class (not a JS term perhaps but whatever, we're talking OO in general here) could have an area() method - outsiders don't need to know that this involves PI, nor do they have to multiply PI by .. well, I don't even know, I'd have to google, how embarassing, but I shouldn't need to anyway, that's up to the Circle class.

And if the Circle class would rather store its size as the radius instead of its diameter, then it could do that, because nobody is accessing that internal representation anyway.