Language Oriented Programming

Yesterday I spent several hours thinking about a concept I have been toying with for several days. Every programming language I have ever used, has its own limitations. The past few months I have been reaching those a lot, which is part of the reason why I started this blog. It made me wonder whether a programming language could be created, which can adjust itself at any given time. One important result is that this would allow you to create new keywords for a set of operations that are used regularly, solving the problem for which now only exist workaround solutions. Another cool aspect I realized, is when you start this process from byte level, the programming language itself could be its own compiler at runtime.

As a thought experiment I tried to come up with a basic set of rules, allowing for this required flexibility. If I didn’t make any logic errors, the rules I came up with can be implemented with a surprisingly small implementation, which for now, I’ll attempt to do in C#. When this turns out fruitful, the next step would be to do the same in assembly. The C# implementation, and the assembly implementation, would be able to run the same code.

While thinking of a name for the programming paradigm I had in mind (Read as: I needed to give the newly created solution in Visual Studio a name.), I checked Wikipedia for existing ones, but didn’t find any similar ones at first. Only by a subsequent google search with some keywords I found appropriate I stumbled upon Language Oriented Programming, and I’m really excited about it! The article reflects a lot (and more) of what I was thinking about and does a really good job of explaining it. As a nice ending brainfuck quotation:

Language Oriented Programming will not just be writing programs, but also creating the languages in which to write our programs. – Sergey Dmitriev, cofounder and CEO of JetBrains Inc.

ViewModel Property and Command Factory

If you are familiar with the MVVM pattern, often used in WPF/XAML, you probably know what a viewmodel should look like. These classes get quite big pretty quickly. Considering that they are mainly just an adapter on your model, to be accessed by your view, they contain a lot of duplicate code. Wherever you read “duplicate”, there most likely exists a cleaner solution, so I’ll cut to the chase. What follows are two code samples with the same behavior. In the second sample I use a factory to minimize the required code. This approach has additional advantages as well as I’ll explain later.

Let’s make a ViewModel to edit this rubber duck! (This might sound familiar to you if you have read Head First’s great book on design patterns.)

Traditional implementation:

public class DuckViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private Duck m_duck;

    private bool m_canQuack;
    public bool CanQuack
    {
        get { return m_canQuack; }
        set
        {
            m_canQuack = value;
            RaisePropertyChanged("CanQuack");
        }
    }

    private Color m_color;
    public Color Color
    {
        get { return m_color; }
        set
        {
            m_color = value;
            RaisePropertyChanged("Color");
        }
    }

    private RelayCommand m_quackCommand;
    public ICommand QuackCommand
    {
        get { return m_quackCommand; }
    }

    private RelayCommand m_saveCommand;
    public ICommand SaveCommand
    {
        get { return m_saveCommand; }
    }

    public DuckViewModel(Duck duck)
    {
        m_duck = duck;
        CanQuack = duck.CanQuack;
        Color = duck.Color;

        m_quackCommand = new RelayCommand(() => Quack(), () => CanQuack());
        m_saveCommand = new RelayCommand(() => Save());
    }

    public void RaisePropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyEventArgs(property));
        }
    }

    public void Quack()
    {
        m_duck.Quack();
    }

    public void CanQuack()
    {
        return m_duck.CanQuack;
    }

    public void Save()
    {
        m_duck.CanQuack = CanQuack;
        m_duck.Color = Color;
    }
}

Phew, that’s a whole lot to write just for two properties and two commands isn’t it? Let’s try improving this.

Factory approach:

public enum Properties { CanQuack, Color }
public enum Commands { Save, Quack }

