I hope this question hasn't been asked before, my google/SX-fu is not very good on this one because I might not know the proper keywords.
Assume I have a class that represents a rather complex object, e. g. a point cloud, that has certain properties (a length, a volume...). Typically, I would go about defining a class for the point cloud (or in this case, a rectangle), like this (example courtesy of A Beginner's Python Tutorial, modified):
class Rectangle:
def __init__(self,x,y):
self.x = x
self.y = y
def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
And whenever I need to know the area of the rectangle, I just call my_rectangle.area()
, which will always give me the proper result, even if the dimensions of the rectangle change.
Now in my application, calculating the perimeter or the area is a lot more complex and takes quite a bit of time. Also, typically, I need to know the perimeter more often than I modify the object. So it would make sense to split the calculation from accessing the value itself:
class Rectangle:
def __init__(self,x,y):
self.x = x
self.y = y
def calc_area(self):
self.area = self.x * self.y
def calc_perimeter(self):
self.perimeter = 2 * self.x + 2 * self.y
Now, if I need to know the area of the rectangle, I need to call my_rectangle.calc_area()
at least once after any modification, but afterwards I can always just get my_rectangle.area
.
Is this a good idea or should I rather keep the area calculation in the .area()
method and access it whenever I need it, while storing the current area in a local variable in whichever script is using my Rectangle
class?
If this is too opinion-based or too dependent on the actual application, please advise on how to improve the question.