Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Default Values and Smarter Property Assessors

In your applications there may be times when you want to give the user the ability to override a setting or configuration value.  Often times you want to provide sensible defaults so that every single configuration option does not have to be specified, only those you which to override.  I want to show a very simple way to make your applications a bit smarter when creating classes with overridable default values.

Example 1:

   1: public class DemoObejct
   2: {
   3:     private string DEFAULT_MESSAGE = "Thank you for your order";
   4:     
   5:     private string message = DEFAULT_MESSAGE;
   6:     
   7:     public string Message
   8:     {
   9:         get { return message; }
  10:         set { message = value; }
  11:     }
  12: }

Example 2:

   1: public class DemoObejct
   2: {
   3:     private string DEFAULT_MESSAGE = "Thank you for your order";
   4:     
   5:     private string message;
   6:     
   7:     public string Message
   8:     {
   9:         get { return message ?? DEFAULT_MESSAGE; }
  10:         set { message = value; }
  11:     }
  12: }

So what's the difference?  The difference IS subtle but I consider the following code snippet:

   1: var obj = new DemoObject();
   2:  
   3: Console.WriteLine(obj.Message);
   4:  
   5: obj.Message = null;
   6:  
   7: Console.WriteLine(obj.Message);

Setting the Message property to null in line 5 results in different behavior between the two examples.  I find the second example to be preferable, setting the property to null invokes the default message again.  It's a very simple thing you can do to provide a more robust object

Here are two more examples where I use this strategy often:

Integers and Default Values:

   1: public class DemoObject
   2: {
   3:     private int? attemptThreshold;
   4:     private const int DEFAULT_ATTEMPTTHRESHOLD = 3;        
   5:         
   6:     public int AttemptThreshold
   7:     {
   8:         get { return attemptThreshold.HasValue ? attemptThreshold.Value : DEFAULT_ATTEMPTTHRESHOLD; }
   9:         set { attemptThreshold = value; }
  10:     }
  11: }

Logging Component:

   1: public class DemoObject
   2: {
   3:     private ILogger logger;
   4:  
   5:     public ILogger Logger
   6:     {
   7:         get { return logger ?? NullLogger.Instance; }
   8:         set { logger = value; }
   9:     }
  10: }

The above logging example is where this type of strategy really shines.  It prevents NullReferenceExceptions in your code if by chance your logger gets a null value at some point, again providing for a more robust object and application.


Posted 03-01-2009 9:18 PM by Tim Barcz
Filed under:

[Advertisement]

Comments

Joel Holder wrote re: Default Values and Smarter Property Assessors
on 03-01-2009 10:50 PM

I use this technique sometimes to create ViewState-backed properties in WebForms.  uberpwn.spaces.live.com/.../cns!3FC3980D58CF7EFB!227.entry

Jeremy Gray wrote re: Default Values and Smarter Property Assessors
on 03-02-2009 12:18 AM

I do understand and appreciate the intent you have in mind, but I'm afraid that I have to disagree with this specific approach.

If you don't want values being set to null, you need a guard clause in your setter. If you want Null Object (or "Missing Object") pattern behavior, implement Null Object (or "Missing Object") pattern. If your classes need these things set properly in order to function correctly, get your invariants specified, construct your object in a valid state from the outset, and then keep it valid.

Setting your system up to hide bugs (null assignments and/or partially-constructed objects) is not what I would prefer to describe as "robust", as much as it may mask issues for a little while.

sotto wrote re: Default Values and Smarter Property Assessors
on 03-02-2009 7:03 AM

Why don't you use the ?? operator with the nullable integer?

Tim Barcz wrote re: Default Values and Smarter Property Assessors
on 03-02-2009 9:33 AM

@Jeremy

"If you don't want values being set to null" - the point is I don't care, if someone wants to null the object to get the default behavior back, they should be able to do so.

"If your classes need these things set properly in order to function correctly, get your invariants specified, construct your object in a valid state from the outset, and then keep it valid."

They don't need these things.  Let's say I have four properties all with default values, the user can create the class and start using right away taking all the default values or they can override specifics ones for more fine grained control.  The base class library does this type of thing for you often, most people just don't realize it.

"Setting your system up to hide bugs (null assignments and/or partially-constructed objects) is not what I would prefer to describe as "robust", as much as it may mask issues for a little while."

