Best way to implement an "Inheritance Square" - c#

Here is my class diagram.
The problem is in AgendaInstance (see red dot). I'm trying to inherit (reuse) Agenda.Tasks to contain its own tasks, which are of type TaskInstance, a subtype of Task.
I can put this.Tasks.Add(new TaskInstance()); inside AgendaInstance. That code works, but the problem comes in when I try to serialize or bind. Since Tasks is statically bound to Task all that gets serialized (e.g., to xml) or bound (e.g., to a grid row) are the properties of Task, not TaskInstance.
Is there a design pattern I can use here to overcome this issue? I don't want to shadow (new) Tasks in AgendaInstance. That would defeat the purpose of having an inheritance hierarchy. My midi-chlorians tell me there's a solution that is higher than directly dealing with serialization or binding specifics; it's a "deeper" issue that lends itself to a more fundamental solution. I'm going to fiddle around with generics but perhaps you know of an even better way or a better pattern.

90% of my experience with xml serialization is bad. They tend to break inheritance model and does not support interfaces. Therefore, it resulting you to hack and tinker the existing class to suit the serialization. XmlIgnore and duplicated properties usually come to hand when dealing with it.
Therefore usually I create another class for the serialization purpose only. Ex: AgendaSerializable, with TaskSerializeable as Tasks. The benefit is: you keep your inheritance and data model clean, while you need to handle with data conversion as the cons.
may the force be with you.

You could make Agenda generic on the Task, like this:
class Agenda<T> where T : Task {
public IList<T> Tasks {get; private set;}
...
}
class AgendaInstance<TaskInstance> {
...
}
Now there is only one Task property in the hierarchy. However, Agenda requires a type parameter to be instantiated, so what used to be a "plain" Agenda becomes Agenda<Task>.

Related

Defining properties of UI using Attributes

For a new project, I was recently asked to investigate a method of attaching information related to UI rendering to business objects in a WPF application. For example a report class:
class ExecutionReport
{
[Displayable(Bold, Background=Color.Red)]
public String OrderId{get; private set;}
[Displayable(Normal, HAlignment=Center)]
public String Symbol {get; private set;}
// this should be hidden as it doesn't have DisplayableAttribute
public String ClientOrderId {get; private set;}]
[Displayable(Normal, HAlignment=Right,
Format("If [Position] < 0 then Background=Color.Red"),
Format("If [Position] > 0 then Background=Color.Lime"),
DisplayFormat("+#;-#;0")]
public Int Position {get; private set;}
}
This is a very new approach for me as typically in most wpf MVVM applications I have worked on there has been a clear separation of the view and viewmodel and I strive as much as possible to keep UI specific details out of the VM. Instead I would lean towards writing this using resource dictionaries and simple converters applied on the bindings in the view layer.
My questions are: Are there any wpf/mvvm frameworks out there that use this kind of an implementation? If so I'm curious to see how it would be achieved.
Are there any obvious pitfalls? The first couple things that come to my mind are
Change notification (ie. INotifyPropertyChanged to trigger an update of the view). Would the implementation of this be a lot harder now?
Difficulty in being able to leverage resource dictionaries for system wide values. For example, maybe I wanted to change the color of red being used throughout the application. I would have to ctrl + f through and find every place in business objects where it was used and change it instead of being able to modify a single StaticResource
Inability to leverage DesignTime DataContexts
Performance. Seems likes this would require heavy use of reflection which might not be as performant as typical value converters
I'm very interested to see if I'm correct on the second and third points or if both of these things could still be acheived?
Ultimately I feel that this is a bad design and I'm leaning towards writing a different implementation to show the interested party how I would typically approach this kind of problem. Just want to make sure I'm not missing something obvious that might actually make this more elegant.
IMO this seems like a horrible idea, they all seems like examples that should be implemented as XAML converters.
All of the points list seem to be valid reasons to avoid doing this.
Note: There are a set of attributes in the framework which provide some UI functionality already (very limited), see the System.ComponentModel.DataAnnotations namespace.
This approach is very popular and it's called aspect oriented programming (ASP.NET MVC leverages it a lot). The most popular library to write this fast is PostSharp (see customers case studies, there are some companies which have used it for WPF). The best thing in PostSharp is that uses compile-time weaving.
For the first point:
PostSharp got well tested NotifyPropertyChanged aspect, you can add [NotifyPropertyChanged] attribute to class and all properties will call PropertyChanged when value gets changed.
For the second point: you can always make your attribute to look for StaticResources and pass resource key in attribute.
For the third (although I'm not 100% sure about it) and fourth point: compile time weaving means that aspect is "appended" to code on compilation - like you would have written it inside method/property to which you have appended attribute. It's like post-build compiler and doesn't use reflection (if aspect you wrote doesn't use reflection) so performance is really good.
However in example you gave I'd rather go with value converters and styles like #AwkwardCoder said - but aspects(attributes) are also useful with "view" for example: they're great for validiation.
I agree that this seems like a horrible idea, and your comment ...
in most wpf MVVM applications I have worked on there has been a clear
separation of the view and viewmodel and I strive as much as possible
to keep UI specific details out of the VM. Instead I would lean
towards writing this using resource dictionaries and simple converters
applied on the bindings in the view layer
... I think sums up why and how to avoid it.
Tying your business objects directly to implementation details such as colour, horizontal alignment, or position, seems like a short-term win (but long term hell).

