{"id":718,"date":"2009-10-12T20:29:19","date_gmt":"2009-10-12T19:29:19","guid":{"rendered":"http:\/\/www.gamlor.info\/wordpress\/?p=718"},"modified":"2021-03-11T09:44:57","modified_gmt":"2021-03-11T08:44:57","slug":"maybe-monad-or-the-better-nullreference","status":"publish","type":"post","link":"https:\/\/www.gamlor.info\/wordpress\/2009\/10\/maybe-monad-or-the-better-nullreference\/","title":{"rendered":"Maybe-Monad (Or The Better NullReference)"},"content":{"rendered":"<p>The Maybe-Monad sounds like some magic, but it\u2019s something terrible simple. Its a computation which returns a result or \u2018Nothing\u2019. Often the a null-reference is used to represent \u2018Nothing\u2019. This is common practice, but in my opinion this isn\u2019t a elegant solution. First you have to read the documentation to know that the function may return null. Then you have check for null explicit. Furthermore you cannot chain calls anymore since the code is chopped up in check-statements. It would be much more elegant to represent such a computation more explicit. In .NET the <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.nullable.aspx\">Nullable<\/a>-Type actually allows this. It explicit states that the returned result is either the value or \u2018Nothing\u2019. However it only works on value-types, which is rather limiting.<\/p>\n<p>I\u2019ve found this <a href=\"http:\/\/abdullin.com\/journal\/2009\/10\/6\/zen-development-practices-c-maybe-monad.html\">blog entry which introduces a Maybe-class<\/a> with a lot of useful operations. I always wanted to implement something like this but now I don\u2019t have to. I can just use it and get rid of null-returns.<\/p>\n<div id=\"attachment_729\" style=\"width: 310px\" class=\"wp-caption alignnone\"><a href=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/maybe.png\"><img loading=\"lazy\" decoding=\"async\" aria-describedby=\"caption-attachment-729\" class=\"size-medium wp-image-729\" title=\"maybe\" src=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/maybe-300x209.png\" alt=\"may-pi\" width=\"300\" height=\"209\" srcset=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/maybe-300x209.png 300w, https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/maybe-1024x714.png 1024w, https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/maybe.png 1200w\" sizes=\"(max-width: 300px) 100vw, 300px\" \/><\/a><p id=\"caption-attachment-729\" class=\"wp-caption-text\">may-pi<\/p><\/div>\n<p>The cool thing about the Maybe-class is that it allows you to avoid if-else-checks by using a clear functional style. An example:<\/p>\n<pre class=\"csharpcode\"><span class=\"rem\">\/\/ 1. we try to get a person<\/span>\r\n<span class=\"rem\">\/\/ 2. we 'convert' to person into an email, but only if it actually has a value<\/span>\r\n<span class=\"rem\">\/\/ 3. then we send an email, but only if it actually has a value<\/span><\/pre>\n<pre class=\"csharpcode\">Maybe&lt;Person&gt; person = TryGetById(111);\r\nperson.Convert(p=&gt;p.Email)\r\n    .Apply(SendMail);<\/pre>\n<p>\u00a0<\/p>\n<p>Another example with the IDictionary.TryGetValue. The classic-version is really ugly. First it requires an if-else-case. In addition you cannot assign the value directly, which prevent you from using the var-declaration:<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">public<\/span> <span class=\"kwrd\">class<\/span> PersonServices\r\n{\r\n    IDictionary&lt;<span class=\"kwrd\">string<\/span>, Person&gt; emailTable = <span class=\"kwrd\">\/\/ some value<\/span>\r\n\r\n    <span class=\"kwrd\">public<\/span> IEnumerable&lt;Person&gt; PersonByEmail(<span class=\"kwrd\">string<\/span> email)\r\n    {\r\n        Person person;\r\n        <span class=\"kwrd\">if<\/span>(emailTable.TryGetValue(email,<span class=\"kwrd\">out<\/span> person))\r\n        {\r\n            <span class=\"kwrd\">return<\/span> person.Children;\r\n        } <span class=\"kwrd\">else<\/span>\r\n        {\r\n            <span class=\"kwrd\">return<\/span> <span class=\"kwrd\">new<\/span> Person[0];\r\n        }\r\n    }\r\n}<\/pre>\n<p>Now the Maybe-Version. It\u2019s only 3 lines of code instead of 8. The .TryGet is an extension-method which returns a Maybe&lt;Person&gt;. The next-line gets the children of the person if a person is returned. The last line gets the value or returns a sensible default.<\/p>\n<pre class=\"csharpcode\"><span class=\"kwrd\">public<\/span> <span class=\"kwrd\">class<\/span> PersonServices\r\n{\r\n    IDictionary&lt;<span class=\"kwrd\">string<\/span>, Person&gt; emailTable = <span class=\"kwrd\">\/\/ some value<\/span>\r\n\r\n    <span class=\"kwrd\">public<\/span> IEnumerable&lt;Person&gt; PersonByEmail(<span class=\"kwrd\">string<\/span> email)\r\n    {\r\n        <span class=\"kwrd\">return<\/span> emailTable.TryGet(email)\r\n            .Convert(p =&gt; p.Children)\r\n            .GetValue(<span class=\"kwrd\">new<\/span> Person[0]);\r\n    }\r\n}<\/pre>\n<pre class=\"csharpcode\">\u00a0<\/pre>\n<p>But certainly you already have code which doesn\u2019t use this programming idiom. But you can create an extension-method to convert reference-types to Maybe-object.<\/p>\n<pre class=\"csharpcode\">Maybe&lt;AuthContext&gt; LoadAuthContext(<span class=\"kwrd\">long<\/span> userId)\r\n{\r\n    <span class=\"kwrd\">return<\/span> oldSessionService.LoadUser(userId)\r\n        .AsMaybe().Convert(usr=&gt;ConvertToAuthContext(usr));\r\n}<\/pre>\n<p>Of course this could also be implemented in other languages. In some it would be even more elegant (in the functional ones this is anyway integrated). In others like JAVA the benefit isn\u2019t that great due the inner-classes boiler-plate-code.<\/p>\n<p>And of course use this only when needed. Prefer methods which always return a valid value.<\/p>\n<p>The original code is from this <a href=\"http:\/\/abdullin.com\/journal\/2009\/10\/6\/zen-development-practices-c-maybe-monad.html\">blog-post<\/a> and the <a href=\"http:\/\/code.google.com\/p\/lokad-shared-libraries\/\">lokad-shared-libraries<\/a>. (I use a stripped version, since I don\u2019t want to include the whole library). The extension-methods are here: <a href=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/MayExtensions.cs\">MayExtensions.cs<\/a>\u00a0and <a href=\"https:\/\/www.gamlor.info\/wordpress\/wp-content\/uploads\/TestMaybeExtensions.cs\">TestMaybeExtensions.cs<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The Maybe-Monad sounds like some magic, but it\u2019s something terrible simple. Its a computation which returns a result or \u2018Nothing\u2019. Often the a null-reference is used to represent \u2018Nothing\u2019. This&hellip; <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","_links_to":"","_links_to_target":""},"categories":[126],"tags":[21],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/718"}],"collection":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/comments?post=718"}],"version-history":[{"count":7,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/718\/revisions"}],"predecessor-version":[{"id":3832,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/posts\/718\/revisions\/3832"}],"wp:attachment":[{"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/media?parent=718"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/categories?post=718"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.gamlor.info\/wordpress\/wp-json\/wp\/v2\/tags?post=718"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}