RE: A tiny OOP challenge (Python, Java, C++, any language with class) /
Writing these sorts of things can definitely help with learning programming. Small little programs like this are good practice.
One way to expand on this is to think about the exercise itself. Is this class a good example of object oriented design? What constraint do the interface place on us?
For example, void add(double number)
, forces us to implement our object as a mutable object. Sometimes we may not want a mutable object, perhaps we want our objects to be thread safe or believe immutability helps with reasoning.
Imagine we change the interface instead to Averager add(double number)
. Now we are no longer constrained to implement our our class mutably. In fact, we get some nice syntactic features as well.
averager
.add(2)
.add(3)
.add(4);
But I think the real benefits come in when we remove ourselves from the OO constraint. This class inherently limits what interpretations we can give to our data. What if we need the product, the median, and the average, but we don't own the code to this object. We must proxy our object, (or write a new one) ultimately, duplicating our state in two places, making ourselves potentially out of sync.
This sort of encapsulation actually makes your code less reusable and more susceptible to error.
Why not just use a list and write functions that operate on that list? We now don't constrain ourselves on future functionality.