Propagate properties to parent control C# - c#

Is there any way how to propagate properties from child control into parent - so I can access property like - Parent.Property1 instead of Parent.Child.Property1 ? I cant use inheritance - my parent cant be extended child type - its inherited from different class.
Also I dont wanna add code for each property from child to parent like:
public object Property1
{
get{ return Child.Property1; }
set{ ChildProperty1 = value; }
}
Maybe using reflection - something like this?
public PropertyInfo[] Properties
{
get{ return Child.GetType().GetProperties(); }
set{ Child.GetType().GetProperties().SetValue() = value.GetValue()}
}
Thanks

Without changing the parent not, but you don't need to inherit the child, you can just pass through the property:
In the parent:
public object Property1
{
get { return Child.Property1; }
set { Child.Property1 = value; }
}
Then you can access Parent.Child.Property1 also by Parent.Property1.
EDIT: As you just edited you question to NOT want to do it that way, then back to "No, it is not possible."!

Well, that's the very old design problem you're facing - there is no clear-cut solution to that in C#.
That's typically resolved by wrapping up child properties (as pointed out already by all), which could be tedious - or b) exposing a child, which isn't often the best way.
I wouldn't suggest the reflection as you don't want to do that really. Performance aside (might not notice that on small apps but if you adopt that style of coding it'd get back to haunt you soon), that's just resulting in a bad design, messy code and hard to follow, e.g. you don't know where and who could be using reflection to change some other part, or access - you don't want to do that to your 'own code' (in this case), only normally if forced into it, using other code - or in some situations (not rare, every larger bit of code has some sort of reflection in it but for a good reason) that warrants that, i.e. you have no other way of doing things, like crossing generic non-generic world, getting dynamic properties etc.
Having said that,
you could redesign some things usually to achieve something desirable in some other way.
E.g. by using interfaces and indirectly exposing a child - or moving things around so that the class that owns the properties is in the right place 'in the chain' when / where you need to use properties.
i.e. it's hard to explain this - as this requires a very specific scenario in mind and then a very specific solution - but normally you always have some sort of 'winning design' that solves those problems, and the fact that you're facing such a problem usually means..
1) you might not have organized classes in the best way for the problem at hand, and you're forced to trying to propagate the properties - instead of rearranging the responsibilities between the classes,
2) or you simply have such a situation that there is no other way around it :)...
... hope this helps some

Related

Mimicking multiple inheritance in C# without interfaces