public class DuckViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private readonly NotifyPropertyFactory<Properties> m_properties;
    private readonly CommandFactory<Commands> m_commands;

    private Duck m_duck;

    [NotifyProperty(Properties.CanQuack)]
    public bool CanQuack
    {
        get { return (bool)m_properties.GetValue(Properties.CanQuack); }
        set { m_properties.SetValue(Properties.CanQuack, value); }
    }

    [NotifyProperty(Properties.Color)]
    public Color Color
    {
        get { return m_properties.GetValue(Properties.Color) as Color; }
        set { m_properties.SetValue(Properties.Color, value); }
    }

    public DuckViewModel(Duck duck)
    {
        m_duck = duck;
        CanQuack = duck.CanQuack;
        Color = duck.Color;

        m_properties = new NotifyPropertyFactory<Properties>(this, PropertyChanged);
        m_commands = new CommandFactory<Commands>(this);
    }

    [CommandExecute(Commands.Quack)]
    public void Quack()
    {
        m_duck.Quack();
    }

    [CommandCanExecute(Commands.Quack)]
    public bool CanQuack()
    {
        return m_duck.CanQuack;
    }

    [CommandExecute(Commands.Save)]
    public void Save()
    {
        m_duck.CanQuack = CanQuack;
        m_duck.Color = Color;
    }
}

There already exist dozens of other solutions to simplify (and improve) implementing INotifyPropertyChanged. One approach is to use a base class. I prefer the factory approach, following the design principle.

Favor composition over inheritance.

To remove the literals from the PropertyChanged call lambda’s can be used. Because my approach uses reflection, the literal isn’t a problem anymore, and is traded for an enum value.

Besides solving the previously mentioned problems, the factory approach has additional advantages:

  • No more private field members required for the properties, just one for the factory.
  • As an advantage of the factory design, the view model doesn’t need to know about concrete implementations. Behavior can be added/changed inside the factory.
  • As you might have noticed, no more command members! All the commands are contained within the command factory. Yes, you can still magically bind to them, which I’ll explain in a bit!

How it works:

You might notice the similarity with my previously posted dependency property factory. I refactored the latter, and all three factories (commands, notify property and dependency property) use the same abstract base class AbstractEnumSpecifiedFactory, which already handles a lot of the required behavior by using reflection. It links MemberInfo objects to the desired attributes. Concrete implementation decide which attributes it needs, and what to do with them.

To be able to still bind to the commands I created a custom Markup Extension for XAML, allowing me to do the following.

<Button Command="{m:CommandBinding {x:Static Binding:Commands.Quack}}" Content="Quack" />

This has another additional advantage that binding is done in a safe way. The CommandBinding extension uses -you guessed it- reflection to get the correct command out of the CommandFactory in the data context.

While creating the CommandBinding extension I prepared myself to optionally create a custom general Binding extension, so that the naming conventions for dependency properties can safely be ignored, and the useless property fields can be removed.

Source code can be found in my FCL Extension library in the Whathecode.PresentationFramework assembly. The NotifyPropertyFactory is located in Whathecode.System.ComponentModel.NotifyPropertyFactory and the CommandFactory is located in Whathecode.System.Windows.Input.CommandFactory.

Why code snippets promote bad design

It is a well established guideline that duplicate code should be prevented. It’s one of the main software design principles, also known as “Don’t Repeat Yourself” (DRY).

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system. – Andy Hunt and Dave Thomas in their book The Pragmatic Programmer

Code snippets are defined as “a small region of re-usable source-code“. A lot of IDE’s have a feature to manage and use code snippets. It should be quite obvious why this contradicts DRY. It is actually even worse, as it makes it easier for you to do so. Yet, so many people embrace them as a good ‘solution’. There already exists a solution for having to write duplicate code, it is called encapsulation.

So why do code snippets exist? Sometimes you reach the limitations of a programming language, and a piece of code can’t be encapsulated any further. You want to do a similar task over and over again, but with variable parameters. A good example of this is a C# property, which defines a value, accessible through a getter and optionally a setter.

public string Name
{
    get;
    set;
}

The previous sample is an auto-implemented property. Every keyword is relevant and required by C#. An equivalent would be a simple member field, “public string Name;“, but this wouldn’t give us the flexibility to easily make the setter private, or add additional code to the getter or the setter. The point I’m making is, within the confines of the language, it can’t be simplified without sacrificing flexibility. This should be the only reason to use code snippets!

