Referencing a parent's value from a child element - c#

I am trying to figure out a more elegant way to set the property of a parent in c#. I currently pass the parent into the child element, and reference it that way. This seems both cumbersome and possibly even incorrect.
The Child:
public class ValidatedField<T>
{
public OpenIssues parent { get; set; }
//Other values
public void Highlight()
{
parent.isNotValid = true;
isHighlighted = true;
}
}
And the Parent:
public class OpenIssues
{
public OpenIssues()
{
DateAppealFiled = new ValidatedField<DateTime?>(this);
}
public bool isNotValid { get; set; }
public ValidatedField<DateTime?> DateAppealFiled { get; set; }
}
Is there a more streamlined way to reference the parent in this case? Or am I doomed to sending the entire parent to the child, just to modify one value in the parent?

Is there a more streamlined way to reference the parent in this case?
Or am I doomed to sending the entire parent to the child, just to
modify one value in the parent?
The entire parent (in your words) is just a few bytes of reference/pointer
However,
You can essentially do this one of 3 ways
Pass in a concrete reference or interface from your parent.
Use events/delegate/action and register then trigger them on update
Or a decoupled pub/sub messaging system or mediator
What you are doing is fine, though all have their downsides and are cumbersome in different ways
The most modern approach is a decoupled messaging system, this is common in viewmodels where you don't want to couple view models and classes together. However, this is most likely overkill for trivial situations.
Also too, actions and events have their places as well. The parent(or someone) subscribes, and unsubscribes (well... should).
However, if you don't mind the tight coupling of your parent and child, and if there is little need to use them in different parent child configuration, just use references. No harm done.

Related

How to Design whether a Class Property has Changed?

I have a class with about 20 properties but I'd simplify it for this question:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
I'd like to have a class or property that identifies whether my class is dirty. By this I mean to identify whether any of its values have changed?
There are 3 design approaches I can take:
1)
When setting the property inside the class, I check whether the property IsDirty.
public string Name
{
get { return this._name; }
set { if (this._name != value) { this.IsDirty = true; this._name = value; }
}
2)
When setting the property from outside the class, I check whether the property IsDirty.
e.g.
if (p.Name != newName)
{
p.IsDirty = true;
p.Name = newName;
}
This approach forces me to add lots of ifs in the client class. Some properties are even collections or even reference objects so the number of lines would be increased even.
3)
When the object is ready to be saved, then I check whether any properties IsDirty by getting a cloned object and checking the equality.
This would have a poorer performance as I would have to clone or load again the original object then compare the properties one by one.
Which one is the best design? or is there any other design pattern that can help with this?
Another option would be to Implement the INotifyPropertyChanged Interface.
Please note that this will help you make thing more tidy and your API clearer, but as far as internal implementation regarding keeping track after changes, It is still up to you to implement. I think this goes along best with your Option #1
Option 1 is clearly best: it puts the responsibility of tracking dirtiness where it belongs: inside the object. Option 2 is out because as you mentioned, you are forcing this responsibility onto the clients of your classes. And option 3 has the additional problem as you mentioned of performance.
Incidentally, you should look into a proxy implementation using DynamicProxy. This will allow your code to look like this:
public class Product
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
and with the judicious use of interceptors, you can get the behaviour you want. You can write an interceptor to intercept any "sets" and do some logic inside, such as setting an IsDirty flag.
Another idea would be to make this a GoF Observable and let interested Observer parties register their interest in changes. It's a more event-based approach.
This is the best solution and complies with SRP principle very nicely, I created the below classes:
ProductWithChangeDetection; this uses the Decorator pattern to add this new feature to an existing product object
ProductChangeDetector; this contains logics for checking and notification. Currently only exposes ChangeDetected property but if more complexity needed one should implement INotifyPropertyChange interface.
ProductEquitable; this implements IEquitable and has some overloads for checking whether two objects/properties are equal

