Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null vs Value Not Set

We've written a web service which uses a simple entity translator to map the values of DTO back on to "real" server side business objects. As part of this excercise. We have come across an "interesting" distinction between explicitly set null values and clients having not set a value.

The problem is essentially that we want to set a default value on the real business object if the client has not explicitly set a value, however using standard nullable types there is no way to tell if a client has explicitly meant "set this to null" or just not set it.

The solution here is obviously some sort of "flag".

Within a business object we can track the state of a field internally using private "IsDirty" flags set within the property setters, but a DTO only really specifies an Interface so this means exposing this data to the public. This leaves a number of implementation options. The language is C# (so statically typed) so...

  1. We could expose an "IsSet" flag on each property?
  2. We could expose each property as a class which has a .Value and .IsSet property? etc. etc.

How would you choose to expose these "flags" on the Data Contract? What would you here regard as best practice for this?

Any opinions on this would be greatly appreciated.

like image 744
ChrisV Avatar asked May 11 '09 07:05

ChrisV


2 Answers

Using a class for each property value would be more scalable that having to declare a bool for each property. It would also enable you to chose which properties are able to be left empty and/or set to null.

like image 169
stevehipwell Avatar answered Sep 17 '22 15:09

stevehipwell


You could write a class that wraps the flags with the data:

public class DtoData<T> 
{
  T data;
  bool IsSet { get; private set; }
  T Data 
  { 
    get { return data; }
    set { data = value; IsSet = true; } 
  }
}


public class XyzDto 
{
  // only private setters, initialize in constructor
  DtoData<int?> SomeInt { get; private set; }
  DtoData<string> SomeString { get; private set; }
}

This has some disadvantages so. For instance, that all your data is wrapped in a reference type, so the reference to DtoData could still be null, you need to create them in a constructor. And it's hard to make values accessible only internal or protected.


Personally, I would try to avoid this problem. Why should "not defined" actually exist? Are you sending around differences, incomplete Dtos, or where does it come from? This problem could come with filters, where you need a difference if you filter a field for null or if you don't filter it at all. But for such scenarios, you need a special "field-filter" class anyway.

like image 40
Stefan Steinegger Avatar answered Sep 17 '22 15:09

Stefan Steinegger