Are destructed (modified) objects always the receiver when traced back to the most primitive method?

StackOverflow https://stackoverflow.com/questions/22167372

  •  31-05-2023
  •  | 
  •  

Вопрос

Some methods are destructive on the receiver. For example, given an array a and an objectb, applying the method Array#push as a.push(b) modifies a, but not b. We can wrap this in another method:

class Object
  def into a
    a.push(self)
  end
end
b.into(a)

so that this time, not the receiver b but the argument a is modified. Nevertheless, Object#into internally calls Array#push, so that when we trace the internal process (within Ruby implementation), we can say that, ultimately, the modified object a is the receiver in this case as well.

Are all cases of destruction (modification) ultimately traceable to a method where the modifee is the receiver?

If so, what is making it so? Is it for the sake of C-implementation, or does it follow from object orientation, or is it just coincidence?

Это было полезно?

Решение

It isn't necessarily that way, but it is conventionally that way. The reason is that each object is meant to be responsible for handling its own state. Having a message to an object leave that object the same but modify another object generally goes against that principle.

This is an old OO idea. You don't modify objects — instead, you ask them to modify themselves.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top