Personally, I don’t use snippets at all, as I spend way more time designing my code, than writing it anyhow. Furthermore, I see the following disadvantages when using them:

  • You think less about the code you are writing. E.g. for the property, by default the setter is public, which is definitely not always desirable.
  • It promotes laziness, not caring whether a certain snippet can be encapsulated. E.g. code snippets for dependency properties as I discussed earlier.

Even when you find yourself in a scenario where you write a lot of code which can’t be improved any further, other options are available, e.g. code generation. I might make this the subject of one of my future posts.

Java Generic Observer

Design patterns, you gotta love them! What would we do without our beloved Observer Pattern? Since its usage is so common, most frameworks provide an implementation out of the box. Microsoft even added a language construct for it to C#, called ‘events‘. As a Java developer, it would seem you are less lucky. Through the years, my unconditional trust in the design of frameworks has been wavering. Java’s default implementation of the Observer pattern is a nice example of what I consider bad design. Perhaps that’s why it’s not even used in the framework itself. (ActionListener in awt)

If you haven’t watched “Despicable Me” yet, stop reading and watch it first! 😉 It’s a great movie. Consider a person (Gru) needing the ability to watch over his minions.

A standard implementation using the framework’s classes would be:

Gru gru = new Gru();
Minion fred = new Minion();
fred.addObserver(gru);
fred.moo();

public class Minion extends Observable
{
    public void moo()
    {
        setChanged();
        notifyObservers("hehehe");
    }
}

public class Gru implements Observer
{
    public void punch(Minion minion) { ... }

    @Override
    public void update(Observable o, Object arg)
    {
        if (o instanceof Minion)
        {
            String s = (String)arg;
            if (s.equals("hehehe"))
            {
                punch((Minion)o);
            }
        }
    }
}

The thing that bothers me (and others) in this implementation is the need for type checking. After browsing around, I found an implementation by Allain Lalonde who addressed this issue by using a dynamic proxy. I found his solution to be really useful, implemented it, and added a small feature which allows extending from a generic AbstractObservable class. The result looks as follows:

Gru gru = new Gru();
Minion fred = new Minion();
fred.addObserver(gru);
fred.moo();

public interface IMinionListener
{
    public void laughing(Minion minion);
}

public class Minion extends AbstractObservable<IMinionListener>
{
    public void moo()
    {
        getEventDispatcher().laughing(this);
    }
}

public class Gru implements IMinionListener
{
    public void punch(Minion minion) { ... }

    public void laughing(Minion minion)
    {
        punch(minion);
    }
}

How it works.

Events are dispatched through an ObserverPool as described by Allain Lalonde. This is a proxy class which forwards calls (as defined by the interface) to a set of listeners, the observers. You can use this pool directly, or extend from AbstractObservable which already creates and wraps it for you.

Possible problems.

As with the original Observable, you might not be able to extend from AbstractObservable since multiple inheritance isn’t allowed. You could use composition instead, and use the IAbstractObservable interface.

AbstractObservable source code

Better solution? (most likely)

I wrote this code a while ago, before I started this blog. While writing, I followed a link on Wikipedia which I wish I found before. It seems there is a free package available called PerfectJPattern, containing componentized design patterns, including the observer pattern. From the looks of it, they also use a proxy approach. The project looks really well maintained, clean, and thoroughly implemented. Next time I develop in Java, I’ll check it out.

Dependency Property Factory – Part 3

This post is a second follow-up to an earlier attempt to simplify creating dependency properties. In the previous follow-up I discussed unanswered questions about the WPF dependency property system which prevented me from continuing the implementation.

First of all, I would like to thank Einar Ingebrigtsen for helping me out on some of the following issues. He has a solution of his own inside the open source Balder project.

The answers to the questions:

“Does anyone know concrete examples of problems caused by not following the convention of naming the CLR property wrapper the same as the dependency property, or in other words, why is it of any importance?”

External tools may use this convention to access the dependency properties. I would argue these tools could be made smart enough to solve this without the convention, but since my proposed solution doesn’t require passing this name anymore at all, this is not an issue anymore.

“Why can I still use the dependency properties through XAML, without adding the field identifiers that end with the suffix ‘Property’?”

The XAML processor doesn’t use these identifiers directly, as the documentation on msdn might make you believe. However, again external tools, or future versions may follow this convention, so let’s assume it is required. Since I don’t own/use any of these tools I can’t verify this. Of real importance is the necessity for the properties to be registered in a static context. Luckily this makes the factory approach still a viable option.

The solution!

Taking all this new information into consideration, this is the best I could come up with:

public class FactoryExample : DependencyObject
{
    public enum Property
    {
        Standard,
        ReadOnly,   // This becomes a readonly property.
        Callback    // This property has callbacks assigned to it.
    }
    private static readonly DependencyPropertyFactory<Property> m_properties =
        new DependencyPropertyFactory<Property>();

    public static readonly DependencyProperty StandardProperty =
        m_properties[Property.Standard];
    public static readonly DependencyProperty ReadOnlyProperty =
        m_properties[Property.ReadOnly];
    public static readonly DependencyProperty CallbackProperty =
        m_properties[Property.Callback];

    [DependencyProperty(Property.Standard, DefaultValue="foo")]
    public string Standard
    {
        get { return m_properties.GetValue(this, Property.Standard) as string; }
        set { m_properties.SetValue(this, Property.Standard, value); }
    }

    [DependencyProperty(Property.ReadOnly)]
    public bool ReadOnly
    {
        get { return (bool)m_properties.GetValue(this, Property.ReadOnly); }
        private set { m_properties.SetValue(this, Property.ReadOnly, value); }
    }

    [DependencyProperty(Property.Callback)]
    public int Callback
    {
        get { return (int)m_properties.GetValue(this, Property.Callback); }
        set { m_properties.SetValue(this, Property.Callback, value); }
    }

    [DependencyPropertyChanged(Property.Callback)]
    public static void OnChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
    {
        ...
    }

    [DependencyPropertyCoerce(Property.Callback)]
    public static object OnCoerce( DependencyObject d, object value )
    {
        ...
    }
}

As you might notice, not too many things have changed since the first post, but besides the advantages mentioned earlier, there are a couple of new features.

  • The owner type for the factory is automatically set to the outer class of the passed template parameter. You can still pass the type manually.
  • Exceptions are (optionally) thrown when the conventions aren’t followed. Thanks to the exceptions I actually found out one of my CLR property wrappers was set to protected (public is required), indicating a design flaw.
  • Behaviour of get and set is encapsulated inside the factory. (E.g. No need to know whether a dependency property is read only when using a private setter.)
  • Safe for obfuscation. (Before ID.ToString() was used, where ID was the enum value. Now the property name is used and the enum value is solely used to link things together.)

If you are anything like me, looking at the code you might think “This can still be improved!“. Unfortunately it looks like we reached the limitations of C#. What follows are some failed ideas I considered.

Requirement for an enum:

Why specify an enum, right? We already have the properties, why not use those as ID’s? In Einar’s implementation an expression tree is used as a way to represent the property by using a lambda expression, returning the property itself. (E.g. o => o.Standard) Unfortunately, expression trees can’t be passed as an argument to Attributes, required by the factory. Why? My guess is, “No particular reason.

AbstractDependencyObject:

Why not have an abstract class implement the factory by default? A default GetValue() and SetValue() method could be added, so “m_properties.GetValue(this, Property.Standard)” would be reduced to “GetValue(Property.Standard)”. Such an implementation would quickly turn out unusable as multiple inheritance isn’t supported.

Every property has almost the exact same implementation!:

Although macros can be nasty, I’d argue this would be a correct usage for them. But, ofcourse C# doesn’t support macros. The duplicate code was there before, at least it’s reduced and grouped together now.

So it looks like this is the end, …. or is it? Enter, Aspect Oriented Programming!

At first, a strangely unfamiliar name to me. Now, I can only dream of the following implementation.

[DependencyObject]
public class FactoryExample
{
    [DependencyProperty(DefaultValue="foo")]
    public string Standard { get; set; }

    [DependencyProperty]
    public bool ReadOnly { get; private set; }

    [DependencyProperty]
    public int Callback { get; set; }

    ...
}

By acquiring a license for PostSharp, or with a lot of free time on your hands by implementing it yourself, you could attempt an implementation just like that! If it whet your appetite, be sure to check it out, but for me, the road ends here.

Dependency Property Factory source code

For the latest version of this code, you can download my FCL Extension library. It’s located in the Whathecode.PresentationFramework assembly under the namespace Whathecode.System.Windows.DependencyPropertyFactory.

Dependency Property Factory – Part 2

This post is a follow-up to an earlier attempt to simplify creating dependency properties.

I didn’t notice a possible problem with the approach of the previous post since it doesn’t cause any problems in the project I use it in. WPF is quite strict when it comes to creating custom dependency properties. There are several ways in which you can do it wrong, and the code in the last post does admittedly, exactly that. “There are established naming conventions regarding dependency properties that you must follow in all but exceptional circumstances.” In my opinion, the ability to misuse an interface, and additionally not even being able to notice it, indicates a design flaw. To quote someone with a lot more experience:

Make interfaces easy to use correctly and hard to use incorrectly. The best way to prevent incorrect use is to make such use impossible. – Scott Meyers

…, and that’s exactly what I’ll try to do.

Convention 1: “The name of the field is always the name of the property, with the suffix Property appended.”

public static readonly DependencyProperty IsSpinningProperty =
    DependencyProperty.Register(
    "IsSpinning", typeof(Boolean), typeof(OwnerType));

Convention 2: “Define a CLR “wrapper” property whose name matches the name of the dependency property.”

public bool IsSpinning
{
    get { return (bool)GetValue(IsSpinningProperty); }
    set { SetValue(IsSpinningProperty, value); }
}

Convention 3: “In all but exceptional circumstances, your wrapper implementations should perform only the GetValue and SetValue actions, respectively.”

First I want to determine why ignoring these conventions causes problems. I was already aware that XAML bypasses property wrappers, resulting in convention 3, and proposed a solution in the previous post. An exception could be thrown in the factory class to prevent a wrong CLR property wrapper. Apparently XAML bypasses the wrappers by calling GetValue() and SetValue() directly (for performance reasons), using the property name with “Property” suffixed to it as a parameter. E.g. the property with the name “ABC” gets called as GetValue(ABCProperty). This causes convention 1. Convention 2 is a bit vague and not mentioned explicitly why it is necessary. Other problems when not following these conventions are according to msdn:

  • Certain aspects of styles and templates will not work.
  • Most tools and designers must rely on the naming conventions to properly serialize XAML, or to provide designer environment assistance at a per-property level.

Does anyone know concrete examples of problems caused by not following convention 2, or in other words, why is it of any importance?

The factory class mentioned in the previous post doesn’t follow convention 1 at all. Why can I still use the dependency properties through XAML? The setter and binding in the following sample work perfectly. It seems like all XAML really needs is the name of the dependency property as passed with the DependencyProperty.Register() method. This would also make a lot more sense, since the name would be redundant otherwise.

