I suppose theoretically a subclass constructor could call a base constructor with arguments such that the base invariant will be violated, but then the subclass constructor fixes things up before ending. However, that is probably a rare situation that we can live with.
I will give your proposed solution a try.
Forums
invariants and derived classes
12 posts
• Page 2 of 2 • 1, 2
Re: invariants and derived classes
I can think of a more complete solution that gets rid of even the last issue you mentioned. But it requires creating, for every class, an internal, protected, copy of each constructor, that does not check the invariant, and that is used by the constructors of derived classes. This is easier to code than to say:
Your A class would be translated to:
And your class B:
There are obvious problems with this, the biggest one is my opinion is that clients of the class using other .NET languages will see all this "hidden" constructors and they will be confused by them.
Your A class would be translated to:
class A
def invariant_impl as bool
return .x > 0 _
and .name.length
var _x as int
# The constructor used by everyone that refers to the class, except its derived classes
# This was written by the user
def init
_x = 1
assert .invariant_impl # polymorphic compiler generated invariant check.
# ...
# The constructor used by derived classes (although people writing them won't even realize it)
# This is automatically generated by the compiler
def _init(dummy as _obscure_internal_type)
_x = 1
# Notice no invariant check!!
def main is shared
a = A() # Uses user written constructor. No way to refer to the other one from client code
And your class B:
class B
inherits A
var _y as int
# The lines marked (*) are inserted automatically by the compiler, the user only wrote (**)
def init
base(_var_of_dummy_type) # forces call to ctor. with no invariant check (*)
_y = 1 (**)
assert .invariant_impl # the invariant is thus only checked at the end (*)
There are obvious problems with this, the biggest one is my opinion is that clients of the class using other .NET languages will see all this "hidden" constructors and they will be confused by them.
- jonathandavid
- Posts: 159
12 posts
• Page 2 of 2 • 1, 2
Who is online
Users browsing this forum: No registered users and 14 guests