On Tuesdays at CronDose we talk about coding interview strategies and today we’re going to discuss the difference between class and instance methods.
I’m a Ruby developer and this episode’s answer will be addressed from the Ruby perspective, however it’s a concept that can be important to know in other languages as well, for example Objective C and Java have class and instance method options.
So what do you do when the interviewer asks the difference between class and instance methods?
From a practical perspective a class method can be called by itself, for example, if you had a class that handled sending SMS messages, you could call the class method by itself and simply pass in the values that you want to send in the SMS message.
An instance method is a function that requires an instance of the class to be created. In the SMS example we didn’t need to create an SMS instance, we only cared about the system sending the text message. An example of an instance method would be something like a full name method in a Customer class. If you want to know the full name of a customer you most likely have a customer in mind and Already instanciated the class into an object with a specific Customer selected.
In summary, I typically use instance methods since I’m usually calling methods on objects, class methods are helpful from time to time, but in many cases they can be a sign of poorly constructed code since many class methods could be refactored into modules and out of classes.