<DependencyPropertyTestControl
    XamlSetTest="100"
    Margin="{Binding RelativeSource={RelativeSource Self},
    Path=XamlSetTest}" />
    public class DependencyPropertyTestControl : Label
    {
        public enum Property
        {
            XamlSetTest
        }
        private static readonly DependencyPropertyFactory<Property> m_properties =
            new DependencyPropertyFactory<Property>( typeof( DependencyPropertyTestControl ) );

        public static readonly Dictionary<Property, DependencyProperty> Properties =
            m_properties.Properties;

        [DependencyPropertyAttribute( Property.XamlSetTest )]
        public string XamlSetTest
        {
            get { return GetValue( Properties[ Property.XamlSetTest ] ) as string; }
            set { SetValue( Properties[ Property.XamlSetTest ], value ); }
        }

        [DependencyPropertyChangedAttribute( Property.XamlSetTest )]
        public static void OnSourceChanged( DependencyObject d, DependencyPropertyChangedEventArgs e )
        {
            var control = d as DependencyPropertyTestControl;

            if ( control != null )
            {
                control.Content = e.NewValue;
            }
        }
    }

UPDATE:
I posted these questions on the msdn forum to see whether somebody could answer them. The answer seems to confirm my suspicions that the property system only uses the name passed to Register() and not the field identifier. I’m guessing it can access the dictionary of DependencyObject directly and uses the dependency property name as the key to find the property in this dictionary. Still it is not wise to break conventions, so I’ll attempt to adjust the factory so that it enforces them instead. I’m afraid this will make a lot of its code superfluous. Perhaps a helper class is a better approach. Recently I discovered exactly such an implementation, and will check it out.

Make Interfaces Easy to Use Correctly and Hard to Use Incorrectly

Dependency Property Factory

If you have ever developed an application using WPF, you most likely came across dependency properties. At first you love the flexibility of them and what it allows you to do, as they are great! However, after a while you might feel like you are writing a lot of duplicate code, and are filling up entire classes with it. This for me was a strong indication to encapsulate the behaviour and creation of dependency properties as good software design calls for.

To get a quick idea of my proposed solution I’ll simply post two code segments. One taken from an excellent tutorial on dependency properties by Christian Mosers. The other adjusts the code segment using the new approach.

Most common usage:

// Dependency Property
public static readonly DependencyProperty CurrentTimeProperty =
    DependencyProperty.Register(
        "CurrentTime",
        typeof(DateTime),
        typeof(MyClockControl),
        new FrameworkPropertyMetadata(
            DateTime.Now, OnCurrentTimePropertyChanged, OnCoerceTimeProperty
        ));

// .NET Property wrapper
public DateTime CurrentTime
{
    get { return (DateTime)GetValue(CurrentTimeProperty); }
    set { SetValue(CurrentTimeProperty, value); }
}

private static void OnCurrentTimePropertyChanged(
    DependencyObject source,
    DependencyPropertyChangedEventArgs e)
{
    MyClockControl control = source as MyClockControl;
    DateTime time = (DateTime)e.NewValue;
    // Put some update logic here...
}

private static object OnCoerceTimeProperty(DependencyObject sender, object data)
{
    if ((DateTime)data > DateTime.Now)
    {
        data = DateTime.Now;
    }
    return data;
}

// Register the private key to set the value
private static readonly DependencyPropertyKey IsMouseOverPropertyKey =
    DependencyProperty.RegisterReadOnly(
        "IsMouseOver",
        typeof(bool),
        typeof(MyClass),
        new FrameworkPropertyMetadata(false));

// Register the public property to get the value
public static readonly DependencyProperty IsMouseoverProperty =
    IsMouseOverPropertyKey.DependencyProperty;

// .NET Property wrapper
public int IsMouseOver
{
   get { return (bool)GetValue(IsMouseOverProperty); }
   private set { SetValue(IsMouseOverProperty, value); }
}

My proposed solution:

// Enum declaring all the dependency properties present.
public enum Property
{
    CurrentTime,
    IsMouseOver
}

// A factory class used to create and manage the dependency properties.
private static readonly DependencyPropertyFactory<Property> m_properties =
    new DependencyPropertyFactory<Property>(typeof(MyClockControl));

// Public dictionary used to access the dependency properties.
public static readonly Dictionary<Property, DependencyProperty> Properties =
    m_properties.Properties;

