{"id":3071,"date":"2015-02-11T13:00:09","date_gmt":"2015-02-11T13:00:09","guid":{"rendered":"http:\/\/writeasync.net\/?p=3071"},"modified":"2015-02-11T15:19:26","modified_gmt":"2015-02-11T15:19:26","slug":"null-objects-not-values","status":"publish","type":"post","link":"http:\/\/writeasync.net\/?p=3071","title":{"rendered":"Null objects, not values"},"content":{"rendered":"<p>The <a href=\"http:\/\/en.wikipedia.org\/wiki\/Null_Object_pattern\">Null Object pattern<\/a> is oft-cited but not-oft-enough used (in my experience). After all, which looks more elegant\/maintainable\/object-oriented?<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n\/\/ Null values\r\npublic IEnumerable&lt;Result&gt; GetFilteredResults()\r\n{\r\n    IEnumerable&lt;Result&gt; results = this.GetAllResults();\r\n\r\n    \/\/ Callee can return a null sequence, need to be defensive.\r\n    if (results != null)\r\n    {\r\n        IFilter filter = this.GetFilter();\r\n        foreach (Result result in results)\r\n        {\r\n            \/\/ Filter may have been undefined -- check explicitly.\r\n            if ((filter == null) || filter.Passes(result))\r\n            {\r\n                yield return result;\r\n            }\r\n        }\r\n    }\r\n}\r\n\r\n\/\/ Null objects\r\npublic IEnumerable&lt;Result&gt; GetFilteredResults()\r\n{\r\n    \/\/ Is it a real filter or a 'Null' filter? Who cares!\r\n    IFilter filter = this.GetFilter();\r\n\r\n    \/\/ Is the results sequence empty? Doesn't matter!\r\n    foreach (Result result in this.GetAllResults())\r\n    {\r\n        if (filter.Passes(result))\r\n        {\r\n            yield return result;\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p>The difference is subtle but important. Not only do null checks go away in the Null Object world, but overall responsibilities become more explicit and unambiguous &#8212; &#8220;run a filter against a sequence, that&#8217;s all&#8221; as opposed to &#8220;act as a pass all filter if none provided, otherwise run the filter as usual.&#8221;<\/p>\n<p>When Null Object is eschewed, &#8220;performance overhead&#8221; is typically cited. Returning an object might mean allocating memory. Too many heap allocations in a particularly hot path may lead to an <a href=\"https:\/\/msdn.microsoft.com\/en-us\/magazine\/cc163528.aspx\">overworked garbage collector<\/a>. Such concerns are sometimes (or perhaps most of the time?) imaginary, but <a href=\"https:\/\/www.facebook.com\/notes\/facebook-engineering\/three-optimization-tips-for-c\/10151361643253920\">if backed up by measurement<\/a>, they are of course worth consideration.<\/p>\n<p>Allocation&#8217;s usual antidote is caching. The Null version of your object could be a pre-created instance that you hand out as needed, e.g.:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\nclass PassAllFilter : IFilter\r\n{\r\n    public bool Passes(Result result)\r\n    {\r\n        return true;\r\n    }\r\n}\r\n\r\nclass MyClass\r\n{\r\n    \/\/ We'll allocate only one of these filters per AppDomain,\r\n    \/\/ no matter how many MyClass instances are created.\r\n    private static readonly IFilter DefaultFilter = new PassAllFilter();\r\n\r\n    public MyClass()\r\n    {\r\n        this.Filter = DefaultFilter;\r\n    }\r\n\r\n    public IFilter Filter { get; set; }\r\n\/\/ ...\r\n}\r\n<\/pre>\n<p>This works fine in the above case for at least two reasons: the <code>IFilter<\/code> implementation is <strong>stateless\/immutable<\/strong>, and there is no real penalty for eagerly constructing it (in other words, we don&#8217;t benefit much from <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/dd997286(v=vs.110).aspx\">laziness<\/a>).<\/p>\n<p>But let&#8217;s take a look at the <code>GetFilteredResults<\/code> code again. The dominant cost here is far more likely to be the <strong>construction of a new sequence\/enumerator on each call<\/strong> due to the use of an <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/dscyy5s0.aspx\">iterator method<\/a>. Perhaps <em>that<\/em> is the more pressing concern to be addressed. One possible solution lies in the <a href=\"https:\/\/pragprog.com\/articles\/tell-dont-ask\">Tell Don&#8217;t Ask<\/a> (TDA) style. Rather than returning raw data, we preserve <a href=\"http:\/\/en.wikipedia.org\/wiki\/Encapsulation_(object-oriented_programming)\">encapsulation<\/a> and have the caller tell us what to do with the data:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n\/\/ VOID return\r\npublic void ForEachFilteredResult(Action&lt;Result&gt; action)\r\n{\r\n    \/\/ Still using Null Object here, of course!\r\n    IFilter filter = this.GetFilter();\r\n    foreach (Result result in this.GetAllResults())\r\n    {\r\n        if (filter.Passes(result))\r\n        {\r\n            \/\/ Apply the caller's operation here\r\n            action(result);\r\n        }\r\n    }\r\n}\r\n\r\n\/\/ Sample use case\r\nForEachFilteredResult(r =&gt; PrintResult(r.ToString()));\r\n<\/pre>\n<p>There are still possible sources of overhead here. Passing the action as a delegate may involve <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/0yw3tz5k.aspx\">implicitly capturing surrounding local state variables<\/a>. This is why a lot of delegates end up accepting an extra <code>Object<\/code> parameter to pass user-defined data, e.g. in <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/hh160386(v=vs.110).aspx\"><code>Task.ContinueWith<\/code><\/a>.<\/p>\n<p>To recap: Null Objects are a great tool for better OO, but the performance gains you seek may point you in an entirely different (but even more strongly object-oriented) direction.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Null Object pattern is oft-cited but not-oft-enough used (in my experience). After all, which looks more elegant\/maintainable\/object-oriented? \/\/ Null values public IEnumerable&lt;Result&gt; GetFilteredResults() { IEnumerable&lt;Result&gt; results = this.GetAllResults(); \/\/ Callee can return a null sequence, need to be defensive.&hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[91],"tags":[],"class_list":["post-3071","post","type-post","status-publish","format-standard","hentry","category-design"],"_links":{"self":[{"href":"http:\/\/writeasync.net\/index.php?rest_route=\/wp\/v2\/posts\/3071","targetHints":{"allow":["GET"]}}],"collection":[{"href":"http:\/\/writeasync.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/writeasync.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/writeasync.net\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/writeasync.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=3071"}],"version-history":[{"count":0,"href":"http:\/\/writeasync.net\/index.php?rest_route=\/wp\/v2\/posts\/3071\/revisions"}],"wp:attachment":[{"href":"http:\/\/writeasync.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=3071"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/writeasync.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=3071"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/writeasync.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=3071"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}