Proxy objects to simulate a soon-to-be-created database

I have a database that contains "widgets", let's say. Widgets have properties like Length and Width, for example. The original lower-level API for creating wdigets is a mess, so I'm writing a higher-level set of functions to make things easier for callers. The database is strange, and I don't have good control over the timing of the creation of a widget object. Specifically, it can't be created until the later stages of processing, after certain other things have happened first. But I'd like my callers to think that a widget object has been created at an earlier stage, so that they can get/set its properties from the outset.
So, I implemented a "ProxyWidget" object that my callers can play with. It has private fields like private_Length and private_Width that can store the desired values. Then, it also has public properties Length and Width, that my callers can access. If the caller tells me to set the value of the Width property, the logic is:
If the corresponding widget object already exists in the database, then set
its Width property
If not, store the given width value in the private_Width field for later use.
At some later stage, when I'm sure that the widget object has been created in the database, I copy all the values: copy from private_Width to the database Width field, and so on (one field/property at a time, unfortunately).
This works OK for one type of widget. But I have about 50 types, each with about 20 different fields/properties, and this leads to an unmaintainable mess. I'm wondering if there is a smarter approach. Perhaps I could use reflection to create the "proxy" objects and copy field/property data in a generic way, rather than writing reams of repetitive code? Factor out common code somehow? Can I learn anything from "data binding" patterns? I'm a mathematician, not a programmer, and I have an uneasy feeling that my current approach is just plain dumb. My code is in C#.
First, in my experience, manually coding a data access layer can feel like a lot of repetitive work (putting an ORM in place, such as NHibernate or Entity Framework, might somewhat alleviate this issue), and updating a legacy data access layer is awful work, especially when it consists of many parts.
Some things are unclear in your question, but I suppose it is still possible to give a high-level answer. These are meant to give you some ideas:
You can build ProxyWidget either as an alternative implementation for Widget (or whatever the widget class from the existing low-level API is called), or you can implement it "on top of", or as a "wrapper around", Widget. This is the Adapter design pattern.
public sealed class ExistingTerribleWidget { … }
public sealed class ShinyWidget // this is the wrapper that sits on top of the above
{
public ShinyWidget(ExistingTerribleWidget underlying) { … }
private ExistingTerribleWidget underlying;
… // perform all real work by delegating to `underlying` as appropriate
}
I would recommend that (at least while there is still code using the existing low-level API) you use this pattern instead of creating a completely separate Widget implementation, because if ever there is a database schema change, you will have to update two different APIs. If you build your new EasyWidget class as a wrapper on top of the existing API, it could remain unchanged and only the underlying implementation would have to be updated.
You describe ProxyWidget having two functions (1) Allow modifications to an already persisted widget; and (2) Buffer for a new widget, which will be added to the database later.
You could perhaps simplify your design if you have one common base type and two sub-classes: One for new widgets that haven't been persisted yet, and one for already persisted widgets. The latter subtype possibly has an additional database ID property so that the existing widget can be identified, loaded, modified, and updated in the database:
interface IWidget { /* define all the properties required for a widget */ }
interface IWidgetTemplate : IWidget
{
IPersistedWidget Create();
bool TryLoadFrom(IWidgetRepository repository, out IPersistedWidget matching);
}
interface IPersistedWidget : IWidget
{
Guid Id { get; }
void SaveChanges();
}
This is one example for the Builder design pattern.
If you need to write similar code for many classes (for example, your 50+ database object types) you could consider using T4 text templates. This just makes writing code less repetitive; but you will still have to define your 50+ objects somewhere.