[DependencyPropertyAttribute(Property.CurrentTime, DefaultValue=DateTime.Now)]
public DateTime CurrentTime
{
    get { return (DateTime)GetValue(Properties[Property.CurrentTime]); }
    set { SetValue(Properties[Property.CurrentTime], value); }
}

[DependencyPropertyChangedAttribute(Property.CurrentTime)]
private static void OnCurrentTimePropertyChanged(
    DependencyObject source,
    DependencyPropertyChangedEventArgs e)
{
    MyClockControl control = source as MyClockControl;
    DateTime time = (DateTime)e.NewValue;
    // Put some update logic here...
}

[DependencyPropertyCoerceAttribute(Property.DateTime)]
private static object OnCoerceTimeProperty(DependencyObject sender, object data)
{
    if ((DateTime)data > DateTime.Now)
    {
        data = DateTime.Now;
    }
    return data;
}

[DependencyPropertyAttribute(Property.IsMouseOver)]
public bool IsMouseOver
{
   get { return (bool)GetValue(Properties[Property.IsMouseOver]); }
   private set {
       m_properties.SetReadOnlyProperty(this, Properties[Property.IsMouseOver], value);
   }
}

 

As you might notice, the last code sample has a few advantages.

  • To identify the dependency property an enum is used, still allowing for strong typed identification of the properties.
  • By passing the owner type for the dependency property to the factory class, it is specified in just one place.
  • The settings for a dependency property are placed right above the property which is used in code internally. Parameters you had to pass manually to the DependencyProperty.Register() method before are deduced automatically. You can still specify them manually as well.
  • Although not really visible through this short code sample, adding more properties is really easy and requires a lot less code.
  • Centralized code. In the unlikely event that the Register() method changes, you only have to adjust the code of the factory class.

How it works:
The factory uses reflection to analyse the code to which the attributes are applied. This way it knows the property type and whether the dependency property should be readonly or not. As a name for the property, the ToString() method is used by default.

To be fair I’ll also mention the problems I see with this approach:

  • There is a small overhead to retrieve the dependency property through the Dictionary every time. I do believe this will have a minor impact.
  • Since DependencyObject internally already works with a dictionary, it’s kind of a double effort.
  • The enum value needs to be defined three times for every property. I don’t know an immediate solution for this, but it is relevant for a future post where I’ll discuss data model generation.

Possible expansions:

  • Right now the Dictionary used to make the properties available for public use isn’t read only. Since this class isn’t available by default this might be a subject I’ll address at a later time. Googling for a short amount of time already indicated this is a known problem. Perhaps a custom implementation of Collection can be created to break all references to DependencyProperty.
  • Because the factory controls the creation of the dependency properties, exceptions can be thrown when invalid usage is detected. E.g. When the .NET properties contain more statements than the GetValue() and SetValue().

All things considered I don’t see any major disadvantages, but I’m no WPF expert. I’d love to have some input from people more experienced with WPF.

Factory source code

UPDATE:

Possible problems due to WPF’s naming conventions are discussed in a new post.
For the most recent version, go to my last post for information. For the source code, you can download my FCL Extension library. The DependencyPropertyFactory is located in the Whathecode.PresentationFramework assembly under the namespace Whathecode.System.Windows.DependencyPropertyFactory.

The lyf so short, the craft so long to lerne.

As a software developer, I’ve reached a certain point in my career where I think I can add real contributions to the community. Every now and then, I write a piece of code of which I think: “Why can’t I find an existing implementation of this?”. Realizing how I relied on insights and implementations of others over the past few years, and will continue to, I decided to start this blog about programming and software design.

Ever since I read the book on design patterns by Head First, I’ve been addicted to following good software design. My personal experience is people sometimes talk more about the subject than putting it into practice.

Not coming up with a proper title for this first post, I decided to make it a quotation (I know it’s cliché…) which pretty much sums up how I feel about programming.

The lyf so short, the craft so long to lerne. — Geoffrey Chaucer