4

I have a problem with repeating code and would like to know a way to short the code further.

Thats how my code currently looks like:

private string _description = null;    
public string Description
{
    get
    {
        _description = GetLang(this.TabAccountLangs, "TextAccount");
        return _description;
    }
    set
    {
        if (object.Equals(value, _description))
            return;

        SetLang(this.TabAccountLangs, "TextAccount", value);

        OnPropertyChanged();
    }
}

This property and the code within can come several times within one class and in serval classes within the whole project, the only things changing are the name of the property and backing field it self, as well as the parameters from the method calls.

Now I would like to know, if there is a way to further shorten this code for example like this: (is just pseudo code)

[DoYourSuff(FirstParam=this.TabAccountLangs, SecondParam="TextAccount", ThirdParam=value)]
public string Description { get; set; }

This example would use an attribute, but maybe there is something better or if the attribute is the best way to do this. How would I implement such an attribute?

8
  • 6
    That is just strange that you only assign a value to _description in the get.
    – paparazzo
    Oct 30, 2013 at 9:08
  • You could perhaps look into the use of a PropertyBag.
    – default
    Oct 30, 2013 at 9:21
  • @Blam: I am basically using the backingfield only to suppress multiple OnPropertyChanged() calls when setting the same value over again, how would you solve this? Oct 30, 2013 at 9:31
  • My comments explains it.
    – paparazzo
    Oct 30, 2013 at 9:45
  • @Blam: ?!? sorry didnt understand what you mean, could you possible exaplain it to me in more detail? Or provide some code how you would solve this, without the backing field. Oct 30, 2013 at 9:48

8 Answers 8

5

Several answers seem worthy, but here's another option.

Have a look at Fody.
They have a plethora of plugins, some of them do quite similar things. If you can't find the one you like , you can probably modify it to do your will (and post it back to contribute to the community at the same time).

The PropertyChanged plugin for Fody,for example, will change these 51 lines of code:

public class Person : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    string givenNames;
    public string GivenNames
    {
        get { return givenNames; }
        set
        {
            if (value != givenNames)
            {
                givenNames = value;
                OnPropertyChanged("GivenNames");
                OnPropertyChanged("FullName");
            }
        }
    }

    string familyName;
    public string FamilyName
    {
        get { return familyName; }
        set 
        {
            if (value != familyName)
            {
                familyName = value;
                OnPropertyChanged("FamilyName");
                OnPropertyChanged("FullName");
            }
        }
    }

    public string FullName
    {
        get
        {
            return string.Format("{0} {1}", GivenNames, FamilyName);
        }
    }

    public virtual void OnPropertyChanged(string propertyName)
    {
        var propertyChanged = PropertyChanged;
        if (propertyChanged != null)
        {
            propertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

To 14:

[ImplementPropertyChanged]
public class Person 
{        
    public string GivenNames { get; set; }
    public string FamilyName { get; set; }

    public string FullName
    {
        get
        {
            return string.Format("{0} {1}", GivenNames, FamilyName);
        }
    }
}
3
+50

Summary

Use interception to address cross cutting concerns in how your properties are implemented.

Attributes can be used to associate static metadata to your code, whilst runtime dependencies require a bit more configuration.


Explanation and Example

My understanding is that you are essentially concerned with an exercise in Aspect Orientated Programming. You wish to decouple the definition of your class, to the way the underlying data is persisted and any subsequent consequences (such as the raising of the INotifyPropertyChanged event).

What's interesting about your case is that you wish to do using both static data (the string value "TextAccount" in your code sample) and data that is only known at runtime (the this.TabAccountLangs in your code example). These types of data require different approaches.

There is quite a bit going on in my solution, but let me first post the code and then explain it:

internal class Program
{
    private static void Main(string[] args)
    {
        var cOldClass = new PlainOldClass();
        var classProxyWithTarget = 
            new ProxyGenerator().CreateClassProxyWithTarget(cOldClass,new Intercetor(cOldClass));
        classProxyWithTarget.PropertyOne = 42;
        classProxyWithTarget.PropertyTwo = "my string";
    }

}

[AttributeUsage(AttributeTargets.Property)]
public class StaticDataAttribute : Attribute
{
    public string StaticData { get; private set; }

    public StaticDataAttribute(string resourceKey)
    {
        StaticData = resourceKey;
    }
}

public interface IMyRuntimeData
{
    string TabAccountLangs { get; }
    void OnPropertyChanged(string propertyName = null);
}

public class PlainOldClass : IMyRuntimeData
{
    [StaticData("FirstProperty")]
    public virtual int PropertyOne { get; set; }

    public string PropertyTwo { get; set; }
    public event PropertyChangedEventHandler PropertyChanged;

    public string TabAccountLangs { get; private set; }

    public virtual void OnPropertyChanged(string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class Intercetor: IInterceptor
{
    private readonly IMyRuntimeData _runtimeData;

    public Intercetor(IMyRuntimeData runtimeData)
    {
        _runtimeData = runtimeData;

    }

    public void Intercept(IInvocation invocation)
    {
        var isPropertySetter = invocation.Method.Name.StartsWith("set_");
        var isPropertyGetter = invocation.Method.Name.StartsWith("get_");

        if (isPropertySetter)
        {
            //Pre Set Logic
            invocation.Proceed();
            //Post Set Logic
            var attribute = invocation.Method.GetCustomAttributes(false).Cast<StaticDataAttribute>().SingleOrDefault();
            if (attribute != null)
            {
                string resourceKey = attribute.StaticData;
                string tabAccountLangs = _runtimeData.TabAccountLangs;
                _runtimeData.OnPropertyChanged(invocation.Method.Name.Substring(4));
            }   
        } else if (isPropertyGetter)
        {
            //Pre Get Logic 
            invocation.Proceed();
            //Post Get Logic
        }
        else
        {
            invocation.Proceed();
        }
    }
}

I rely heavily on interception to address cross cutting concerns. I have used Castle's Dynamic Proxy in my implementation of the IInterceptor interface. The actual logic isn't important or maybe relevant to your needs - but it should at least give a conceptual view of how you can achieve what you want in your specific situation.

The properties I care about are marked as virtual (so the Dynamic Proxy intercepts calls to them), and decorated with the StaticDataAttribute, to allow me to attach static data to each property. The trickier part is those aspects of the interception that rely on data that is not determined until runtime, that is the raising of the property changed event, and using the value of this.TabAccountLangs. These "runtime dependencies" are encapsulated within the interface IRuntimeData, which is injected in to the constructor of the interceptor.

The Main(string[] args) method shows how everything is put together. Obviously you wouldn't use it like this in code - you could wrap this "gluing" logic within a factory pattern, or configure the interception at the level of your IoC container configuration.

3

If you really want to go down this route? Code generation will work.

http://msdn.microsoft.com/en-us/library/vstudio/bb126445.aspx

Microsoft has embedded the T4 templating language into Visual Studio. This templating language allows quick and easy ways to generate boilerplate code. While the system itself is primitive, clumsy, and generally frustrating, it allows you to generate code with whatever approach you like.

To do the basics, you'd make a template file describing your reusable code and logic.

So for example, we could have a TemplatedFields.Include.tt file that looks like this

<# // myFields and myClassName must be defined before importing this template #>
<# // stuff in these braces will not appear in the outputted file, but are executed by the templating engine #>
//this code is outside of the braces and will appear in the file1
public partial class <#= myClassName #> //notice the equals sign.  Works like webforms.
{

    <# ForEach(var field in myFields) { #>
    private string _<#= field.Name #> = null;    
    public string <#= CapitalizeFirstLetter(field.Name) #>
    {
        get
        {
            _<#= field.Name #> = GetLang(<#= field.FirstParam #>, "<#= field.SecondParam #>");
            return _<#= field.Name #>;
        }
        set
        {
            if (object.Equals(value, _<#= field.Name #>))
                return;

            SetLang(<#= field.FirstParam  #>, "<#= field.SecondParam #>", value);

            OnPropertyChanged();
        }
    }
    <# } #>
}

And then for the definition of your... well, let's say this is Person.cs

Person.Templated.tt

<#@ output extension=".cs" #>
//stuff inside the angle braces is sent to the TT engine and does not appear in the file.
<#
var myClassName = "Person";
var myFields = new List<Field>()
{
    new Field {Name="Description", FirstParam="this.TabAccountLangs", SecondParam="TextAccount"),
    new Field {Name="Name", FirstParam="this.TabAccountLangs", SecondParam="TextAccount"),
    new Field {Name="MoarFieldzzzz", FirstParam="this.TabAccountLangs", SecondParam="TextAccount"),
}
 #>
 //included code is appears below, now that values have been set above.
 <#@ include file="TemplatedFields.Include.tt" #>

Saving the above file will generate Person.Templated.cs automatically. I don't remember if you need a directive or not to make sure that VS will compile the resulting CS file, but I'm pretty sure it does by default.

I leave the implementation of CapitalizeFirstLetter and the definition of Field as an excersize for the reader. This is, of course, an exceptionally crude approach - there are far more structured and intelligent ways to build a framework with t4.

Because the class is partial, you can provide more specific hand-coded logic in a second Person.cs file.

Oleg Sych has made the t4toolbox to make large, complicated T4 projects easier, but I warn you: T4 are a path to madness.

3

Setters can be replaced with one-liners:

    private string foo;
    public string Foo
    {
        get { return foo; }
        set { Setter(v => foo = v, value, () => Foo, () => Bar); }
    }

e.g.:

 set { Setter( v => SetLang(this.TabAccountLangs, "TextAccount", v), value, () => Foo );

"Setter" is the method in base class:

public abstract class BaseObject : INotifyPropertyChanged
    {
    public event PropertyChangedEventHandler PropertyChanged;

    protected void Setter<T>( Action<T> setter, T newVal, Expression<Func<T>> property, params Expression<Func<object>>[] dependentProperties )
        {
        if ( !equals( getPropValue( property ), newVal ) )
            {
            setter( newVal );
            notifyDependentProps( property, dependentProperties );
            }
        }

    private static string getPropertyName<Tz>( Expression<Func<Tz>> property )
        {
        return getPropertyInfo( property ).Name;
        }

    private static PropertyInfo getPropertyInfo<T>( Expression<Func<T>> property )
        {
        MemberExpression expression;
        var body = property.Body as UnaryExpression;
        if ( body != null )
            expression = (MemberExpression) body.Operand; //for value types
        else
            expression = ( (MemberExpression) property.Body );
        var pi = expression.Member as PropertyInfo;
        if ( pi == null )
            throw new ArgumentException( "expression must be valid property" );
        return pi;
        }

    private void valueChanged<Ta>( Expression<Func<Ta>> property )
        {
        if ( PropertyChanged != null )
            PropertyChanged( this, new PropertyChangedEventArgs( getPropertyName( property ) ) );
        }

    private void notifyDependentProps<T>( Expression<Func<T>> property, Expression<Func<object>>[] dependentProps )
        {
        valueChanged( property );
        if ( dependentProps != null && dependentProps.Length > 0 )
            {
            for ( int index = 0; index < dependentProps.Length; index++ )
                valueChanged( dependentProps[index] );
            }
        }

    private T getPropValue<T>( Expression<Func<T>> property )
        {
        PropertyInfo pi = getPropertyInfo( property );
        return (T) pi.GetValue( this, new object[] {} );
        }

    private bool equals<T>( T first, T second )
        {
        return EqualityComparer<T>.Default.Equals( first, second );
        }
    }
3

You can do something similar to this:

public class MyClass
{
    private TabAccountLangs TabAccountLangs = //whatever;
    private readonly Wrapper _wrapper = new Wrapper(TabAccountLangs);

    private string Decsription
    {
        get { return _wrapper.GetValue<string>("TextAccount"); }
        set { _wrapper.SetValue<string>("TextAccount", value, OnPropertyChanged); }
    }
}

public class Wrapper
{
    private Dictionary<string, object> _map = new Dictionary<string, object>(); 

    //pass TabAccountLangs to constructor and assign to _langs property
    //Constructor should be here

    public T GetValue<T>(string name)
    {
        object result;
        if (!_map.TryGetValue(name, out result))
        {
            result = GetLang(_langs, name);
            _map[name] = result;
        }
        return (T) result;
    }

    public void SetValue<T>(string name, T value, Action onSuccess)
    {
        object previousValue;
        if (_map.TryGetValue(name, out previousValue) && previousValue.Equals(value))
        {
            return;
        }
        SetLang(_langs, name);
        _map[name] = value;
        onSuccess();
    }

    //The rest
}

I don't know a lot about the details of your task but this will give you the basic idea. In case your classes don't share the same parent, this will prevent code duplication. In case if they do, you can hide this wrapper in base class and don't pass OnPropetyChanged delegate to wrapper

3

You may use PostSharp.

I won't paste any example here: They are plenty on their site !

2

You can not implement such attribute without building up some framework which will go through your solution and generate code for such properties behind the scene. Creating and, more importantly, debugging such thing will require a lot of effort and generally is not worth it. At least not when the only reason for that is "to shorten the code".

Instead i would recommend using inheritance and aggregation where possible. You should also consider making a Resharper template (if you are using Resharper) or VS snippets (if you are not). This will not reduce the amount of code, but it will greatly reduce the time required for writing such properties.

1
  • 1
    Well answered. I want to add a reason why such attribute is not possible: Variable values like this.TabAccountLangs and value cannot be used in attributes. The only possibility I can imagine would be passing hardcoded strings to the attribute and then call the correct methods using reflection. But that has to be done in get and set, and would defeat the purpose of such attributes.
    – Kabbalah
    Nov 6, 2013 at 10:33
2
  1. Create a custom attribute and apply to those fields
  2. Detect when you apply the attribute: create an another app, that runs all the time, and checks wheter you applied the attribute. I would try out the Roslyn CTP
  3. Use partial classes. Generate the properties to another file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.