Having ViewModel call Actions instead of executing Commands and publishing events?

In this hypothetical question, let's say the ViewModel publishes a rather complex event that the View subscribes to. The View then manipulates multiple screen elements based on the state within that event. For example, several buttons are made visible/hidden, or enabled/disabled, or maybe a storyboard is started.
// purely as an example:
public class SomeEvent
{
public bool ShouldShowAddButton { get; set; }
public bool ShouldShowDeleteButton { get; set; }
public bool AddButtonEnabled { get; set; }
public bool DeleteButtonEnabled { get; set; }
}
Since the VM does not know anything about the View, it can't actually reach in and do these things and instead relies on the event. Standard MVVM practice, I think. (Another option would be to make each of these items be their own published event, sent one after another.)
However, what if the VM could call into the View without knowing anything about the View?
public class MyViewModel
{
public Action OnShowAddButton { get; set; }
public Action OnShowDeleteButton { get; set; }
...etc
private void OnSomeStateChange()
{
// here, we'd normally publish the SomeEvent class
// instead, we could just call OnShowAddButton (or whatever) instead
}
}
public class MyView
{
public MyView()
{
this.myViewModel.OnShowAddButton = () => ...;
...etc
}
}
Is there a reason this would be frowned upon, other than not being "typical" of MVVM design? As far as I can tell, it's still maintaining the correct level of separation.
I think this variation is mixing a bit of MVC with a bit of MVVM, although it's none of both. So, the Model-View part of the pattern is solved in your proposal by injecting the models straight into the view implementation and then send some kind of commands, via events.
You then need to solve or go around the View-Model part of the pattern by either providing properties in the model that can be set directly by the view, or by exposing some events in the view and do the same kind of injection in the model.
I think it will get ugly. Even if the model is only a set of observable entities and you control them from somewhere else (the controller? :)).
I can already see the code, countless events and properties mixed and mingled... But it all depends on how complicated your UI will become, how many views you will have and how complex will they get. In a view with 10+ buttons and/or inputs I think is a bad idea to go with this approach.
I say that as long as you do not have a dedicated MVVM infrastructure, like WPF or HTML, there's no point in implementing your own. You can't get to that beautiful degree of separation only with a hand-coded framework. You need some support to entirely separate the UI code from the model, do bindings and so on.
Perhaps you can comment some more on what you want to use it. If you need it for a client framework (like HTML/JS) or for a Windows Forms implementation then there may be some dedicated solutions you could use, or better, some easier paths you could take.
This all comes from a guy who implemented an MVP variation on top of ASP.NET Web Forms. If I only could turn back time.

Use value of a parent property when creating a complex child in AutoFixture

I'm using AutoFixture to generate data for a structure involving a parent object and complex child objects, like this:
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public Child[] Children { get; set; }
}
public class Child
{
public string Name { get; set; }
public int ParentId { get; set; }
}
Is there a way to automatically set the property ParentId of the generated Child object to the id assigned to the parent? Right now my solution looks like this, which isn't very pretty:
var parent = fixture.Build<Parent>().Without(p => p.Children).CreateAnonymous();
parent.Children = fixture.CreateMany<Child>(10).ToArray();
foreach (var i in parent.Children)
{
i.ParentId = parent.Id;
}
It feels like there's a better way to do this that I am missing? I looked into creating a custom ISpecimenBuilder but didn't manage to solve it that way either.
AutoFixture is based on a set of rules and assumptions about the API it may be asked to work with. Consider that it's been created and compiled without any prior knowledge of the Child and Parent classes, or any other types in a given API. All it has to work with is the public API.
Think of AutoFixture as a very dim programmer who doesn't even understand your language (not even English). The more fool-proof you can make your API, the easier it will be to use AutoFixture with it.
The problem with circular references like the Parent/Child relationship described here is that it breaks encapsulation. You'll need to create at least one of the class instances initially in an invalid state. That it's difficult to make AutoFixture work with such an API should mainly be taken as a warning sign that the API might benefit from refactoring.
Additionally, the .NET Framework Design Guidelines recommends against exposing arrays as properties - particularly writable properties. Thus, with a better encapsulated design, the API might be much easier to work with, both for AutoFixture and yourself and your colleagues.
Given the API above, I don't see any way this can be made much easier to work with. Consider how to remove the circular reference and make collection properties read-only, and it will be much easier.
For the record, I haven't written an API with a circular reference for years, so it's quite possible to avoid those Parent/Child relations.

