I’m coding in Python, but the question seems independent of programming language.
I have a class that represents some system check:
class Check:
@abstractmethod
def run()
""" You have to define your own run(). As a result, it must set self._ok. """
...
@property
def is_ok():
return self._is_ok
Then we have a set of checks by subclassing Check class, and they’re used in the following way (simplified):
class Checker:
checks = [check1, check2...]
def __call__(self):
for check in self.checks:
if not check.is_ok:
alarm()
The question is: Is it fine to oblige subclass to set some protected object attributes?
1
Why wouldn’t it be okay to require subclasses to do work? The parent is abstract, after all.
The more important question is: why is run()
supposed to signal success via an out-of-bound mechanism (setting a global variable) rather than a return value? There are sometimes reasons for doing this (e.g. because it’s an extremely entrenched convention, like errno
in C), but usually it’s a bad sign because of issues with concurrency, maintainability etc.
2
To provide an alternative to letting the value be set by the subclass you can instead have them provide a doRun that returns true/false to signify success and the run assigns that result to self._ok
, this also allows more checks like catching exceptions or ensuring it only runs once:
class Check:
@abstractmethod
def doRun()
""" You have to define your own doRun(). As a result, it must return whether it was successful. """
...
def run()
if not is_ok """ runs once, remove if not needed """
self._ok = doRun()
@property
def is_ok():
return self._is_ok
1
One commonly (albeit not universally) accepted principle of object design is that an object should be immutable unless this makes the design substantially more complex. Immutable objects are easier to reason about, can be used in a multithreaded environment more easily and are generally less prone to bugs.
From the code you have shown us, there is no reason I can see why you need mutable objects, so I would use immutable ones.
1