Class inheritance versus Interface inheritance - theory

What is the difference between the Class inheritance and Interface inheritance? What of the above yields a lower coupling and a higher cohesion..

Class inheritance is more of a is a, so Square is a Shape whereas Interface is more of has the ability of, so Square has the ability of Resizable. But as you say you can couple multiple abilities using interface inheritance.

Related

Treeview inheritance relationship

Hallo,
I am trying to visualize a hierarchial (Is-a) class relationship using Treeview with WPF but I find it difficult.
I studied some code from the Internet like
http://www.codeproject.com/KB/WPF/TreeViewWithViewModel.aspx
These examples show a (has-a) class relationship and in this case the visualization with WPF+Treeview+Databinding is quite clean and intuitive.
On the contrary What I have is
public class Device() { }
public class VisionDevice() : Device { }
public class CommunicationDevice() : Device { }
public class SerialComm() : CommunicationDevice {}
public class Webcam : VisionDevice { }
I would like to visualize a WPF treeview structure like that
Device
VisionDevice
WebCam
CommunicationDevice
SerialComm
It is possible to do that using HierarchicalDataTemplate but the solution I found is not very elegant.
In conclusion: Treeviews is good for has-a class relationship but difficult to adapt to is-a relationship. Do you agree?
In conclusion: Treeviews is good for
has-a class relationship but difficult
to adapt to is-a relationship. Do you
agree?
Yes, tree views are good for structures where you know the root and have a connection from that to all its children (e.g. an object knows its properties and those properties are in turn objects which behave the same way), for types it is quite problematic since the traveral is the other way around, the supertype knows nothing of its subtypes but the subtypes know their supertypes (unlike objects which rarely have a reference to their parent).
To visualize types you would first need to collect all the leaves and while going towards the root check which types have a branch in common till you arrive at your target supertype. Not very elegant...
(Alternatively you can start at the root and query all types every time to see if their immediate parent is the type you are currently looking at, in terms of performance that should be even worse)

Any way to use interfaces with wpf HierarchicalDataTemplate

Hi I am using an interface IFooNode, which is part of a tree.
I wanted to display this tree in a TreeView using a HierarchicalDataTemplate.
This however does not work due to the interface.
I see two ways around that neither are what I would call "nice"
Find out what type really implements IFooNode (let's call it FooNode...), then find the assembly defining FooNode, add a Reference to that assembly and create a HierarchicalDataTemplate for FooNode (hoping the Implementating class never changes...)
Write a class MyCoolIFooNodeWrapperForWpf that wraps IFooNode, do not bind to the tree, but fill a list of MyCoolIFooNodeWrapperForWpf from the tree root and create a HierarchicalDataTemplate for MyCoolIFooNodeWrapperForWpf.
Can I somehow always apply a HierarchicalDataTemplate, no matter what type the data is (This I think would be the lesser evil...)
Any other Ideas?
You can use ItemTemplateSelector. In the selector's code you can check which interface your data object implements, and select the appropriate DataTemplate/HeirarchicalDataTemplate for this item.
The selector can both be applied to the container itself (ItemsControl.ItemTemplateSelector) and to your hierarchical data template (HeirarchicalDataTemplate.ItemTemplateSelector).
I think this is the lesser evil.
If you're not selecting from among multiple templates, you don't need to specify a data type on the template. If all of the objects in your tree implement your interface, just stick in a template using properties of that interface and you're good to go. You don't need to do anything in the template to make it specific to that interface.
If, for some reason, you need to do template selection based on what interface an object supports, you need to implement a template selector, and deal with the many-to-one problem that prevents WPF's built-in template selection mechanism from using interfaces in the first place. (That is, if you have a template for IFoo and one for IBar, what template do you use for an object that supports IFoo and IBar?)

WPF Properties on View Model Interface?

Using "vanilla" WPF (no MVVM framework like Prism).
Let me say up front that I absolutely advocate coding against abstractions/interfaces vs. implementations whenever possible.
In WPF, when you do your bindings in the view, you are really not coding your bindings against the viewmodel interface. You are really binding against an implementation of the viewmodel/datacontext. I think you could even argue that you are binding against a blank canvas, since the view doesn't really have any knowledge of what it will bind to at runtime.
So is a view model interface that includes every property that the view will bind to a useless abstraction? Should view model interfaces be leaner, only containing methods needed to change state (or handle commands, etc.).
I hope that question makes sense. :)
IMHO, the ViewModel is a Model for the View. 90% of the time, they will likely be 1 to 1... the useful part is moving the logic back into something more testable than XAML. Together, they compose the UI, but the UI behavior is separated from the UI presentation.
Personally, I do not make use of ViewModel interfaces. Between the Command Pattern and the loose binding that WPF and Silverlight use, I don't feel that abstraction would be useful.
I might use ViewModel interfaces in a system where the behavior and View state differed widely based on some business criteria. E.g. if your View was doing driver's license field editing and the fields required varied from state to state, you could make a case for a single, complex view bound to an IStateDriversLicenseViewModel interface. The correct one could be dependency injected based on the state you are working on and could expose properties like IsOrganDonorSectionVisible, to allow the view to reflect the correct changes. However, in this case I suspect a view composed of user controls would lead to fewer problems and less complexity in maintenance.
Abstraction [ie Interface programming] is useful if and only if loose coupling [ie an implementation-agnostic relactionship between consumer and producer] is desired.
Depending on your interpretation of Model View ViewModel [MVVM], tight coupling is permitted.
In practice, the typical scenario I have seen is a tight coupling between View and ViewModel and between View and Model(s). Typical, because Views are designed to fulfil a specific business requirement, ViewModels are tailored to suit the View to facilitate the View's business role.
As Ben Von Handorf suggests, that part of our application that actually adapts the underlying Model(s) to the ViewModel should be separate from our View [at least the declarative Presentation part]. So the adapting is typically captured by a View's implementation of a Command. So, while the declarative aspect of the View has no knowledge of the underlying Model(s) and is loosely coupled, the business implementation, or View's Command, introduces a tight coupling between View and Model. Again, this is cool because the View's sole purpose is to leverage that data in a specific manner as part of its business.
I too am a fan of abstraction, in particular Interface Programming, Dependency Injection [DI], and Inversion of Control [IoC]. However, when tight coupling makes sense, as it does in MVVM, then abstraction is an over-complication.
IMO, the simplicity introduced by tight coupling is what makes MVVM so attractive over its cousins in the Model View Controller [MVC] space.
I think it's generally not sensible to define an interface when you're only ever going to create one class that implements it. That describes every view model class I've ever created. And the view can't use interfaces anyway.
I do sometimes use interfaces in view model classes, but only if I need to define interactions between those classes that don't properly live in the model.