Ending with too many objects (layered design)

I have a lot of dropdown lists, custom grids on my webform which are displayed to the end user. Each is populated from database through a DAL. I have separate classes defined for each. However, I am thinking about reducing the number of classes, as every new requirement results in a separate custom object.
How can I reduce the no. of classes for such requirements? Should I use datasets, lists etc. ?
"Separate classes defined for each" and "How can I reduce the no. of classes for such requirements".
Do you really create a new class for each dropdown list?
From my experience, usually I generalized it by using this class:
public class DropDownItem<T>{
public string Display{get;set;}
public T Value{get;set;}
}
It can be done using Dictionary<T> though.
Never used in ASP.Net, but it works well in Winform and WPF databinding. In Asp.Net specific, I think normal select-option is enough to supply the need.
However for gridview, you need to generalize your classes to be more generic. Declare a class which has most of the parameter, which is nullable.
Example one request has 10 parameter, 5 is mandatory and other 5 is nullable. Grid A display param 1,2,3,4,5,7,8 and grid B display param 1,2,3,4,5,6,9,10. This way, you can use one class in many more grid.
Don't use DataSets/DataTable. It is better to use more class than DataSet. The maintainability will be better when using more class than DataSet, because it is strongly typed, rather than "COLUMN_NAME" in DataSet.
I hope this doesn't sound too critical, but if each requirement being added as a class is ending up as a lot work, perhaps you can look into inheritance to clean up boilerplate/shared code in those classes.
Generally a lot of small classes (that don't overlap functionality with other classes) is a good thing. The opposite complexity problem, the "god" class, where all your code is stuffed into fewer classes, is much worse.

Nested Validation

I'm wondering what the best approach is to take with validation.
If I have a complex object object composed of primitives, associations, and collections of other custom objects, should an IsValid() method validate the child objects as well as the required fields/keys of the root object?
If yes, should this be in some sort of abstract class, or is it best to use interfaces? With abstract, I would need to cast my child object interfaces to their concrete class definition in order to use an abstract method, whereas with interface validation I believe I can keep my children as interfaces as I call their validation methods.
Also, I'm not using MVC, but MVP with web forms (and trying to employ DDD principles).
Thanks.
UPDATE
I have a Aggregate root of ScheduledMeeting:
class ScheduledMeeting : BaseValidation
{
ScheduledMeetingID {get;set;}
ITimeSlot TimeSlot {get;set;}
IList<IMeetingAssignee> Assignees{get;set;}
DateTime meetingDate {get;set;}
AssignEmployees(IList<IEmployees> employees){}
}
Currently, there exists an abstract class of BaseValidation, which looks similar to the following:
public bool isValid(bool validateKeys)
{
if (validateKeys)
{
ValidateRequiredFields();
ValidateKeys();
}
else
{
ValidateRequiredFields();
}
return true;
}
where ValidateRequiredFields() and ValidateKeys() are overridden in implementing objects.
If I'm to use the above and cascade to IMeetingAssigned, I would need to loop in both ValidateKeys() and ValidateRequiredKeys() in ScheduledMeeting, casting IMeetingAssigned to concrete MeetingAssigned before then calling either ValidateKeys() or ValidateRequiredKeys() in this object (as it would also implement BaseValidation), and so on, all the way down.
UPDATE 2
I am stuck with .NET 3.5, and so cannot implement Code Contracts, etc. (as far as I'm aware).
Don't let your objects get into an invalid state in the first place, saves you a lot of 'IsValid' trouble.
Since you're employing Domain Driven Design I assume you have identified and modelled your classes as Aggregates.
To answer your question: Yes, the Aggregate Root is responsible of making sure that itself and everything that's contained is valid at any given point in time. The Aggregate Root should never be in an invalid state.
Update from the comments: Get rid of your validation interface. An Aggregate should never be in an invalid state in the first place. Whenever the state of your AR is about to change, make sure the resulting state wouldn't brake any invariants. If it would, the AR should reject the modification.
Enforce the invariants, don't validate after the fact.

Exposing Data as C# Properties - Good or Bad?

I am kinda not getting my head around this and was wondering if someone could please help me understand this.
So here is the problem, I have a class in which there are no required parameters. If user does not set the fields I can take the default value and carry on. Previously, I designed the same class as Joshua Bloch's Builder Pattern (Effective Java) (immutable object). I didn't had any good reason for making the class immutable except for the fact that I didn't wanted to have telescopic constructors and I didn't wanted to expose the data of the class.
But now, a fellow programmer friend is trying to convince me that it's okay to expose the data from the class using C# properties. I am not sure about this and I still feel that I should not be allowing user to muck with data.
Maybe I am completely wrong in my understanding. Could someone please clear my doubt about this, that whether it's good or bad to expose the data from the class?
If it is good then in what case it is good? Or else if someone can please point me to the article/book that clarifies this I would really appreciate it.
Thanks!
Expose the data in the class if it is needed or of interest outside the class, and do not do so if it is not. Expose it read-only if it's only needed to be read outside, and expose it as a full read/write property if it should be able to be changed. Otherwise, keep it in a private field.
immutable classes are easier to reason about especially in a multi tasking application, but they usually pay in performance (because when you need to change the value of a field you need to build the whole class again with the new value).
So, you could be ok or (depending on what you're coding) even better off with properties but as usual there's no silver bullet.
Settable properties are also the only way to code objects for some specific frameworks or libraries (e.g. ORMs like NHibernate), because you can't control how the library/framework initializes the object.
About constructors, C# 4 has optional parameters, that could help you avoid a long chain of constructors and also communicate much more clearly the fact that the parameters are optional.
However I can't think of many cases where you would end up with classes with a long list of optional parameters. If you find that you're coding classes like that too often (especially with the builder pattern, which is very elegant looking on the consumers' side of the class but complicates the code for the class itself) you may be using the wrong design. Are you sure you are not asking your classes to have too many responsibilities?
It basically depend on what's the purpose of your Class in the application context (could you give us more details?).
Anyway reckon that you could make a property safe from external changes by declaring is setter as private:
http://msdn.microsoft.com/en-us/library/bb384054.aspx
public string UserName { get; private set; }
It's "good" when the consumer of the class needs the data. You have two possibilities to offer properties.
if you only want to offer a property for information purpose, then choose a read only property like this:
public string MyInformation { get; private set; }
If you have the need to allow the consumer to change that property, then make the setter public like that:
public string MyChangeableInformation { get; set; }
But if the consumer has no need to get the information, then hide it in your class!
But now, a fellow programmer friend is trying to convince me that it's
okay to expose the data from the class using C# properties. I am not
sure about this and I still feel that I should not be allowing user to
muck with data.
As a rule of thumb, methods should represent actions whereas properties represent data. What your friend might have tried telling you is that you can expose the data of your class to outside world and still maintain full control on how other classes are accessing the data. In your case, as other have mentioned, you can use properties with private setters, such that the caller should not be able to modify the data.

Categories

Resources