Is Julia's way of OOP superior to C++/Python? Why Julia doesn't use class-based OOP?

From a syntactic point of view, the main difference is if the functions that act on objects are part of the object or not. In some cases one thing is more natural than the other, in other cases it is the contrary. For example:

julia> mutable struct Person
         name
         height
         position
       end

julia> me = Person("Leandro","1.80",0.)
Person("Leandro", "1.80", 0.0)

julia> function displace!(p,Δx)
         p.position = p.position + Δx
       end
displace! (generic function with 1 method)

julia> displace!(me,2.)
2.0

julia> me
Person("Leandro", "1.80", 2.0)

The name and height are properties of me, and that makes sense. The displace! function acts on the the person, changing its position. That also makes sense. In a typical OO syntax, one would call something like

me.displace(2.0)

which is somewhat odd, I think. However, in other cases the natural way of thinking would favor this construct. For example:

julia> function walks!(p,Δx)
         p.position = p.position + Δx
       end
walks! (generic function with 1 method)

julia> walks!(me,2.0)
4.0

julia> me
Person("Leandro", "1.80", 4.0)

The function does the same, but now walking seems to be naturally a property of the a person, thus it could sound natural to call:

me.walks(2.0)

as in typical OO syntax.

Thus, it is not about what you can do, but how natural things look like at the end. In some cases the OO syntax looks more natural, in other cases the functional syntax is more natural. In math, in general, functional forms are more natural, I think, but it might be more natural to write in OO style if you are dealing with buttons, icons, etc, but that still depends on what operation one is doing to the object.

One great thing about the multiple dispatch in Julia is the following. If now I define another struct:

mutable struct Car
   color
   position
end

which also has a position field. You can simply use the same function to displace this car. You do not need to define a new function for that. On the other side, in strict OO programming you would need to define an abstract class of things to avoid having to copy the function to every type of object.

29 Likes