473,706 Members | 2,441 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Code Review! Parent-child relationships

Hi all,

I've been trying to write some classes, so when I have a parent-child
relationship, such as with Folders in my application, I don't have to
remember to add a parent reference, as well as adding to the child
collection, eg:

parent.Children .Add(child);
child.Parent = parent;

And I've come up with the below (I've included my test, and three classes).
It seems to work, but I have two questions....

1. Does this look like the best way of doing this?

2. I now want to extend this to support multiple lists (eg, my folders can
contain both folders, and messages. Messages can have child messages, and
therefore have both a parent folder, and a parent message), eg.

folder.ChildFol ders // Returns List<TreeItem<F older>>
folder.Messages // Returns List<TreeItem<M essage>>

message.ParentM essage // Returns TreeItem<Messag e>
message.ParentF older // Returns TreeItem<Folder >

Or should I create a base class that represents the entire tree (Folders and
Messages)? Though this way, I'd have a single child list, and would need to
add properties, like .ChildFolders, which would filter the .Children list!

I know it looks like a lot of code here, but it's just 3 classes and my
command line test. If you paste it into VS, it'll look dead simple :)

Any thoughts or suggestions?

Thanks,

Danny Tuppeny

namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Test1();
Test2();
}

static void Test1()
{
Folder parent = new Folder();
Folder child = new Folder();

child.Parent = parent;

if (parent.Childre n.Contains(chil d))
{
Console.WriteLi ne("Test succeeded");
}
else
{
Console.WriteLi ne("Test failed");
}
}

static void Test2()
{
Folder parent = new Folder();
Folder child = new Folder();

parent.Children .Add(child);

if (parent == child.Parent)
{
Console.WriteLi ne("Test succeeded");
}
else
{
Console.WriteLi ne("Test failed");
}
}
}

public class ChildList<T> : List<T>
{
public event EventHandler<Ch ildListEventArg s<T>> Added;
public event EventHandler<Ch ildListEventArg s<T>> Removed;

public class ChildListEventA rgs<T> : EventArgs
{
public T Item;
public ChildListEventA rgs(T item)
{
Item = item;
}
}

public new void Add(T item)
{
EventHandler<Ch ildListEventArg s<T>> added = Added;
if (added != null)
added(this, new ChildListEventA rgs<T>(item));

base.Add(item);
}

public new void AddRange(IEnume rable<T> collection)
{
EventHandler<Ch ildListEventArg s<T>> added = Added;
if (added != null)
{
foreach (T item in collection)
{
added(this, new ChildListEventA rgs<T>(item));
}
}

base.AddRange(c ollection);
}

public new void Insert(int index, T item)
{
EventHandler<Ch ildListEventArg s<T>> added = Added;
if (added != null)
added(this, new ChildListEventA rgs<T>(item));

base.Insert(ind ex, item);
}

public new void InsertRange(int index, IEnumerable<T> collection)
{
EventHandler<Ch ildListEventArg s<T>> added = Added;
if (added != null)
{
foreach (T item in collection)
{
added(this, new ChildListEventA rgs<T>(item));
}
}

base.InsertRang e(index, collection);
}

public new bool Remove(T item)
{
EventHandler<Ch ildListEventArg s<T>> removed = Removed;
if (removed != null)
removed(this, new ChildListEventA rgs<T>(item));

return base.Remove(ite m);
}

public new void RemoveAll(Predi cate<T> match)
{
EventHandler<Ch ildListEventArg s<T>> removed = Removed;
if (removed != null)
{
foreach (T item in base.FindAll(ma tch))
{
removed(this, new ChildListEventA rgs<T>(item));
}
}

base.RemoveAll( match);
}

public new void RemoveAt(int index)
{
EventHandler<Ch ildListEventArg s<T>> removed = Removed;
if (removed != null)
removed(this, new ChildListEventA rgs<T>(base[index]));

base.RemoveAt(i ndex);
}

new void RemoveRange(int index, int count)
{
EventHandler<Ch ildListEventArg s<T>> removed = Removed;
if (removed != null)
{
foreach (T item in base.GetRange(i ndex, count))
{
removed(this, new ChildListEventA rgs<T>(item));
}
}

base.RemoveAt(i ndex);
}
}

