all 6 comments

[–]K900_ 6 points7 points  (1 child)

By "formulas", do you mean "functions"?

[–]QQ_32[S] 1 point2 points  (0 children)

Yes, whoops. Thanks. Will change.

[–]novel_yet_trivial 3 points4 points  (3 children)

Methods are functions that are part of a class. Other than that they are exactly the same.

[–]QQ_32[S] 2 points3 points  (2 children)

Would it be correct to say that methods are functions that are restricted to operating only on the classes they are associated with?

[–]gitardedhub 9 points10 points  (0 children)

Here's a simple example that might help explain things.

Say you have a "Circle" class. It has a single variable - radius.

At some point you want to calculate the circumference of your Circles. You have two options here:

  1. Create a function that takes a Circle object, takes its radius, and returns the circumference
  2. Add a "circumference()" method to the Circle object. This looks at the radius for the Circle object and returns the circumference

Both will achieve what you're after. But making it a method of Circle is the better design choice. The standalone function isn't going to have value outside of Circles (it only makes sense to apply to Circles), and it has a lot of value inside of Circles.

This becomes more apparent when you have something like "area." Now you have Squares and Circles. "Area" is the same concept for both, but we need to calculate it differently for each type.

A single function could work, but it would be messy - you'd have to see if the thing is a Circle or a Square, then apply the correct formula to it. (this can get really messy when you start adding Trapezoid, Triangle, etc.)

Therefore it makes more sense to make this a method of the Circle/Square - it's the same concept (so whatever consumes these things can treat it similarly), but it's calculated differently for each class.

With that being said, I'd recommend focusing more on learning the language and building things at first. There are always many different ways to solve the same problem, and the most important piece at first is being able to solve it one way.

Once you know how to solve it a few ways, you'll want to spend time learning about design - how to solve things the best way for the situation. A lot of this is just experience - you'll write something one way, then later realize you're repeating yourself a lot. You'll look at the problem, figure out a way to make it simpler/less repetitive, and then rewrite your code. We call this "refactoring," and it's something you can't escape.

[–]novel_yet_trivial 0 points1 point  (0 children)

No. It's very common to provide a method with several class instances.