I know that multiple inheritance in C# is only allowed by using Interfaces and that there are very valid reasons why multiple inheritance can quickly become a real headache. (Working in .NET Framework if that makes any difference to the answers)
However.
In working on various projects accross many classes I find myself returning to the same patterns to handle behaviour.
For example I have an Interface IXMLSavable which requires the functions GetXML() and SetFromXML(XElement e) to be implemented. The way I implement this in every class is, that I write different functions for different versions of the XML (If I changed something in the GetXML() I want to maintain backwards compatibility...). And according to a version-attribute on the root Element I switch case to the right ReadVersionX(XElement e) function so all my data stays consitent.
Another example would be centered around eventing. If for example I want to implement a "stop firing events for the time being"-Lock I would go about thusly:
private bool suppressEvents;
public bool SuppressEvents
{
get { return suppressEvents; }
set
{
bool prevValue=SuppressEvents;
suppressEvents=value;
if(prevValue!=SuppressEvents && !SuppressEvents) TheChangeEvent?.Invoke();
}
}
So I can run multiple operations on the object in question without it giving of a right old firework display of events. Again: This code will be almost unchanged for a lot of classes.
For the XML one I could refactor this to a class that has a Dictionary<int,delegate> ReadFunctions which I could then set in every implementation (I concede that there needs to be a bit of customisation in the "implementing" class) and reduce the amount of bolierplate for every class (the explicit switching on the version attribute) to just filling this dictionary.
The eventing one could go into a class on its own quite readily, I would probably only need to hook up the right event to the invokation, but that could easily be remedied by an abstract function I will have to implement (again: customisation still necessary but much less boilerplate).
Each "now-class-was-interface" on its own would make a splendid base class for any object. I could use functionality down an inheritance tree and customise it by overwriting functionality with new if I would need it.
The problem starts when I want to combine the two now-classes together. Due to the limitation in C# (which, again, is there for a reason) I cannot inherit from both above described classes at the same time. This would only be possible if I have one of these classes inherit from the other. Which would be possible, but would lead to a whole lot of a different headache when I want one functionality but not the other. Or the other functionality and not the one. The way around that would be to create a plethora of permutation classes (so one class for each combination of the functionaities). And while that would solve the problem it would probably be a nightmare to maintain.
So the real question is: Is there a way to correctly plug in different already implemented functionality into a class in an inheritance like manner that allows the addition of multiple distinct functionality packages as opposed to interfaces that cannot by the very nature of themselves provide any concrete implementation.
In many cases you can avoid inheritance with the use of interfaces/default interface methods/extension methods, decorators, or some other pattern.
In your case with xml you could simply change your interface to have one ReadMethod per version, and use a extension method to select the correct one
public interface IXMLReadable{
void ReadVersion1(XElement e);
void ReadVersion2(XElement e);
}
public static class IXMLReadableExtensions {
public static void Read(this IXMLReadable self, XElement e){
// Read version from xml, call ReadVersion1 or ReadVersion2
}
}
default interface methods would do more or less the same thing, with the added advantage of allowing the class to override the Read-method if it wants some other behavior.
However, my preferred solution would be to instead convert your object to a Data Transfer Object (DTO), add any required serialization attributes to this object, and use a library to serialize this. Added fields etc can usually be accommodated by just marking it as optional. Larger changes can usually be done by creating a new DTO class.
One way to solve your event problem could be to move this logic to a separate class
public class SuppressibleEvent
{
private bool suppressEvents;
private bool pendingEvent;
public void Raise()
{
if (!suppressEvents)
{
TheChangeEvent?.Invoke(this, EventArgs.Empty);
}
else
{
pendingEvent = true;
}
}
public event EventHandler TheChangeEvent;
public bool SuppressEvents
{
get => suppressEvents;
set
{
suppressEvents = value;
if (!suppressEvents && pendingEvent)
{
TheChangeEvent?.Invoke(this, EventArgs.Empty);
pendingEvent = false;
}
}
}
}
Optionally you may add a interface, so that only the owner can raise the event, but others can listen and register. You could also add methods/events to your class that just forwards to the actual implementation.
The overall point is that there is usually a better pattern to use than implementation inheritance. Some might require a bit more code, but usually gain a bit of flexibility as a result.

Composition and interaction with owner instance

I was wondering what is the best practice for accessing the owner instance when using composition (not aggregation)
public class Manager
{
public List<ElementToManage> Listelmt;
public List<Filter> ListeFilters;
public void LoadState(){}
}
public class Filter
{
public ElementToManage instance1;
public ElementToManage instance2;
public object value1;
public object value2;
public LoadState()
{
//need to access the property Listelmt in the owner instance (manager instance)
//instance1 = Listelmt.SingleOrDefault(...
}
}
So far I'm thinking about two possibilities:
Keep a reference to the owner in the Filter instance.
Declare an event in the Filter class. The manager instance subscribe to it, and the filter throw it when needed.
I feel more like using the second possibility. It seems more OOP to me, and there is less dependencies between the classes ( any refactoring later will be easier),
But debugging and tracing may be a bit harder on the long run.
Regarding business layer classes, i don't remember seeing events for this purpose.
Any insight would be greatly appreciated
There is no concept of an "owner" of a class instance, there should not be any strong coupling between the Filter instance and the object that happens to have an instance of it.
That being the case an event seems appropriate: It allows for loose coupling while enabling the functionality you want. If you went with option #1 on the other hand you would limit the overall usefulness of the Filter class - now it can only be contained in Manager classes, I don't think that is what you would want.
Overall looking at your code you might want to pass in the relevant data the method LoadState operates on so it doesn't have to "reach out".
I recomend the reference to owner of filter instance. The event can be handled by more handlers and can change result of previous handler(s). And you propadly don't want change the owner during lifetime of Filter without notification the Filter instance.
My short answer : Neither.
First option to keep a reference to the owner is problematic for several reasons. Filter class no longer has a single responsibility. Filter and Manager are tightly coupled. etc.
Second option is only a little better, and yes I've used events in similar scenearios, it rarely if ever ends well.
It's difficult to give a definite advice without more specific details. Some thoughts:
1) Are you sure your classes are as they should be? Maybe there should be a class to compose a single ElementToManage and a single Filter ?
2) Who is responsible for creating a Filter? For example, if it is Manager, maybe the Manager can give the list as a construction parameter? Maybe you can create a FilterFactory class that does any needed initializations.
3) Who calls filter.LoadState()? Maybe the needed list could be passed as a parameter to the LoadState() method.
4) I frequently use an "Initialization Design Pattern" (my terminology) For example I'll have a BinaryTree where parent and child will point to each other. The Factory constructs the nodes in a plain state, and than calls an initialize method with other needed objects. The class becomes complicated because I probably need to ensure that an uninitialized object raises an error for every other usage, and need to ensure that an object is initialized only once, is initialized only through the Factory, etc. But if it works, it is usually the best solution, in my opinion.
5) I'm still trying to learn "Dependency Injection" and getting nowhere, I guess it may have something to do with your question. I wonder if someone will come with an answer involving Dependency Injection.

