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?