Hide bugs?  No way!  This post is definitely not promoting the hiding of bugs, I'm sorry you read it that way.  As far as the paritally-constructed comment, again, the object is fully constructed, with some values coming from default values.  There is no recommendation of partially-constructed object.

Tim Barcz wrote re: Default Values and Smarter Property Assessors
on 03-02-2009 9:34 AM

@sotto

Totally could have, there's nothing wrong with that approach.

Keith Dahlby wrote re: Default Values and Smarter Property Assessors
on 03-02-2009 9:35 AM

Coalesce (??) essentially compiles into the pattern Tim used:

   int? CS$0$0001 = attemptThreshold;

   return (CS$0$0001.HasValue ? CS$0$0001.GetValueOrDefault() : DEFAULT_ATTEMPTTHRESHOLD);

Nullable<T> provides a method just for this purpose:

   return attemptThreshold.GetValueOrDefault(DEFAULT_ATTEMPTTHRESHOLD);

Jeremy's argument sounds a lot like design for design's sake. Why complicate things if this accomplishes the same goal and is equally maintainable? This approach doesn't preclude you from logging attempts to set invalid data, it just ensures the property will never return null.

Cheers ~

Keith

Arjan`s World » LINKBLOG for March 2, 2009 wrote Arjan`s World &raquo; LINKBLOG for March 2, 2009
on 03-02-2009 2:55 PM

Pingback from  Arjan`s World    &raquo; LINKBLOG for March 2, 2009

devlicio.us wrote re: Default Values and Smarter Property Assessors
on 04-03-2011 1:18 PM

Default values and smarter property assessors.. Awesome :)

devlicio.us wrote re: Default Values and Smarter Property Assessors
on 04-22-2011 8:56 AM

Default values and smarter property assessors.. Smashing :)

devlicio.us wrote re: Default Values and Smarter Property Assessors
on 06-02-2011 7:47 PM

Default values and smarter property assessors.. I like it :)

devlicio.us wrote re: Default Values and Smarter Property Assessors
on 06-04-2011 8:08 PM

Default values and smarter property assessors.. Great! :)

r7sw porn video hpge wrote re: Default Values and Smarter Property Assessors
on 07-02-2011 1:52 AM

Default values and smarter property assessors.. Awful :)

seo social bookmarking wrote re: Default Values and Smarter Property Assessors
on 01-18-2013 6:43 PM

YyWJ9J Really enjoyed this article post.Really thank you! Great.

http://bestmedicineonline.info wrote re: Default Values and Smarter Property Assessors
on 02-15-2013 6:49 AM

IbrWp9 Really appreciate you sharing this post.Much thanks again. Awesome.

social bookmarking service wrote re: Default Values and Smarter Property Assessors
on 04-03-2013 11:15 PM

X4UI6i Thanks for the post.Really thank you! Much obliged.

grizzly bears wrote re: Default Values and Smarter Property Assessors
on 04-06-2013 12:36 AM

I really enjoy the article.Much thanks again. Fantastic.

super news wrote re: Default Values and Smarter Property Assessors
on 07-13-2013 12:52 PM

yWEj0y Appreciate you sharing, great blog.Thanks Again. Really Great.

awesome linkbuilding site wrote re: Default Values and Smarter Property Assessors
on 10-01-2013 7:24 AM

yVxnXl I really liked your blog.Much thanks again. Will read on...

Add a Comment

(required)  
(optional)
(required)  
Remember Me?

About The CodeBetter.Com Blog Network
CodeBetter.Com FAQ

Our Mission

Advertisers should contact Brendan

Subscribe
Google Reader or Homepage

del.icio.us CodeBetter.com Latest Items
Add to My Yahoo!
Subscribe with Bloglines
Subscribe in NewsGator Online
Subscribe with myFeedster
Add to My AOL
Furl CodeBetter.com Latest Items
Subscribe in Rojo

Member Projects
DimeCasts.Net - Derik Whittaker

Friends of Devlicio.us
Red-Gate Tools For SQL and .NET

NDepend

SlickEdit
 
SmartInspect .NET Logging
NGEDIT: ViEmu and Codekana
LiteAccounting.Com
DevExpress
Fixx
NHibernate Profiler
Unfuddle
Balsamiq Mockups
Scrumy
JetBrains - ReSharper
Umbraco
NServiceBus
RavenDb
Web Sequence Diagrams
Ducksboard<-- NEW Friend!

 



Site Copyright © 2007 CodeBetter.Com
Content Copyright Individual Bloggers

 

Community Server (Commercial Edition)