Monthly Archives: April 2013

Data Transfer Objects in Domain-Driven Design Patterns

Data Transfer Object. A simple pattern for exchanging information between the Presentation Layer and the Service Layer.

The basics are explained in lots of articles all over the web, but there are some details that are not so obvious. I implemented DTOs following my instincts, but I always had the feeling I was asuming things and not doing it well.

That’s whay I keep on asking about the insights of patterns like this.

I found a very interesting article about DTOs by Bozhidar. I recommend you to read it because it gives several hints and advices on how to use this pattern sucessfully.

Bozho’s tech blog – On DTOs

The last part I want to notice is the question I posted. As you see, Bozher was really kind and answered really quick.



Aplanar propiedades de dependencia

Muy útil para evitar tener propiedades redundantes cuando hay herencia (recuerda que las propiedades de dependencia pueden ser heredables). Here I go with the explanation!


  1. Tenemos una estructura en árbol de padres e hijos, todos ellos DependencyObjects.
  2. Tenemos una propiedad de dependencia heredable
  • Queremos que el valor de la propiedad de dependencia más repetido en los hijos pase a ser el valor del padre.
  • A partir de ese momento, la propiedad en el padre es el valor más repetido en sus hijos.

¿Qué podemos hacer ahora?

Puesto que por el mecanismo de herencia, el valor del padre se hereda en los hijos, lo ideal sería que si el padre tiene el valor más repetido, en todos los hijos que tengan el valor más repetido se “reseteara” la propiedad. Haciendo esto, efectivamente, el hijo hereda el valor del padre automáticamente, que además será el valor óptimo (el más repetido). Además, esto es recursivo, por lo que el padre de todos los padres tendrá los valores más comunes dentro de sus hijos.

Esto puede ser útil en varias ocasiones (a mí ya me ha sido útil Winking smile)

Aquí dejo el código:

 private static void FlattenProperty(IParentOfDependencyObjectChildren parent,
            DependencyProperty dependencyProperty)
            var childrenList = parent.Children.ToList();

            if (childrenList.Any())
                foreach (IParentOfDependencyObjectChildren child in childrenList)
                    FlattenProperty(child, dependencyProperty);

                var values = childrenList.Select(o => o.GetValue(dependencyProperty)).ToList();
                var mostRepeated = values.GetMostRepeatedItem();
                foreach (var child in childrenList)
                    if (child.GetValue(dependencyProperty).Equals(mostRepeated))
                parent.SetValue(dependencyProperty, mostRepeated);
 public static class EnumerableExtensions
        public static T GetMostRepeatedItem<T>(this IEnumerable<T> list)
            // group by value and count frequency
            var query = from i in list
                        group i by i into g
                        select new { g.Key, Count = g.Count() };

            // compute the maximum frequency
            var ordenada = (from c in query orderby c.Count descending select c);

            return ordenada.First().Key;
    public interface IParentOfDependencyObjectChildren
        IEnumerable<DependencyObject> Children { get; }
        void SetValue(DependencyProperty dependencyProperty, object value);

Aberración Máxima

Estaba buscando ejemplos por Internet y me lo he encontrado: El súmmum.

Parafraseando el famoso traje biónico de Crysis os presento la antítesis del código limpio.

Os reto a que encontréis algo peor. Un método Get que no devuelve nada y que encima ¡establece cosas! Chorricode destilado.

		/*Cálculo de la X2*/
        private void CalculateX2(Graphic base)
            if (base is Numeric)
            else if (base is Text)

¿Sospechoso eso de ver un getColumns(…) cuyo valor no se almacena en ningún sitio?

¡Es que es es un método void!

        public void getColumns(int s)

“int s”, ¿estamos locos? Y eso del guión bajo da un mal rollo que no veas. Además de quedar horrible a la vista :S

        private void _getColumns(int s)
            this.width = (this.averageWidth) * s;
            this.Initialx2 = Initialx1 + this.width;

Meaninful names, sí señor. Un getter que es un setter encubierto.


Translator Pattern. Know Your Patterns :)




This pattern is really simple. It provides a method to convert from a representation to another. The same concept can be represented in many ways. Sometimes you have to “import” and “export” representations, so you have to provide a proper encapsulation for the logic that converts from one object to another.

Why would you need to do that? In my personal experience I have used it to convert instances of “legacy” clases that are not too well designed. It happens that a lot of logic already exists in the solution that work with those clases, so redefining them would be really expensive. The brand new features use better an more robust clases. For newer parts, I use a translator to perform a one time time conversion. When a legacy part of the application needs a “new” instance, I request a conversion to the old class instance.

It can be seen as a pattern similar to Adapter or Builder. But Adapter translates interfaces and provide a “wrapper” that interacts between the outer world and the wrapped classes along all its lifecycle. Builder creates complex objects. It’s a similar pattern, but I don’t feel it’s the same as the builder doesn’t translate, it builds up an instance.

What do you think about it? Do you see a Builder here? Smile

TemplateBinding Vs. Binding TemplatedParent



More limiting than using regular Binding. More efficient than a Binding, but it has less functionality

  • Only works inside a ControlTemplate’s visual tree
  • Doesn’t work with properties on Freezables
  • Doesn’t work within a ControlTemplate’s Trigger
  • Provides a shortcut in setting properties(not as verbose),e.g. {TemplateBinding targetProperty}

Regular Binding

  • Does not have above limitations of TemplateBinding
  • Respects Parent Properties
  • Resets Target Values to clear out any explicitly set values

Differences between Abstract Factory / Builder / Adapter

When it comes to patterns, it’s important to know the differences. Sometimes you have to name a class and you tend to call it “a X-builder”, or a “X-Generator”. But… are you sure you gave it the correct name?

It’s important to name things properly in our projects. From variables, to methods and classes. It REALLY matters. Even more when you are part of a team. When we are implementing a pattern we should give every entity the right now to avoid ambiguity.

In this particular case, those patterns may seem to do similar things, but they don’t. So, how to identify each one?


I hope somebody is kind enough to point out the differences between them. Come on, participate! Comments are welcome.