Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

I have some objects each hold a list of variables, and a list which holds all variables of these objects, for example

class A
{
   List<Var> varList;
}

class B
{
   List<A>   aList;
   List<Var>   allVarOfAs; 
  // it is a common list which holds the members of varList of all members of the aList
}

Now if an object from varList in an an object of aList (an A object in B) is removed, how can I update the common list allVarOfAs?

What is the pattern for such situation?

share|improve this question

2 Answers 2

up vote 4 down vote accepted

The simplest solution is to NOT have the aggregated list 'allVarOfAs'. Instead make it a method or property which returns the aggregated list on the fly, but doing a SelectMany over aList. E.g.

IEnumerable<Var> allVarOfAs 
{
     get
     {
          return aList.SelectMany(a=>a.varList);
     }
}

or

List<Var> allVarOfAs
{
     get
     {
          return aList.SelectMany(a=>a.varList).ToList();
     }
}
share|improve this answer
    
Yes, it can be the get function of a allVarOfAs property. –  Ahmad Jun 1 at 14:40

First, add some encapsulation and suppose you declare your fields private and define public add and remove methods in class B (which add and remove A instances). Then, add and remove will be respondible for updating allVarOfAs.

The problem with this approach is that as long as any other object has a reference to the same aList (directly, or by having a reference to an A), it can modify it without going throught your B instance. You would have to ensure that no instance of class A is ever shared with other objects, and that A.varList is only modified by a B object (otherwise, the actual union of lists and the one computed in B could differ).

It is simpler and always correct to recompute allVarOfAs when needed (see JacquesB's answer).

Maintaining allVarOfAs could be done incrementally: but do you really need to?

share|improve this answer
1  
I think the main problem is that varList might be modified in an instance of A class. Even private, the functions inside it can modify the varList without notifying the B object. –  Ahmad Jun 1 at 14:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.