visitor pattern

R

RedLars

Hi,

Given this class definition,
public class Node
{
Node parent;
object current;
ArrayList children;



}


I would need to type check the object variable everytime I'd need to
use it. Like shown below;

void SomeMethod(Node node)
{
object obj = node.current;
if (obj is SomeType1)
{
// code
}
else if (obj is SomeType2)
{
// code
}
else if (obj is SomeType3)
{
// code
}



}


Is such a type check at runtime a bad thing in c#? Would using a
visitor patterns' double dispatch be a more elegant solution? This
would lead to changing the original Node to;

public class Node
{
Node parent;
baseObject current; // change from object to base class in apps'
object model
ArrayList children;



}

and adding the neccessary interfaces etc. Suppose it would make the
Node class less usable for other purposes - i,e, by binding it to a
specific object model.
 
K

Kevin Spencer

void SomeMethod(Node node)
{
object obj = node.current;
if (obj is SomeType1)
{
// code
}
else if (obj is SomeType2)
{
// code
}
else if (obj is SomeType3)
{
// code
}

This is definitely a bad idea, because it is not extensible. Fourthermore,
since the type is object, the object could be any type, and there are
thousands of types, so you would have to either implement a case for each
type, or deal with exceptions. Some version of the Visitor pattern might be
your best solution. At least this way, the implementation of the Visitor
handles the operation itself. Of course, without knowing more about what
"SomeMethod" does, I couldn't say for sure. It is possible that you could do
something a bit less complex by simply creating an interface or base
abstract class to use for the "current" property, and calling a method that
must be implemented in that class for each type concerned. However, using
the Visitor design pattern, or any legitimate design pattern, has its
advantages, as the pattern is well-known.

--
HTH,

Kevin Spencer
Microsoft MVP

Printing Components, Email Components,
FTP Client Classes, Enhanced Data Controls, much more.
DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top