What design pattern will you choose?

I want to design a class, which contains a procedure to achieve a goal.
And it must follow some order to make sure the last method, let's say "ExecuteIt", to behave correctly.
in such a case, what design patter will you use ?
which can make sure that the user must call the public method according some ordering.
If you really don't know what I am saying, then can you share me some concept of choosing a design patter, or what will you consider while design a class?
I believe you are looking for the Template Method pattern.
Template Method is what you want. It is one of the oldest, simply a formalization of a way of composing your classes.
http://en.wikipedia.org/wiki/Template_method_pattern
or as in this code sample:
abstract class AbstractParent // this is the template class
{
// this is the template method that enforces an order of method execution
final void executeIt()
{
doBefore(); // << to be implemented by subclasses
doInTheMiddle() // also to be implemented by subclasses
doLast(); // << the one you want to make sure gets executed last
}
abstract void doBefore();
abstract void doInTheMiddle();
final void doLast(){ .... }
}
class SubA extends AbstractParent
{
void doBefore(){ ... does something ...}
void doInTheMiddle(){ ... does something ...}
}
class SubB extends SubA
{
void doBefore(){ ... does something different ...}
}
But it seems you are fishing for an opportunity to use a pattern as opposed to use a pattern to solve a specific type of problem. That will only lead you to bad software development habits.
Don't think about patterns. Think about how you would go around solving that specific problem without having patterns.
Imagine there were no codified patterns (which is how it was before). How would you accomplish what you want to do here (which is what people did to solve this type of problems.) When you can do that, then you will be in a much better position to understand patterns.
Don't use them as cookie cutters. That is the last thing you want to do.
Its basically not a pattern, but: If you want to make sure, the code/methods are executes in a specific order, make the class having only one public method, which then calls the non-public methods in the right sequence.
The simple and pragmatic approach to enforcing a particular sequence of steps in any API is to define a collection of classes (instead of just one class) in such way that every next valid step takes as a parameter an object derived from the previous step, i.e.:
Fuel coal = CoalMine.getCoal();
Cooker stove = new Cooker (gas);
Filling apple = new AppleFilling();
Pie applePie = new Pie(apple);
applePie.bake(stove);
That is to say that to bake a pie you need to supply a Cooker object that in turn requires some sort of a suitable fuel to be instantiated first. Similarly, before you can get an instanse of a Pie you'd need to get some Filling ready.
In this instance the semantics of the API use are explicitly enforced by its syntax. Keep it simple.
I think you have not to really execute nothing, just prepare the statements, resources and whatever you want.
This way whatever would be the order the user invokes the methods the actual execution would be assured to be ordered; simply because you have the total control over the real execution, just before execute it.
IMHO Template Method as very little to do with your goal.
EDIT:
to be more clear. Make your class to have one public method Execute, and a number of other public methods to tell your class what to do (when to do it is a responsibility of you and not of the user); then make a number of private methods doing the real job, they will be invoked in the right order by your Execute, once the user has finished settings things.
Give the user the ability of setting, keep execution for your self. He tells what, you decide how.
Template Method is rational, if you have a class hierarchy and base class defines protected operation steps in its public template method. Could you elaborate your question?
As general concept you should choose a pattern as a standard solution to a standard problem so, I agree with Oded, the "Template Method" seems to fit your needs (but what you explained is too few maybe).
DonĀ“t use pattern as "fetish", what you have to keep in mind is:
How can I figure my problem in a standard way?
There is a pattern for this?
Is this the simplest way?

