Bug 3194 – invariant should be checked at the beginning and end of protected functions
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
Other
OS
Linux
Creation time
2009-07-20T14:12:00Z
Last change time
2015-06-09T01:31:13Z
Keywords
patch
Assigned to
nobody
Creator
andrei
Comments
Comment #0 by andrei — 2009-07-20T14:12:56Z
Consider:
class A
{
invariant() { ... }
public void f() { ... }
protected void g() { ... }
}
Currently invariant is called at the beginning and end of each public function, the end of the constructor, and the beginning of the destructor. Scott Meyers pointed out to a quite known fact - protected is much closer to public than to private in terms of offering access control. This is because anyone can just inherit from a class and call protected methods, or even wrap them in public methods.
Consequently, it looks like the invariant of a class must also hold upon entry and exit of all protected methods.
(In reply to comment #1)
> Patch for D2
> https://github.com/D-Programming-Language/dmd/pull/112
I disagree.
Even while you can easily access protected methods of a class, they are intended for internal use, otherwise they'd be public.
Consider:
class A
{
abstract protected SomeType[] getData();
public void processData()
{
//do something that breaks the invariants
foreach (SomeType element; getData())
{
//do something...
}
//do something that restores the invariants
}
invariant() {...}
}
a class B derived from A implementing getData() shouldn't have to respect the invariants while entering/leaving getData(). Anything regarding getData()'s side-effects should be put in an out clause.
BTW, abstract functions shouldn't require a body clause accompanying in and out clauses