why not partial class to build the ViewModel in MVVM pattern?

Why not use partial class to build the ViewModel?
Since the definition of viewmodel classes have some definition of the data classes of datamodel, why not try to reduce some work, extending or making partial classes of the datamodel, completing them with command and etc.
In some cases this may be useful, but generally the ViewModel (or PresentationModel) has a different set of concerns that would muddle the rest of the model.
For example, imagine that you have an object model that represents an order processing workflow (everybody's favorite example.) This same model might be underlying a WPF, a web site, and perhaps even other services.
Within the WPF application there will be WPF-specific concerns for presentation. Adding these concerns to primary model (even as partial classes) results in a violation of SRP. Ultimately, it would obscure the intent of model and make it difficult for consumers of the model to know which parts of it where essential and which were incidental.
I agree but there are also extensions that seem to belong in a partial class as well. For example, a calculated field (say an invoice total), useful on the client and perhaps the viewmodel exposes it for data binding to the UI, however it's really a property of the entity. It may not be represented in the model itself because it can be derrived from the entity's other properties, and IMO better represented by using a partial class to extend the domain entity.

Dependence on DependencyObject and DependencyProperty

I'm building a Silverlight application and one of my caveats from last time was that if you need anything done right in Silverlight/WPF way you'd need to model your objects as a DependecyObject and use DependencyProperty(ies)
I find this model to be rather cumbersome, requiring static fields and initializers in half the classes I use, so is it a good idea to use the good-old event-driven (observer pattern?) in place of DependencyObject?
I'm aiming to minimize code bloat and boiler plates (I hate them) and really would like to know if anyone with experience in Silverlight/WPF has any tips/techniques for keeping usage of DependencyObject and DependencyProperty to a minimum?
Is this a good idea?
Actually, in Silverlight you cannot inherit DependencyObjects, and so you should (and have to) implement INotifyPropertyChanged instead.
Implementing INotifyPropertyChanged has many advantages over DependencyObjects (I will abbreviate this DO to make it easier) and using DependencyProperties (DPs):
This is more lightweight
Allows you more freedom in modeling your objects
Can be serialized easily
You can raise the event when you want, which can be useful in certain scenarios, for example when you want to bundle multiple changes in only one UI operation, or when you need to raise the event even if the data didn't change (to force redraw...)
On the other hand, inheriting DOs in WPF have the following advantages:
Easier to implement especially for beginners.
You get a callback mechanism (almost) for free, allowing you to be notified when the property value changes
You get a coercion mechanism with allows you to define rules for max, min and present value of the property.
There are other considerations, but these are the main.
I think the general consensus is that DPs are great for controls (and you can implement a CustomControl with custom DPs even in Silverlight), but for data objects you should rather implement INotifyPropertyChanged.
HTH,
Laurent
It really depends on which objects you are referring to. If the object is intended to sit in the XAML tree, its best to use DependencyProperties (and thus inherit DependencyObject - which all UIElements do) to allow all the benefits that DependencyProperties provide (being animatable, binding, optional automatic child inheritance, etc). I highly recommend you read the MSDN overview on DependencyProperties if you haven't already.
If the object is an data entity (ie. you are binding its values TO something in the XAML tree) then there is no need to inherit from DependencyObject. If the properties on the object are read-write you may want to implement INotifyPropertyChanged, which will allow bindings to automatically update when the value changes.
I agree with Richard that it depends on the purpose of your class, but as a note it seems that you CAN inherit from DependencyObject directly in Silverlight 2.0 Release, without having to inherit from UIElement or UserControl. At least, I'm doing that in my (SilverLight 2.0 RTW) app.
System.Windows.DependencyObject on MSDN
It is not typical to derive directly from DependencyObject for most scenarios. Instead you might derive from a specific control, from one of the control base classes (ContentControl; Control; ItemsControl), from FrameworkElement, or from non-control classes that still participate in UI such as Panel or Grid. Deriving from DependencyObject might be appropriate if you are defining a business or data storage object where you want dependency properties to be active, or if you are creating a service support class that will own attached properties.
HTH

Resources