Tuesday, November 01, 2005

Eric Gunnerson's C# Compendium : More on virtual by default: "virtual by default is absurd - it's just a game of russian roulette! It's like said above, it's not a question of knowing what people are going to do with your class - it's more the fact that BECAUSE YOU DON'T KNOW WHAT THEY ARE GOING TO DO - YOU HAVE TO BE CAREFUL.

easy example -
public void Open {_open=true;_pointer = OpenTheFile();}
public void Close {if (_open) CloseFile(m_pointer);}

If some idiot starts overriding open, and doesn't properly set m_open or something, then
the close will fail badly. Because there is no way of _guaranteeing_ that anyone who override calls the base class, the ONLY safe way of doing the above class is by making them final... and if you do want them sort of overridable, then you make them protected final functions, and make virtual stub functions that call them..

Especially if you don't give out your source, I put it to you that the % of functions that it would be REALLY REALLY BAD if someone overrode them and didn't properly do what those functions did is much much higher than the % of functions that you can safely override!

(Quite apart from the fact that you want proper encapsulation - I NEVER let any of my coders create a protected class variable - you can make a protected property accessor, but ALL member variables are always private - so it would be impossible to successfully duplicate the functionality of the base class in a child class, without just calling base->function)"

0 Comments:

Post a Comment

<< Home