Should you use accessor properties from within the class, or just from outside of the class? [duplicate]

This question already has answers here:
What is the best way to access properties from the same class, via accessors or directly? [closed]
(5 answers)
Closed 9 years ago.
I have a class 'Data' that uses a getter to access some array. If the array is null, then I want Data to access the file, fill up the array, and then return the specific value.
Now here's my question:
When creating getters and setters should you also use those same accessor properties as your way of accessing that array (in this case)? Or should you just access the array directly?
The problem I am having using the accessors from within the class is that I get infinite loops as the calling class looks for some info in Data.array, the getter finds the array null so goes to get it from the file, and that function ends up calling the getter again from within Data, array is once again null, and we're stuck in an infinite loop.
EDIT:
So is there no official stance on this? I see the wisdom in not using Accessors with file access in them, but some of you are saying to always use accessors from within a class, and others are saying to never use accessors from with the class............................................
I agree with krosenvold, and want to generalize his advice a bit:
Do not use Property getters and setters for expensive operations, like reading a file or accessing the network. Use explicit function calls for the expensive operations.
Generally, users of the class will not expect that a simple property retrieval or assignment may take a lot of time.
This is also recommended in Microsoft's Framework Design Guidelines.;
Do use a method, rather than a
property, in the following situations.
The operation is orders of magnitude
slower than a field set would be. If
you are even considering providing an
asynchronous version of an operation
to avoid blocking the thread, it is
very likely that the operation is too
expensive to be a property. In
particular, operations that access the
network or the file system (other than
once for initialization) should most
likely be methods, not properties.
I think its a good idea to always use the accessors. Then if you need any special logic when getting or setting the property, you know that everything is performing that logic.
Can you post the getter and setter for one of these properties? Maybe we can help debug it.
I have written a getter that opens a file and always regretted it later. Nowdays I would never solve that problem by lazy-constructing through the getter - period. There's the issue of getters with side-effects where people don't expect all kinds of crazy activity to be going on behind the getter. Furthermore you probably have to ensure thread safety, which can further pollute this code. Unit-Testing can also become slightly harder each time you do this.
Explicit construction is a much better solution than all sorts of lazy-init getters. It may be because I'm using DI frameworks that give me all of this as part of the standard usage patterns. I really try to treat construction logic as distinctly as possible and not hide too much, it makes code easier to understand.
No. I don't believe you should, the reason: maintainable code.
I've seen people use properties within the defining class and at first all looks well. Then someone else comes along and adds features to the properties, then someone else comes along and tries to change the class, they don't fully understand the class and all hell breaks loose.
It shouldn't because maintenance teams should fully understand what they are trying to change but they are often looking at a different problem or error and the encapsulated property often escapes them. I've see this a lot and so never use properties internally.
They can also be a performance hog, what should be a simple lookup can turn nasty if someone puts database code in the properties - and I have seen people do that too!
The KISS principle is still valid after all these years...!
Aside from the point made by others, whether to use an accessor or a field directly may need to be informed by semantics. Some times the semantics of an external consumer accessing a property is different from the mechanical necessity of accessing its value by internal code.
Eric Lippert recently blogged on this subject in a couple of posts:-
automatic-vs-explicit-properties
future-proofing-a-design
If using an Get method leads to this kind of error, you should access the value directly. Otherwise, it is good practice to use your accessors. If you should modify either the getter or setter to take specific actions in the future, you'll break your object if you fail to use that path.
I guess what you are trying to implement is some sort of a lazy-loading property, where you load the data only when it is accessed for the first time.
In such a case I would use the following approach to prevent the infinite loop:
private MyData _data = null;
public MyData Data
{
get
{
if (_data == null)
_data = LoadDataFromFile();
return _data;
}
}
private MyData LoadDataFromFile()
{
// ...
}
In other words:
don't implement a setter
always use the property to access the data (never use the field directly)
You should always use the accessors, but the function that reads the value from the file (which should be private, and called something like getValueFromFile) should only be called when the value has to be read from the file, and should just read the file and return the value(s). That function might even be better off in another class, dedicated to reading values from your data file.
If I am understanding it right, you are trying to access a property from within it's implementation (by using a method that calls the same property in the property's implementation code). I am not sure if there any official standards regarding this, but I would consider it a bad practice, unless there would be a specific need to do it.
I always prefer using private members within a class instead of properties, unless I need the functionality property implementation provides.