public class TreeItem<T>
{
TreeItem<T> parent;
ChildList<TreeI tem<T>> children;

public TreeItem()
{
children = new ChildList<TreeI tem<T>>();
children.Added += delegate(object sender,
ChildList<TreeI tem<T>>.ChildLi stEventArgs<Tre eItem<T>> e) { e.Item.parent =
this; };
children.Remove d += delegate(object sender,
ChildList<TreeI tem<T>>.ChildLi stEventArgs<Tre eItem<T>> e) { e.Item.parent =
null; };
}

public TreeItem<T> Parent
{
get { return parent; }
set
{
if (parent != value)
{
if (parent != null)
{
// This automagically unsets the internal parent
parent.children .Remove(this);
}
if (value != null)
{
// This automagically sets the internal parent
value.children. Add(this);
}
}
}
}

public ChildList<TreeI tem<T>> Children
{
get { return children; }
}
}

public class Folder : TreeItem<Folder >
{
string name;

public Folder()
{
}

public string Name
{
get { return name; }
set { name = value; }
}

}
}
Nov 17 '05 #1
4 4566
um... HOw 'bout a nice simple:

parent.AddChild (child);

where AddChild is defined as

public AddChild(IChild pChild)
{
this.Children.A dd(child);
child.Parent = this;
}

--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
"Danny Tuppeny" <gr****@dannytu ppeny.commmmmm> wrote in message
news:43******** *************** @ptn-nntp-reader04.plus.n et...
Hi all,

I've been trying to write some classes, so when I have a parent-child
relationship, such as with Folders in my application, I don't have to
remember to add a parent reference, as well as adding to the child
collection, eg:

parent.Children .Add(child);
child.Parent = parent;

And I've come up with the below (I've included my test, and three classes). It seems to work, but I have two questions....

1. Does this look like the best way of doing this?

2. I now want to extend this to support multiple lists (eg, my folders can
contain both folders, and messages. Messages can have child messages, and
therefore have both a parent folder, and a parent message), eg.

folder.ChildFol ders // Returns List<TreeItem<F older>>
folder.Messages // Returns List<TreeItem<M essage>>

message.ParentM essage // Returns TreeItem<Messag e>
message.ParentF older // Returns TreeItem<Folder >

Or should I create a base class that represents the entire tree (Folders and Messages)? Though this way, I'd have a single child list, and would need to add properties, like .ChildFolders, which would filter the .Children list!

I know it looks like a lot of code here, but it's just 3 classes and my
command line test. If you paste it into VS, it'll look dead simple :)

Any thoughts or suggestions?

Thanks,

Danny Tuppeny

