What The Heck are Collaborator Objects?

Eden Eltume
2 min readMar 3, 2019

--

Lately, I’ve been asking myself what exactly is a collaborator object and why is it even useful in object-oriented programming. I’ve turned to Youtube and Google for guidance but I’ve received little clarification. They have been increasingly less helpful as I dive deeper into esoteric/nuanced questions. But that’s a topic for another day.

You see, the purpose behind collaborator objects did not make sense to me until I came to the first problem in the hard section of OO practice problems. It might have been due to learning so many other things right before it such as inheritance, polymorphism, encapsulation, overriding, etc. Regardless, rereading the lecture on collaborator objects and Wendy Kuhn’s article No Object is an Island here helped. In this article, I hope to explain the gist of collaborator objects.

To go back to the original point, a collaborator object will make sense to you once you realize that a class can be designed to contain any type of instance variables. This means that instance variables don’t just have to be strings or integers but that they can be data structures such as arrays, or hashes. And if you guessed it, even objects of another class we’ve created. An object’s instance variables are its state and the object stored in an object’s state is known as the collaborator object. Why is this even useful? Well, it’s to help model a relationship. In particular, a has-a relationship.

As you may know, when we are inheriting from a parent class we are modelling an is-a relationship. For example a son is-a child of a parent. What if we have a person who has a pet (is not one himself), how would we model that has-a relationship in OOP? We would do it like this:

class Person
attr_reader :name
attr_accessor :cat #setter and getter methods for cat class

def initialize(name)
@name = name
end
end
class Cat
def initialize(name)
@name = name
end
def speak
"Meowwww!"
end
def clean_self
"Licks self.."
end
end
owner = Person.new("Owner")
cute_cat = Cat.new("Cutie")
owner.cat = cute_cat #sets owner's @cat instance variable to cute_cat#because owner.cat returns a Cat object we can then chain any Cat methods to it as well:
puts owner.cat.speak #=> Prints Meowww!
puts owner.cat.clean_self #=> Prints Licks self..

Now you get the gist of it. For further understanding be sure to reread the Collaborator Objects lecture and No Object is an Island article.

--

--

Eden Eltume

Stability is an illusion created by society to protect us from the chaos of the universe.