Question

A while ago, I saw a Stack Overflow answer (I can't seem to find it now) that says functions and methods have different goals. A method is to change something within the instance, while a function is to change something about the instance. For example:

class Animal
{
  int hunger;

  void eat()
  {
    hunger += 2;
  }
}

void die(Animal& animal)
{
  animals.remove(animal);
}

So the method inside the class changes something within the instance, while the function is to change something about the instance. Another point of view would be animals don't kill themselves, so giving them the ability to do so wouldn't make sense, that's why it's a function.

Does this change for Procedural programming? Let's say there's a class/struct for an Animal. And there's a function kill_animal(). What should the function do? Should one of it's parameters be a single Animal and kill that, or should it take in an Animals array, and iterate through that array deciding which animal to kill?

For example, should I prefer this:

struct Animal
{
  int hunger;
}

void kill_animal(Animal& animal)
{
  animals.remove(animal);
}

for (int i = 0; i < animals.size(); ++i)
{
  if (animals[i].hunger <= 0)
    kill_animal(animals[i]);
}

Over this:

struct Animal
{
  int hunger;
}

void kill_animal(Array& animals)
{
  for (int i = 0; i < animals.size(); ++i)
  {
    if (animals[i].hunger <= 0)
      animals.remove(i);
  }
}

kill_animal(animals);

Or vise versa?

Was it helpful?

Solution

A method is to change something within the instance

Really? So "Hello".length() is trying to change the instance? No, a method uses the instance as its context. A context that in some languages it has privileged access to. It doesn't have to change anything.

a function is to change something about the instance

A function doesn't draw its context from an instance. A function doesn't even have an instance. It has whatever was passed, whatever is in scope, and (ick) globals.

But the problem with your last line, kill_animal(animals);, is mostly the name. This says it kills an animal without at all making clear which animal. It would read much better as kill_starving(animals);

Now sure, that could be made into a method: animals.kill_starving(). Which, aside from sounding like Yoda wrote it, works just as well. Both make clear that animals is going to be changed. But that comes from the name. Not the structure.

Procedural or OOP, the purpose of a function or method is to keep you from needing to repeatedly look inside to understand what is going on.

OTHER TIPS

Methods have an implicit parameter this while functions do not.

Therefore, methods can operate on the object to which they are attached. Functions can only operate on explicit parameters.

Apart from this, methods and functions are the same thing.

Licensed under: CC-BY-SA with attribution
scroll top