[Tutor] domain logic and avoiding setters and setters.

David Driver count0.djd at gmail.com
Mon Jul 11 23:00:56 CEST 2005

So I have been trying to figure out how to get around doing getters
and setters and still have an oo way to inherit and apply business
rules. This is what I have some up with so far. Is there any better

class RuleViolationError(Exception):
    def __init__(self, msg):
        self.msg = msg
    def __str__(self):
        return 'Rule violated in rule object: %s' %self.msg
class someObject(object):
    def __init__(self,a):
        self._voilatedRules = {}
        self._rules = [self.aRuleForA]
        self.a = a
    def applyRules(self):
        for rule in self._rules:
            except RuleViolationError, err:
                self._voilatedRules[rule.__name__] = err.msg
        if self._voilatedRules:
            # do something dramatic to deal with all of the
            # voilated business rules
            print 'error(s): '
            print self._voilatedRules
    def aRuleForA(self):
            self.a = int(self.a)
        except ValueError:
            raise RuleViolationError('a is not an integer')

class someObjectChild(someObject):
    def __init__(self, a,b):
        self.b = b
    def aRuleForB(self):
        # apply some business logic for d
        # check that it starts with b, very silly
        if not self.b.startswith('b'):
            raise RuleViolationError('b does not start with b')
    def anotherRuleForB(self):
        #test string for length constraints
        print min,max,l
        if not(l>=min and l<=max):
            raise RuleViolationError('b is out of min or max')
class someObjectChild2(someObjectChild):
    #j ust change one of the rules for b
    def aRuleForB(self):
        # apply some business logic for d
        # check that it starts with d, very silly
        if not self.b.startswith('d'):
            raise RuleViolationError('b does not start with d')

x = someObjectChild(123,'bob jones')

# this should return nothing
x.b = 'obladiobladalifegoesonOOOO'

# this should fail twice on b

y = someObjectChild2(123,'bob jones')

z = someObjectChild('happydance','bob jones')

This isn't near complete, but I think it gets the idea across.

See there, that wasn't so bad.

More information about the Tutor mailing list