Private visible?
xs0
xs0 at xs0.com
Fri Jul 14 03:49:17 PDT 2006
> The original reason why private members would be visible but not
> accessible has been forgotten. However, there were some significant
> issues brought up with making them invisible:
>
> 1) function overloading - if various overloads of a function have
> different protections, different functions will be selected even though
> the same arguments are presented. This can be surprising when code is
> moved around. If they are visible, you'll get an error message instead
> of silently varying behavior.
> 2) function overloading - one could lose the ability to 'poison' an
> operation on certain argument types, because instead the private
> function will not be seen and another selected.
> 3) function overriding - if a private function in a derived class
> overrides a public one in a base class, this overriding will not happen
> if the private function is invisible. Not only does this break
> encapsulation, it prevents the design pattern of being able to 'poison'
> certain operations on a class.
Consider
class Number {
public void setVal(int val) { ... }
public void setVal(long val) { ... }
}
class IntNumber : Number {
public void setVal(int val) { ... }
private void setVal(long val) { assert(0); }
}
Number a = new IntNumber();
a.setVal(10L);
Now, not only does the last line compile, it also calls the wrong
function and fails to fail. There is no poisoning or whatever, and the
author's belief that he achieved something by declaring something
private is misguided. Furthermore, allowing the private declaration
above means allowing broking inherited interfaces, practically always a bug.
Reducing visibility should be forbidden, as it doesn't even work and
leads to bugs.
Private members should be totally invisible, because that's the point of
marking them private.
As for overloading issues, as far as I am concerned, feel free to
require all methods with the same name to have the same protection;
anything else is poor taste anyway.
xs0
More information about the Digitalmars-d
mailing list