Functional vs. Object oriented API

Rui Maciel rui.maciel at gmail.com
Sat Apr 13 04:51:25 EDT 2013


Max Bucknell wrote:

> Hi,
> I'm currently learning Python, and it's going great. I've dabbled before,
> but really getting into it is good fun.
> 
> To test myself, and not detract too much from my actual studies
> (mathematics), I've been writing my own package to do linear algebra, and
> I am unsure about how best to structure my API.
> 
> For example, I have a vector class, that works like so:
> 
>     >>> a = Vector([2, 7, 4])
>     >>> b = Vector.j # unit vector in 3D y direction
> 
> I also have a function to generate the dot product of these two vectors.
> In Java, such a function would be put as a method on the class and I would
> do something like:
> 
>     >>> a.dot_product(b)
>     7

Not necessarily.  That would only happen if that code was designed that way.  
It's quite possible, and desirable, that the dot product isn't implemented 
as a member function of the vector data type, and instead is implemented as 
an operator to be applied to two object.


> and that would be the end of it. But in Python, I can also have:
> 
>     >>> dot_product(a, b)
>     7
> 
> Which of these two are preferred in Python? And are there any general
> guidelines for choosing between the two styles, or is it largely a matter
> of personal preference?

The separation of concerns principle is a good guideline.  This doesn't 
apply exclusively to Python; it essentiallyl applies to all programming 
languages.

http://en.wikipedia.org/wiki/Separation_of_concerns


There are significant advantages in separating the definition of a data type 
from the definition of the operations that are to be applied to it.  If 
operations are decoupled from the data type then it's possible to preserve 
the definition of that data type eternally, while the operators that are 
written to operate on it can be added, tweaked and removed independently and 
at anyone's whims.


Hope this helps,
Rui Maciel



More information about the Python-list mailing list