namespace MyApplication
{
class Program
{
static void Main(string[] args)
{
Test1();
Test2();
}

static void Test1()
{
Folder parent = new Folder();
Folder child = new Folder();

child.Parent = parent;

if (parent.Childre n.Contains(chil d))
{
Console.WriteLi ne("Test succeeded");
}
else
{
Console.WriteLi ne("Test failed");
}
}

static void Test2()
{
Folder parent = new Folder();
Folder child = new Folder();

parent.Children .Add(child);

if (parent == child.Parent)
{
Console.WriteLi ne("Test succeeded");
}
else
{
Console.WriteLi ne("Test failed");
}
}
}

public class ChildList<T> : List<T>
{
public event EventHandler<Ch ildListEventArg s<T>> Added;
public event EventHandler<Ch ildListEventArg s<T>> Removed;

public class ChildListEventA rgs<T> : EventArgs
{
public T Item;
public ChildListEventA rgs(T item)
{
Item = item;
}
}

public new void Add(T item)
{
EventHandler<Ch ildListEventArg s<T>> added = Added;
if (added != null)
added(this, new ChildListEventA rgs<T>(item));

base.Add(item);
}

public new void AddRange(IEnume rable<T> collection)
{
EventHandler<Ch ildListEventArg s<T>> added = Added;
if (added != null)
{
foreach (T item in collection)
{
added(this, new ChildListEventA rgs<T>(item));
}
}

base.AddRange(c ollection);
}

public new void Insert(int index, T item)
{
EventHandler<Ch ildListEventArg s<T>> added = Added;
if (added != null)
added(this, new ChildListEventA rgs<T>(item));

base.Insert(ind ex, item);
}

public new void InsertRange(int index, IEnumerable<T> collection)
{
EventHandler<Ch ildListEventArg s<T>> added = Added;
if (added != null)
{
foreach (T item in collection)
{
added(this, new ChildListEventA rgs<T>(item));
}
}

base.InsertRang e(index, collection);
}

public new bool Remove(T item)
{
EventHandler<Ch ildListEventArg s<T>> removed = Removed;
if (removed != null)
removed(this, new ChildListEventA rgs<T>(item));

return base.Remove(ite m);
}

public new void RemoveAll(Predi cate<T> match)
{
EventHandler<Ch ildListEventArg s<T>> removed = Removed;
if (removed != null)
{
foreach (T item in base.FindAll(ma tch))
{
removed(this, new ChildListEventA rgs<T>(item));
}
}

base.RemoveAll( match);
}

public new void RemoveAt(int index)
{
EventHandler<Ch ildListEventArg s<T>> removed = Removed;
if (removed != null)
removed(this, new ChildListEventA rgs<T>(base[index]));

base.RemoveAt(i ndex);
}

new void RemoveRange(int index, int count)
{
EventHandler<Ch ildListEventArg s<T>> removed = Removed;
if (removed != null)
{
foreach (T item in base.GetRange(i ndex, count))
{
removed(this, new ChildListEventA rgs<T>(item));
}
}

base.RemoveAt(i ndex);
}
}

public class TreeItem<T>
{
TreeItem<T> parent;
ChildList<TreeI tem<T>> children;

public TreeItem()
{
children = new ChildList<TreeI tem<T>>();
children.Added += delegate(object sender,
ChildList<TreeI tem<T>>.ChildLi stEventArgs<Tre eItem<T>> e) { e.Item.parent = this; };
children.Remove d += delegate(object sender,
ChildList<TreeI tem<T>>.ChildLi stEventArgs<Tre eItem<T>> e) { e.Item.parent = null; };
}

public TreeItem<T> Parent
{
get { return parent; }
set
{
if (parent != value)
{
if (parent != null)
{
// This automagically unsets the internal parent
parent.children .Remove(this);
}
if (value != null)
{
// This automagically sets the internal parent
value.children. Add(this);
}
}
}
}

public ChildList<TreeI tem<T>> Children
{
get { return children; }
}
}

public class Folder : TreeItem<Folder >
{
string name;

public Folder()
{
}

public string Name
{
get { return name; }
set { name = value; }
}

}
}

Nov 18 '05 #2
"James Curran" <ja*********@mv ps.org> wrote in message
news:ON******** ******@TK2MSFTN GP09.phx.gbl...
um... HOw 'bout a nice simple:

parent.AddChild (child);

where AddChild is defined as

public AddChild(IChild pChild)
{
this.Children.A dd(child);
child.Parent = this;
}


Because that relies on remember not to use .Children.Add :)

If I can do some extra work now, which reduces the number of bugs my
software might include, it's worth it! :)

Though I guess, returning Children as a ReadOnlyList (or whatever it's
called) and then having an Add method would work.. I don't think it's as
nice though :)
Nov 18 '05 #3
OK, plan 2 (A bit stripped down, but you should get the idea)

interface IParent
{
}

interface IChild
{
IParent Parent;
}

public class ChildList<T> : List<T>
{
private IParent oOwner;
public ChildList(IPare nt pOwner) : base()
{
oOwner = pOwner;
}

public new void Add(T item)
{
base.Add(item);
item.Parent = oOwner;
}
}
public class Folder : IParent, IChild
{
private IParent oParent;
prinvate ChildList<Folde r> children;

public Folder()
{
children = ChildList<Folde r>(this);
}

}

