enki wrote:
I was reading a book on game programming and they were explaining a
game engine class and they say that correct OO programming is making
base calss functions virtual.
Correct programming in general replaces repeated or duplicated code, and
duplicated effort, with virtual methods. This is a very subtle point, but
you can't just say "make all base classes virtual".
Plenty of times, you should not have a base class, if that's simplest.
Are virtual functiontions and dynamic binding correct OO programing
practice?
Stare at these two functions, written in an arbitrary language:
function drawShape(shape, type)
if type == SQUARE
drawSquare(shape)
else
if type == CIRCLE
drawCircle(shape)
else
if type == Triangle
drawTriangle(shape)
end
end
function saveShape(shape, type)
if type == SQUARE
saveSquare(shape)
else
if type == CIRCLE
saveCircle(shape)
else
if type == Triangle
saveTriangle(shape)
end
end
If you want to add a new shape, you must change both of those functions.
(Your tutorials might make you think you should design a program once, then
never change the design. All good designs permit flexibilities and
extensions.)
Now we change the design to the OO equivalent:
class Square
function draw();
function save();
end
class Circle
function draw();
function save();
end
class Triangle
function draw();
function save();
end
function drawShape(shape)
shape.draw()
end
So far, no benefit. If there were only one client, we might not even make
this refactor. But we have two clients, and the second one looks like this:
function saveShape(shape, type)
shape.save()
end
That's it; the second function got short, so overall we have fewer lines of
code. (Tip: Good designs minimize lines of code!)
So if we want to add a new class, we only need to declare it, then pass it
into functions that expect this interface:
class Blob
function draw();
function save();
end
Now pass Blobs into either drawShape() or saveShape(), and they will work.
You don't need to change code in many places just to add new behaviors to
it.
Now read the book /Design Patterns/.
--
Phlip
http://www.c2.com/cgi/wiki?ZeekLand