Jump to content

The ultimate community for Ruby on Rails developers.


Photo

What are the differences between Class and Instance Methods ?

rails ruby class methods instance methods

  • Please log in to reply
4 replies to this topic

#1 jim_2002

jim_2002

    Signalman

  • Members
  • 13 posts

Posted 05 March 2014 - 04:07 AM

After Googling and searching, I still don't get what are the differences between Class and Instance Methods ? and when to use Class or Instance Methods ?  Also, what are the differences between methods in a Controller or a Model ?

 

Can someone explain these to me with examples please ?

 

Thanks very much



#2 Ohm

Ohm

    Driver

  • Moderators
  • 479 posts
  • LocationCopenhagen

Posted 05 March 2014 - 04:07 PM

The difference is really who uses it and how.

 

A class method is a method defined on the class it self.

In Rails, scopes are a clever way of using class methods.

 

Say we have a User model (class), with names and if they are activated or not:

class User < ActiveRecord::Base
  attr_accessor :name, :active
end

Now, instead of creating a scope the regular Rails way, lets do it as a class method:

class User < ActiveRecord::Base
  attr_accessor :name, :active

  def self.active_users
    User.where(active: true)
  end
end

Now we are able to call User.active_users and grab all the active users.

We did this without knowing about a specific user. Instance methods are defined on specific objects.

 

The attr_accessor is a short cut for these with regards to getters and setters. Instead of attr_accessor we could do:

class User < ActiveRecord::Base
  def name
    read_attribute(:name)
  end
  
  def name=(new_name)
    write_attribute(:name, new_name)
  end
end

These are defined on an instance of the User class. In order to call it, we need a user. In Rails we can get the first user, by calling the class method first on the User class. Then we can change the name with the instance method. 

User.first.name = 'Mads'

---

 

Does this make sense? Just shoot if you have additional questions.


Blog: http://ohm.sh | Twitter: @madsohm | Work: Lokalebasen.dk


#3 james

james

    Guard

  • Members
  • 223 posts
  • LocationLeeds, U.K.

Posted 07 March 2014 - 04:06 PM

To add to Ohm's answer

A class is a description of a "thing"

An instance (or object if you prefer) is an actual thing.

Using a car as an example

A description of a car might be model, make, engine, fuel consumption, fuel type, top speed, registration number etc...

A description applies to all cars but an instance of a car applies only to one specific car

You might "buy" a car. You can't ask an instance of a car to buy itself as it doesn't exist yet, you have to create a car from a car class to get an instance (@car = Car.new)

the "new" method has to be a class method simply because the car hasn't yet been made. (What you you do @car = what???. @carsomething?) The "new" method needs to make the car for you and hand it over for you to do what you want with it within the bounds of the classes restrictions

 

But the car hasn't yet been saved and you have the job of describing what the car should be so you could give the make a value of "Ford" and the model a value of "Mondeo" and fill the rest of fields.

These are all properties of a Car class.

Now you can tell @car to do something like start up, you can find out how fast the car is travelling, what color it is, etc... It's no good asking a Car class what colour it is as the class doesn't know but you should be able to ask the Car class what colours are allowed and get a list back so you can choose the colour you want when you are creating it. Of course the Car class should reject invalid values before being saved.

 

Once saved you can get that instance anytime you like, you can determine how old it is simply by comparing the current date with the date it was created, you could create a class method that gets all cars over a certain age but it's no good asking @car (the instance) to get you a list of cars, why on earth should your Ford Mondeo need to know anything about other ford Mondeos' there are tens of thousands of them on the road.

 

In other words the distinction between a class and an instance is just that. There are things you can do with an instance that it doesn't make sense to do on a class and vica versa.

Put simply

A Ford Mondeo might come in different colours, engine sizes etc...

These are all related to a car's class

You might own a ford mondeo and the mondeo you own would be an instance of the car class


Programming is just about problem solving!

#4 jim_2002

jim_2002

    Signalman

  • Members
  • 13 posts

Posted 08 March 2014 - 12:02 AM

Thank you very much for the replies.

 

So basically,   Class methods call on everything of that class and Instance Methods call on specific things of that class?



#5 james

james

    Guard

  • Members
  • 223 posts
  • LocationLeeds, U.K.

Posted 08 March 2014 - 02:41 AM

That's pretty much it!

It may help to think of a class as being the blue print or factory for a specific thing or object or instance and the thing/object/instance as being just that, an actual object,

So a kettle class describes what a kettle is, it knows all about how to make kettles, how many kettles have been made, it can find kettles and give them to you but it can't boil water, that's the job of the actual physical kettle.

 

So if you want to make a cup of tea, first you must either find an existing kettle or create a new one, you go to the Class for this. Then when you have an actual kettle you can use the fill_with_water method, followed by the plug_it_in method followed by the switch_it_on method. Your job as an OO programmer is to design these methods and properties and make them work at the same time as making sure that the kettle doesn't blow up and can't boil dry so when you write the fill_with_water method you must think about raising an error if the kettle is plugged in and how to handle that error. Is it the responsibility of the user to make sure the kettle is unplugged before filling or is it the responsibility of the method?

 

Methods should be discreet and simple. The fill_with_water method should do just that and not care about anything else. The same goes for the plug_in and un_plug methods.

in an OO design you might want to protect things like these methods from the outside world and provide a boil_kettle method that is public to the outside world that calls the un_plug method then calls a fill_kettle method then the plug_in method and then the switch_on method, periodically checks to see if boiled then calls the switch_off method and sends a notification back to the user that the kettle has boiled.

 

As you can see, even the simplest of tasks require a huge amount of thought and planning. In the above example you would need some form of background process and some polling or notification system or call back to the user, you would have protected and public methods but you are giving the outside world a very simple solution. If the kettle doesn't boil you are only concerned about a bug in the kettle not a bug in the cup or the sink classes. If you want to change how a kettle boils to make it boil faster you have complete control by adjusting the boil_kettle method or any of the methods it uses without having to teach the user how to use the new kettle as the user just continues boiling a kettle as always they just notice that the kettle boils a little more quickly

 

The difference between an OO approach and a non OO approach is that a kettle is re-usable.

If you wrote all your code in say a controller action to boil a kettle to make a cup of tea, you would have to duplicate that code when you want to make a cup of coffee and then again when you want to boil some water to make some gravy etc..., by writing a Kettle class all those methods are written only once and used everywhere. More code means more maintenance and more bugs and time is money therefore non OO projects are more expensive than OO projects in the long term despite a greater time spent planning.

 

You may find this http://www.codeproje...sign-Principles an interesting read. It is an extremely good, well thought through and in depth article on how to approach OO design. It may be a little heavy for you at this stage of your learning curve but well worth bookmarking for future reading if it goes over the top of your head right now.

 

Before starting any project get lots of paper and a pen, scribble things down, draw diagrams rip it up and start again over and over until the light bulb switches on and you know exactly what needs to be done and you can focus on how to make the code do what you have designed rather than making the design do what you know how to code.


Programming is just about problem solving!





Also tagged with one or more of these keywords: rails, ruby, class methods, instance methods

0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users