--
Truth,
James Curran
[erstwhile VC++ MVP]

Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
"Danny Tuppeny" <gr****@dannytu ppeny.commmmmm> wrote in message
news:43******** *************** @ptn-nntp-reader03.plus.n et...
"James Curran" <ja*********@mv ps.org> wrote in message
news:ON******** ******@TK2MSFTN GP09.phx.gbl...
um... HOw 'bout a nice simple:

parent.AddChild (child);

where AddChild is defined as

public AddChild(IChild pChild)
{
this.Children.A dd(child);
child.Parent = this;
}


Because that relies on remember not to use .Children.Add :)

If I can do some extra work now, which reduces the number of bugs my
software might include, it's worth it! :)

Though I guess, returning Children as a ReadOnlyList (or whatever it's
called) and then having an Add method would work.. I don't think it's as
nice though :)

Nov 18 '05 #4
"James Curran" <ja*********@mv ps.org> wrote in message
news:%2******** ********@TK2MSF TNGP14.phx.gbl. ..
OK, plan 2 (A bit stripped down, but you should get the idea)

<snip>

That's better - thanks :-)
Nov 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2933
by: Volodymyr Sadovyy | last post by:
Hi. Can somebody refer me to resource with specified/analyzed/approximated productivity in Java coding and Java code review tasks? Coding productivity is more described in the net, but I didn't find anything about code review productivity... Thanks, V
3
5221
by: Arvie | last post by:
I need some advice guys.. I am proposing that we get someone to do a complete audit/review of our Java application codebase, about 1000 JSPs/Servlets and 100 EJBs. If I get firms to submit proposals, what should I be asking /looking out for? I realise that running the applications through a migration tool will help but I am looking for a more through analysis of the actual codebase as well as assessment of the architecture Thanks
0
1442
by: gs-code-review-bounces | last post by:
Your mail to 'gs-code-review' with the subject Re: Application Is being held until the list moderator can review it for approval. The reason it is being held: Post by non-member to a members-only list
6
2084
by: andrew blah | last post by:
Hello I have recently released catchmail - a free (BSD license) open source Python utility www.users.bigpond.net.au/mysite/catchmail.htm This script processes in and outbound emails and stores them to a database. The source code is here: http://www.users.bigpond.net.au/mysite/current/catchmail.py
3
1677
by: Filippo | last post by:
Hi, In my organization we would like to activate a code review system, in wich a developer have to pass a review from a reviewer before check in the modified files in source safe. Is there any way or software to optimizate this task? We actually use .Net 2003 and source safe 6.0d. Thanks in advance.
239
10225
by: Eigenvector | last post by:
My question is more generic, but it involves what I consider ANSI standard C and portability. I happen to be a system admin for multiple platforms and as such a lot of the applications that my users request are a part of the OpenSource community. Many if not most of those applications strongly require the presence of the GNU compiling suite to work properly. My assumption is that this is due to the author/s creating the applications...
3
1597
by: JeanDean | last post by:
I am looking for freeware tool which can review the c++ code(compiled on g++). Please share your experiences and details obout the usage of the tool.
10
1777
by: Jo | last post by:
Hi there: I m wondering what can I do to improve my code, everytime I am coding I feel like it could be done better. I started on c# a good months ago and feel conformtable but sometimes I Need to look up stuff. maybe someone can suggest a good book on good practices for c#? Cheers Jo
4
1914
maxx233
by: maxx233 | last post by:
Hello all, I'm new to OO design and have a question regarding where I should place some code. Here's a simplified situation: I'm making an app to do create, submit, and track employee reviews within our organization. Should I have a class called Review, with properties for things like "review date", "employee being reviewed", etc?.. And methods for things like submit(), generateReport(), delete(), etc? I don't really think I *need* an...
0
1648
by: corey | last post by:
Secure Bytes audit and vulnerability assessment software Secure Auditor named “Versatile tool” and earn “Five Star Ratings” in SC Magazine Group Test Secure Bytes is really pleased to share this great news with its associates that Secure Auditor has been branded as a Five Star product by SC Magazine August 2008 edition. SC Magazine is among the world’s most prestigious Information Security magazines. In the comparative review with...
0
8781
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9286
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9156
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9055
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8997
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7911
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5939
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4453
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
3
2095
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.