Robert said:
Sorry for that. But one other question comes to my mind: Could it make sense
to call those methods directly in an derived class? Technically, this is
possible. But is it also sensible? I ask that also for windows forms classes
with their On... methods. Or is it more advisable to call the correlating
official public methods?
Generally when you have the more private methods available, you would
use them. There aren't really any hard and fast rules, but it 'makes
more sense' for a derived class to use InsertItem rather than Insert to
do its inserting. For example, suppose I had a DinosaurGarden, which is
a subclass of Collection(Of Dinosaur), and I want to ensure that
whenever someone adds a dino to this collection, a predator or prey
dino for the new dino is also added. I would do something like this:
Protected Overrides Sub InsertItem( _
ByVal index As Integer, ByVal newItem As Dinosaur)
'insert this dino
MyBase.InsertItem(index, newItem)
'make a dino it can play with
Dim counterpartDino As Dinosaur = Dinosaur.Playmate(newItem)
'also insert the playmate
MyBase.InsertItem(index, counterpartDino) '**************
End Sub
Note that if instead of the highlighted line I instead had
Me.Insert(index, counterpartDino)
then I would create an infinite loop, because Insert would call
InsertItem and so on. Here using InsertItem makes sense, because I am
doing something internal to the class. However, elsewhere in the class
it might make sense to use the public methods. For example, I might
have an initial seeding routine for the garden:
Public Sub Seed()
Me.Insert(0, New Dinosaur("Velociraptor"))
Me.Insert(0, New Dinosaur("Brontosaurus"))
End Sub
Here, it makes sense for me to use the public Insert method, because
even though this is a method within the Garden class, in a sense it is
a client of the Insert method. I am just inserting dinos into myself
the same as anyone else would.
This kind of thing just takes time, and immersion / exposure to lots of
code, to get a feel for.
Certainly in the WinForms world it's easier to see the appropriate
thing to do: for example, OnPaint is where one writes one's own
painting, but to force a repaint, it's Invalidate().
I guess I'm too used to the OnSomethingHappend naming scheme. For me it
would be much clearer if those method names would start withn an On. This is
also done in the non-generic CollectionBase class. Is there a reason why MS
developers decided to not follow this naming convention in the Collection
class as well? Propably because they want to confuse their customers.
I don't know any reason for sure. It might be that Generics was
produced by a different team than originally produced
System.Collections, so they didn't notice the existing convention.
"OnX" is a fairly standard idea though, going back certainly as far as
the Object Model Naming Guidelines of the late 1990s, so it is a bit
strange.