Data Inheritance in C#

Is there a known pattern to inherit data in a hierarchical object structure? I have a hierarchical 'Item' structure which needs to inherit its 'Type' from its 'Parent' (have the same data as default). The type of sub item can be modified by its own, and when the type of parent Item changes, all sub items which their type is not changed, should get the new type of parent.
Note that I cannot fake it like
public string Type
{
get
{
if (type == null)
return Parent != null ? Parent.Type : null;
return type;
}
}
'cause I have to fill the values in the database, and the structure is too deep to use recursion and not worry about the performance.
The only way I can think of it now is
public string Type
{
set
{
type = value;
UpdateUnchangedChildren(value);
}
}
public int AddChild(Item item)
{
item.Type = Type;
return Items.Add(item);
}
Is there a better way?
Thanks.
It's a common problem, usually related to maintenance of various hierarchical settings/configurations. So, I guess a solution to it can be considered "a pattern".
Anyways, from the internal architecture perspective you have 2 major options:
normalized structure
denormalized structure
"Normazlied" is the one implemented with recursion. A particular piece of data is always stored in one place, all the other places have references to it (e.g., to parent). The structure is easily updated, but readng from it may be a problem.
"Denormalized" means that every node will store the whole set of settings for its level and whenever you update a node it takes some time to go down the hierarchy and corect all the children nodes. But the reading operation is instant.
And so the "denormalized" version seems to be more widely used, because the common scenario with settings is that you update them rarely, while read them often, hence you need better read performance. For example, Windows ACL security model uses the "denormalized" approach to make security checks fast. You can read how they resolve conflicts between the "inherited" and explicit permissions (ACEs) by checking them in a specific order. That might be an overkill for your particular system though, you can simply have a flag that a particular value was overriden or, on the opposite, reset to "default"...
Further details depend on your system needs, you might waht to have a "hybrid" architecture, where some of the fields would be "normalized" and some others won't. But you seem to be on the right way.
I'm not 100% sure what it is you are trying to do... but you could use generics to pass the type of a parent object into a child object... But having a setter there doesn't really make sense... The Parent object's type will be set when it's instantiated, so why would you have a setter there to change it.
Assuming you have something like this...
public class Child<T>
{
public string Type
{
get { return typeof(T).ToString(); }
}
}
So then, when you have a Parent Object of any type, you can pass that to your Child Property...
public class ParentA
{
public Child<ParentA> ChildObj { get; set; }
}
public class ParentB
{
public Child<ParentB> ChildObj { get; set; }
}
public class ParentC
{
public Child<ParentC> ChildObj { get; set; }
}
Calling any of those ChildObj.Type Properties will return ParentA, ParentB & ParentC respectively.
Buit I've a funny feeling you haven't fully explained what it is you're trying to do.
Can you post some more code examples showing a Parent Class & Child/Item Class
An obvious optimization would be to cache the value obtained from the parent when reading the type. That means you will only traverse each path at most once (whereas the naive solution means you'll be traversing each subpath again and again for each path containing it, which means up to O(h^2) instead of O(h)). That would work great if you have more reads than writes.
Consider this:
class Node
{
string _cachedParentType = null;
string _type;
string Type
{
get { return _type ?? _cachedParentType ?? (_cachedParentType = Parent.Type); }
set
{
_type = value;
foreach (var child in Children) { child._cachedParentType = null; }
}
}
}
This means with enough reads and few writes, reading becomes O(1) in the best case or, at worst, a "cache miss" will cost you O(h) with h being the height of the tree; while updating is O(k) with k being the branching level (because we only update one layer down!). I think this will generally be better than the UpdateUnchangedChildren solution (which I presume updates nodes recursively all the way to the leafs), unless you're doing WAY more reads than writes.
"...the structure is too deep to use recursion and not worry about the performance."
Have you actually measured this? How many items are you dealing with, how deep is the structure, and how common is it for items to not have their own "Type" value? What are your performance goals for the application, and how does the recursive solution compare with those goals?
It is very common for people to think that recursion is slow and therefore eliminate it from consideration without ever trying it. It is NEVER a good idea to reject the simplest design for performance reasons without measuring it first. Otherwise you go off and invent a more complicated solution when the simpler one would have worked just fine.
Of course, your second solution is also using recursion, just going down the hierarchy instead of up. If the child inserts are happening at a different time and can absorb the possible performance hit, then perhaps that will be more acceptable.

Implementing a tree in c# managing parent-child

I am implementing a tree think of it as a folder structure so I have a class that looks like:
public class Folder
{
//Various Props like Name etc.
public IList<Folder> Children{get;}
public Folder Parent {get;}
}
Now what I want is to be able to walk up and down the tree so given a root I can find a leaf, and given a leaf I can find the root node. So each child needs a parent. Now the question is what is the best way to add a new node to the tree. I have used two solutions in the past:
Add an AddChild(Folder) method to Folder which handles adding the folder, and can set the parent. The problem with this is I now have to lock my Children collection so you can't bypass this method.
Create my own Children collection which will be given a reference back to the instance, so it can handle setting the parent on the add. The problem with this I have to implement a new collection.
Use a collection which has events when items are added or deleted.
I am curious what patterns people generally use, and then if anyone has any suggestions for my specific use case. I am using nHibernate to persist my tree to SQL server. I'd rather not implement a custom collection as it's a lot of code to get this to work for something which is a very small part of my application.
After looking on MSDN you could try this:
List<Folder> children;
public ReadOnlyCollection<Folder> Children
{
get { return this.children.AsReadOnly(); }
}
If your private member must be declared as an IList then we can copy that into a list and then return it. But I really don't see a problem with using a concrete implementation as a private member. Changing the implementation later won't break compatibility.
IList<Folder> children;
public ReadOnlyCollection<Folder> Children
{
get
{
return new List<Folder>(this.children).AsReadOnly();
}
}
Go with number 1, but make your Children property IEnumerable so that users can't add to the collection.
Personally, I'd go with method 1. Allowing client code to manipulate the Children collection directly violates encapsulation in any case, so 'locking' the Children collection is the Right Thing™.
The 'proper' strategy for keeping your node relationships correct depends on the needs of your clients. I'm presuming that in this specific situation, you'd want clients to be able to alter the child nodes themselves, but not the Children collection. If that's the case, I think Rob Prouse's suggestion (make the Children property return an IEnumerable) is probably the best choice. In other situations, a ReadOnlyCollection would probably be better.
Implementing a custom collection's a lot of work; implementing a wrapper to an existing collection class that exposes only two or three methods isn't. And it seems like that's what you're looking for, judging from your response to JayArr. Something like:
public class ChildCollection
{
// _Children is maintained by the Folder class, hence the internal access specifier
internal Dictionary<KeyType, Folder> _Children = new Dictionary<KeyType, Folder>;
public this[KeyType key]
{
get
{
return _Children[key];
}
}
public IEnumerable<KeyType> Keys
{
get
{
return _Children.Keys;
}
}
}
I would go with option 1 and then make the Children property look like this:
public IEnumerable<Folder> Children
{
get { return this.children.GetEnumerator(); }
}
Now AddChild must be called to add the children. The collection is not accessible.

Categories

Resources