user3002473
user3002473

Reputation: 5074

Choosing between whether to provide object-oriented implementations or functional implementations of primitives

In some larger projects I've worked on, I've always ran into the same problem when dealing with certain objects. Assume I had some vector class Vector, that had an x and a y attribute. It's nice to have this vector class and it's nice to have all it's data self contained, but at the same time it's also convenient to allow a vector to be represented by a 2-tuple.

So my dilemma is this; should I provide only the class implementation of Vector with any and all functions applying to the vector made to be methods of the Vector class, or should I also provide functions that have the same functionality as the methods but act on 2-tuples, i.e. not bounded to any class? Or should I provide both object-oriented and functional implementations?

If it makes any difference, I'm asking this question in terms of Python.

Upvotes: 0

Views: 37

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 113948

I think this is going to come down to preferences but I would do something like this

import operator,functools
import numpy
class Vector: #encompass the behavior in its own class
    @classmethod
    def dot_product(cls,p1,p2):
        #treat p1 and p2 as tuples
        return numpy.dot(p1,p2)
    @classmethod
    def cross_product(cls,p1,p2):
        #treat p1,p2 as tuples
        return numpy.cross(p1,p2)

class Vector2d: #encapsulate the data in its own class
    def __init__(self,points):
        #validate construction data
       self.points = points
    def __getitem__(self,item): #now this will act like an array
       return self.points[item] #allows indexing 
    def __getattr__(self,attr): #allows it to act like a vector (above)
       return functools.partial(getattr(Vector,attr),self.points)

class Vector3d(Vector2d):
    pass

a = Vector2d([2,3])
b = [4,5]
c = Vector3d([2,3,4])
d = [3,4,5]    
print a.dot_product(b)
print c.cross_product(d)

but thats just cause i like python magic stuff :P

Upvotes: 1

Related Questions