51
19

Functions are easy to understand even for someone without any programming experience, but with a fair math background. On the other hand, classes seem to be more difficult to grasp.

Let's say I want to make a class/function that calculates the age of a person given his/her birthday year and the current year. Should I create a class for this, or a function? Or is the choice dependant to the scenario?

P.S. I am working on Python, but I guess the question is generic.

  •  
    Classes are for bigger product. In simple terms, thinking of nut and bolt of a car as objects, while even car is an object too. If you are writing sample programs for fun, stick with functions. – Saran-san Aug 13 '13 at 7:17 
  • 1
    I wrote up my thoughts here – Toby May 1 '14 at 19:15

8 Answers

答えが見つからない?日本語で聞いてみましょう。

89
 

Create a function. Functions do specific things, classes are specific things.

Classes often have methods, which are functions that are associated with a particular class, and do things associated with the thing that the class is - but if all you want is to do something, a function is all you need.

Essentially, a class is a way of grouping functions (as methods) and data (as properties) into a logical unit revolving around a certain kind of thing. If you don't need that grouping, there's no need to make a class.

  • 4
    This is not exactly true. Classes also allow for dispatching on types. If you have a group or template of collaborating functions it may well be a one shot execution but nevertheless using a class buys you the possibility of selectively implementing different functions in the group in order to get specializations of the template. This is not so easily done by plain functions, because there is no type to act as a link between them and to allow specialization on subtypes... – memeplex Mar 1 '16 at 7:08 
  •  
    ... Forcing your logic, you can include the class functions (for example as a vtable) as part of the state or data of the instance. The functions themselves are not stored within the instance but some sort of indirect reference to them instead. So the bottom line is that you may have no data (besides a pointer to a vtable), you may have no more than an instance, but still a class could be a good idea if you need to implement a family of related algorithms consisting of collaborating functions. – memeplex Mar 1 '16 at 7:09 
  •  
    To summarize: a class groups functions and data. There is no benefit to this under any circumstance. We have functions and data types and modules to group them together. Even if you need adhoc function polymorphism: different function implementations for different data types, there are much better solutions than OOP classes; consider Haskell-style type classes which are ultimately language agnostic. – clay May 23 '16 at 15:46