« back

Cookies vs Cookie Cutters- Objects and Instances

11 Sep 2012

It turns out, my understanding of objects has been half baked.

When you create classes, it is like making cookie cutters. Just because you have a cookie cutter that can stamp out cookies though, you do not have a cookie. This is where I was getting confused. I was not realizing that a class in itself is not inherently an instance of itself. You have to use the cookie cutter by stamping it into some dough in order to have a cookie. This cookie then is an instance.

An object is an instance of a class. If CookieCutter is the class, you could say x = CookieCutter.new, this would create a new CookieCutter instance. x becomes the reference to that object.

Even though this it pretty basic, it is powerful and important to get the connection right, especially, I find, when dealing with objects that create new objects inside of them when you are dealing with testing. This is where I realized I had the misunderstanding.

For example, when you have a class, let's say Messenger, and inside Messenger there is a method that looks like this...

1         def save
2            @game.save
3         end
4     

Say you are writing a test for the save method. In rspec your code looks like this...

1        describe 'Messenger' do
2 
3          let(:messenger) { Messenger.new }
4          
5          it "should save a game"
6             messenger.save
7          end
8     

In this case, there is no game that has been created. We could do something like this...

1        describe 'Messenger' do
2 
3          let(:messenger) { Messenger.new }
4          let(game)       { Game.new }
5          
6          it "should save a game"
7             messenger.game.save
8          end
9     

or you could change the code to be like this...

1             def initialize
2                 @game = Game.new
3             end
4             
5             def save
6                @game.save
7             end
8         

Wasn't that fun!

comments powered by Disqus