Logic in get part of property. Good practice?

When databinding my xaml to some data I often use the "get" part of a property to do some logic. Like giving to sum of totals of a list or a check if something is positive.
For example:
public List<SomeClass> ListOfSomeClass{get;set;}
public double SumOfSomeClass
{
get
{
return ListOfSomeClass.Sum(s => s.Totals);
}
}
public bool SumPositive
{
get
{
if(SumOfSomeClass >= 0)
return true;
else
return false;
}
}
This way I can bind to SumPositive and SumOfSomeClass. Is this considered good practice? Even if it gets more complex than this? Or would it be better call a method and return the outcome? What about calls to another class or even a database?
Property getters are expected to be fast and idempotent (i.e. no destructive actions should be performed there). Though it's perfectly fine to iterate over an in-memory collection of objects, I wouldn't recomment doing any kind of heavy lifting in either get or set parts. And speaking of iterating, I'd still cache the result to save a few milliseconds.
Yes, unless it is an operation that might have performance implications. In that case you should use a method instead (as it is more intuitive to the end user that a method might be slow whereas a property will be quick)
I like your naming conventions and I agree entirely with using content such as your example in property getters, if you're delivering an API to be used with binding.
I don't agree with the point others have made about moving code into a method just because it is computationally heavy - that's not a distinction I'd ever make nor have I heard other people suggest that being in a method implies slower than a property.
I do believe that properties should be side-effect-free on the object on which they are called. It's vastly more difficult to guarantee they have no effect on the broader environment - even a relatively trivial property might pull data into memory or at least change the processor cache or vm state.
I say yes, but try to store on a private variable de results of ListOfSomeClass.Sum(s => s.Totals). Specially if you use it more than once.
I don't see any direct issue (unless the list is quite huge) but I would personally use the myInstance.SomeList.Sum() method if possible (.net >= 2.0).
For basic calculations off of fields or other properties in the collection it would be acceptable to do that inside the Get property. As everyone else said true logic should never be done in the getter.
Please change that getter to this:
public bool SumPositive
{
get
{
return SumOfSomeClass >= 0;
}
}
You are already using a boolean expression, no need to explicitly return true or false
Having complex logic in getters/setters is not a good practice. I recommend to move complex logic to separate methods (like GetSumOfXYZ()) and use memoization in property accessors.
You can avoid complex properties by using ObjectDataProvider - it allows you to define method to pull some data.
Depends... if this was on a domain entity then I wouldn't be in favor having complex logic in a getter and especially not a setter. Using a method (to me) signals a consumer of the entity that an operation is being performed while a getter signals a simple retrieval.
Now if this logic was in a ViewModel, then I think the getter aspect is a little more forgivable / expected.
I think that there is some level of logic that is expected in Getters and Setters, otherwise you just have a kind of convoluted way to declare your members public.
I would be careful about putting any logic in the Getter of a property. The more expensive it is to do, the more dangerous it is. Other developers expect a getter to return a value immediately just like getting a value from a member variable. I've seen a lot of instances where a developer uses a property on every iteration of a loop, thinking that they are just getting back a value, while the property is actually doing a lot of work. This can be a major slowdown in your code execution.

Categories

Resources