· design

Design Simplicity: Partially updating an object

One of the most common discussions that I have with my colleagues is around designing bits of code in the simplest way possible.

I’ve never quite been able to put my finger on exactly what makes a design simple and there is frequently disagreement about what is even considered simple.

On the last project I worked on we had an interesting problem where we wanted to partially update different parts of an object from different pages of the application.

design-simplicity.jpg

We had access to the id of the object from the URL so my initial thought was that when we submitted each page we could load the full object from the database and update it with the values that had just been submitted from that page.

The problem with that solution was that it meant we needed to make another database call without any real benefit from doing so.

We had already created objects representing the data submitted from these pages so Christian suggested that an alternative approach would be to create NHibernate mappings for those objects instead so that we could just map the updated values straight to the database.

We had bit of duplication in our objects as we had one object representing every bit of data the user had provided so far and then two smaller objects just representing the data provided for each of the pages.

public class TheObject
{
	public string Page1Property { get; set; }
	public string Page2Property { get; set; }
}
public class PartialObject1
{
	public string Page1Property { get; set; }
}
public class PartialObject2
{
	public string Page2Property { get; set; }
}

We then created NHibernate mappings for each of those objects:

public class TheObjectMapping : ClassMap<TheObject>
{
	Map(x => x.Page1Property);
	Map(x => x.Page2Property);
}
public class PartialObject1Mapping : ClassMap<PartialObject1>
{
	Map(x => x.Page1Property);
public class PartialObject2Mapping : ClassMap<PartialObject2>
{
	Map(x => x.Page2Property);

When loading the object from the database onto the page we used 'TheObject' and its associated mappings and when updating the object from the individual pages we could use the partial object mappings.

I think this was quite a neat approach as it allowed us to reduce the complexity of our controller code when updating an object as well as removing the need for one trip to the database.

The trade off was that we ended up writing more mapping code but that seemed to be a reasonable trade off to make.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket