<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Shani Fedida</title>
    <description>The latest articles on DEV Community by Shani Fedida (@shanif).</description>
    <link>https://dev.to/shanif</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F208324%2F6b3d5286-ce43-4c9e-a515-6baad57328d4.jpg</url>
      <title>DEV Community: Shani Fedida</title>
      <link>https://dev.to/shanif</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/shanif"/>
    <language>en</language>
    <item>
      <title>How to get rid of NullPointerException</title>
      <dc:creator>Shani Fedida</dc:creator>
      <pubDate>Sat, 12 Sep 2020 17:39:53 +0000</pubDate>
      <link>https://dev.to/shanif/how-to-get-rid-of-nullpointerexception-35k</link>
      <guid>https://dev.to/shanif/how-to-get-rid-of-nullpointerexception-35k</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftrbdlcgdm59j8liar738.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ftrbdlcgdm59j8liar738.png" alt="NULL MEME" width="800" height="434"&gt;&lt;/a&gt;&lt;/p&gt;

NullPointerException — it surprises me the same as it surprises you




&lt;p&gt;OverOps, an Israeli company that helps developers understand what happens in production, carried out &lt;a href="https://blog.takipi.com/the-top-10-exceptions-types-in-production-java-applications-based-on-1b-events/" rel="noopener noreferrer"&gt;research&lt;/a&gt; on what are the top Java exception in production. Want to guess which one is in #1 place? &lt;strong&gt;NullPointerException&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3beeu8wnxvjzumaxomec.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3beeu8wnxvjzumaxomec.png" alt="NullPointerException OverOps’s monster" width="140" height="154"&gt;&lt;/a&gt;&lt;/p&gt;

NullPointerException OverOps’s monster




&lt;p&gt;Why is this exception is so frequent? I argue (as does Uncle Bob in his book Clean Code 😉) that it is &lt;strong&gt;not&lt;/strong&gt; because developers forget to add null checks.&lt;/p&gt;

&lt;p&gt;The reason: &lt;strong&gt;developers use nulls too often.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  So where do all those NULLs come from?
&lt;/h2&gt;

&lt;p&gt;In C# and Java, all reference types can point to null. We can get a reference to point to null in the following ways:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;“uninitialized” reference type variables — variables that are initialized with nulls and are assigned with their real value afterward. A bug can cause them to never be reassigned.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;uninitialized reference-type class's members.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;explicit assignment to null or returning null from a function.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here are some patterns I noticed in functions returning null:&lt;/p&gt;

&lt;h3&gt;
  
  
  Error handling
&lt;/h3&gt;

&lt;p&gt;Returning null when the input is invalid. This is one way of returning error codes. I think it is an old school programming style, originating in the times when exceptions didn’t exist.&lt;/p&gt;

&lt;h3&gt;
  
  
  Missing optional data for entities
&lt;/h3&gt;

&lt;p&gt;An entity’s property can be optional. When there is no data for an optional property, it returns null.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  Hierarchical models
&lt;/h3&gt;

&lt;p&gt;In hierarchical models, we usually can navigate up and down. When we are at the top, we need a way to say so, usually we do it by returning null.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  Find functions
&lt;/h3&gt;

&lt;p&gt;When we want to find an entity by criteria in a collection, we return null as a way to say the entity was not found.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h2&gt;
  
  
  What are the problems with using nulls?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  It will blow up. Eventually…
&lt;/h3&gt;

&lt;p&gt;The code in which the NullPointerException is raised can be very far from where the bug is. &lt;strong&gt;It makes tracing the real problem harder&lt;/strong&gt;. Especially if the code is branched.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe6qnlh9w8wdecnh7mewo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe6qnlh9w8wdecnh7mewo.png" alt="I am happy now but I will blow up eventually." width="200" height="200"&gt;&lt;/a&gt;&lt;/p&gt;

I am happy now but I will blow up eventually.




&lt;p&gt;In the following code example, there is a bug, somewhere in class A, causing &lt;code&gt;entity&lt;/code&gt; to be null. But the NullPointerException is raised inside a function of class B. Real-life code can be much more complicated.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  Hidden errors
&lt;/h3&gt;

&lt;p&gt;I encounter null checks which seem like the developer was thinking:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;“I know I should check for null but I don’t know what it means when the function returns null and I don’t know what to do with it,” or&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;“ I think this cannot be null but just to make sure, I don’t want it to blow up in production”&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;It usually looks like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Those kinds of null checks cause some code logic to not trigger, &lt;strong&gt;without the ability to know about it&lt;/strong&gt;. Writing this kind of code means that some logic of a flow failed but the whole flow succeeded. It also can cause a bug in some other functionality which assumed the other function did its job.&lt;/p&gt;

&lt;p&gt;Imagine you buy a ticket to a show online. You got a success message! The day of the show finally arrived, you leave work early, arrange a babysitter, and go to see the show. When you arrive you discover you don’t have tickets! and there are no empty seats. You return home upset and confused😠. &lt;strong&gt;Can you see how this kind of null check can cause this situation ?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;It also makes the code branched and ugly 😢&lt;/p&gt;

&lt;h2&gt;
  
  
  Missing non-nullable reference types in C# and Java
&lt;/h2&gt;

&lt;p&gt;In C# and Java &lt;strong&gt;reference types can always point to null&lt;/strong&gt;. This leads to a situation that we cannot know, by looking at a function signature, if null is a valid input or output of it. I believe most of the functions don’t return or accept null.&lt;/p&gt;

&lt;p&gt;Because it is hard to know if a function returns null or not (unless documented), developers are either inserting null checks when not needed or don’t check for nulls when needed — and yes, sometimes putting null checks when needed 😉.&lt;/p&gt;

&lt;p&gt;This poor design choice causes the problems I described before in “Hidden errors” and a lot of NullPointerException errors, of course. Lose-lose situation. 😢&lt;/p&gt;

&lt;p&gt;There are languages like &lt;a href="https://kotlinlang.org/docs/reference/null-safety.html" rel="noopener noreferrer"&gt;Kotlin &lt;/a&gt;that aim to eliminate NullPointerException errors by differentiating between nullable references and non-nullable references. This allows catching the null assigned to non-null references and making sure developers check for null before dereferencing nullable references, &lt;strong&gt;all at compile-time&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Microsoft is adopting the same approach by introducing &lt;a href="https://msdn.microsoft.com/en-us/magazine/mt829270.aspx" rel="noopener noreferrer"&gt;Nullable Reference Types&lt;/a&gt; in C#8.&lt;/p&gt;

&lt;h2&gt;
  
  
  So what should we do?
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Listen to Uncle Bob
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://en.wikipedia.org/wiki/Robert_C._Martin" rel="noopener noreferrer"&gt;Robert C. Martin&lt;/a&gt;, who is widely known as “Uncle Bob,” wrote one of the most famous books about clean code called (surprisingly) &lt;a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882" rel="noopener noreferrer"&gt;“Clean Code”&lt;/a&gt;. In this book, Uncle Bob claims, &lt;strong&gt;we should not return nulls and should not pass null to a function.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F31j81puhdn3cmbbxbhp3.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F31j81puhdn3cmbbxbhp3.jpg" width="702" height="395"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  But how?
&lt;/h3&gt;

&lt;p&gt;I want to propose some &lt;strong&gt;technical patterns&lt;/strong&gt; for eliminating null usage. &lt;strong&gt;I am not saying this is the best solution for every scenario — just options&lt;/strong&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Using the option type
&lt;/h4&gt;

&lt;p&gt;The &lt;a href="https://en.m.wikipedia.org/wiki/Option_type?wprov=sfla1&amp;amp;fbclid=IwAR3Y-vZX-mrpINhipnr_tjyZ4P8KZH0yLCtvcJqbtaMxry2DO6HJWdSP3XA" rel="noopener noreferrer"&gt;option type&lt;/a&gt; is a different way to represent an optional value. This type asks if a value exists and, if so, accesses the value. &lt;strong&gt;When trying to access the value which doesn’t exist, it raises an exception&lt;/strong&gt;. This solves the problem of NullPointerException raised in code areas away from the bug. In Java there is the &lt;a href="https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html" rel="noopener noreferrer"&gt;Optional class&lt;/a&gt;. In C# (until C# 7 ) there is the &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/nullable-types/" rel="noopener noreferrer"&gt;Nullable type&lt;/a&gt; which is only for value types but you can create your own or use a &lt;a href="https://github.com/nlkl/Optional" rel="noopener noreferrer"&gt;library&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;A straightforward approach is to replace a reference that can be null (by logic) with this type:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h4&gt;
  
  
  Splitting the function into two
&lt;/h4&gt;

&lt;p&gt;Each function that returns null will be converted into two functions. One function with the same signature that throws an exception instead of returning null. The second function returns a boolean representing if it is valid or not to call the first function. Let’s see an example:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;If the code holding an &lt;code&gt;IEmployee&lt;/code&gt; instance assumes this employee has a manager the code should call to &lt;code&gt;Manager&lt;/code&gt;. But if this assumption doesn’t exist the code should call to &lt;code&gt;HasManager&lt;/code&gt; and handle the two possible outputs.&lt;/p&gt;

&lt;p&gt;Let’s see another example:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
 

&lt;p&gt;The logic of &lt;code&gt;ContainsEmployeById&lt;/code&gt; is the same as &lt;code&gt;FindEmployeById&lt;/code&gt; but without returning the employee. Now let’s say that those functions reach the DB, we have a performance problem here. Let’s introduce a similar but different pattern: the boolean function when returning true will also return the data we search for. It looks like this:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;A common use of this pattern is &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.int32.parse?view=netframework-4.7.2#System_Int32_Parse_System_String_" rel="noopener noreferrer"&gt;int.Parse&lt;/a&gt; and &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.int32.tryparse?view=netframework-4.7.2#System_Int32_TryParse_System_String_System_Int32__" rel="noopener noreferrer"&gt;int.TryParse&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The fact that I can separate a function to two functions and each has its usages is a sign that &lt;strong&gt;returning null is a code smell for violating the Single Responsibility Principle&lt;/strong&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Splitting the interface
&lt;/h4&gt;

&lt;p&gt;A practical guideline we can derive from the &lt;a href="https://en.wikipedia.org/wiki/Liskov_substitution_principle" rel="noopener noreferrer"&gt;Liskov principle&lt;/a&gt; is that a class &lt;strong&gt;must implement all the functions&lt;/strong&gt; of an interface it implements. Returning null or throwing an exception are ways to not implement a function. So &lt;strong&gt;returning null is a code smell for violating the Liskov principle.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;If a class can’t implement a specific interface’s function &lt;strong&gt;we can move that function to another interface&lt;/strong&gt; and each class will implement only the interface it can.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now instead of asking &lt;code&gt;employee.HasManager&lt;/code&gt; — which we will do if we used the first approach “Splitting the function into two” — we ask employee is &lt;code&gt;IManagedEmployee&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  I am not working alone and not on a greenfield project. What now?
&lt;/h2&gt;

&lt;p&gt;In existing codebases, there is a lot of code returning reference types. We cannot know if null is a valid output or not.&lt;/p&gt;

&lt;p&gt;The first quick win I wish you to have is to &lt;strong&gt;change your coding conventions&lt;/strong&gt; so null is not a valid input or output to a function. Or, at least when you decide that null is a valid output, use &lt;strong&gt;the Option type.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Some tools can help to enforce this convention like &lt;a href="https://www.jetbrains.com/help/resharper/Code_Analysis__Value_Analysis.html" rel="noopener noreferrer"&gt;ReSharper &lt;/a&gt;and &lt;a href="https://github.com/Fody/NullGuard" rel="noopener noreferrer"&gt;NullGuard&lt;/a&gt;. I guess, although I haven’t tried this yet, you can add a &lt;a href="https://docs.sonarqube.org/display/DEV/Adding+Coding+Rules" rel="noopener noreferrer"&gt;custom rule to SonarQube&lt;/a&gt; which will alert when the word null appears.&lt;/p&gt;




&lt;p&gt;I would love to know what you think. Are you going to embrace this convention? And if not, why? What’s holding you back?&lt;/p&gt;

&lt;p&gt;If you encounter a scenario in which you think returning null is the right design choice, or the patterns I suggested are not good, I would love to know.&lt;/p&gt;

&lt;p&gt;Thanks &lt;a href="https://www.linkedin.com/in/mark-kazakov-98994197/" rel="noopener noreferrer"&gt;Mark Kazakov‏&lt;/a&gt; for the funny meme, &lt;a href="https://www.linkedin.com/in/alex-zhitnitsky-86567238/" rel="noopener noreferrer"&gt;Alex Zhitnitsky &lt;/a&gt;from OverOps for answering my questions, &lt;a href="https://www.facebook.com/baot.tech/" rel="noopener noreferrer"&gt;Baot &lt;/a&gt;for organizing a great writing event for new bloggers, &lt;a href="https://www.linkedin.com/in/itzik-saban-54b93829/" rel="noopener noreferrer"&gt;Itzik Saban &lt;/a&gt;, &lt;a href="https://www.linkedin.com/in/amitayhorwitz/" rel="noopener noreferrer"&gt;Amitay Horwitz&lt;/a&gt; and &lt;a href="https://www.facebook.com/max.ophius" rel="noopener noreferrer"&gt;Max Ophius&lt;/a&gt; for giving me feedback.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>java</category>
      <category>codequality</category>
      <category>programming</category>
    </item>
    <item>
      <title>The 4th step in TDD</title>
      <dc:creator>Shani Fedida</dc:creator>
      <pubDate>Wed, 09 Sep 2020 18:47:05 +0000</pubDate>
      <link>https://dev.to/shanif/the-4th-step-in-tdd-26np</link>
      <guid>https://dev.to/shanif/the-4th-step-in-tdd-26np</guid>
      <description>&lt;p&gt;If you are doing TDD or not, your daily work is combined from a few repetitive actions. Each one has its own “methodology”, even if he is not aware of.&lt;/p&gt;

&lt;p&gt;Yesterday I have been working on a bug from production. I created a test reproducing the bug, meaning I had a failing test — the 1st step in TDD.&lt;/p&gt;

&lt;p&gt;While working, I found myself thinking about a lot of things in the same time: refactoring, trying to understand the existing code, how I make my test pass without breaking the others, how my tests should look like and so on.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;I got into a SWIRL.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fov8p7s3j2q3xd2ljvc2q.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fov8p7s3j2q3xd2ljvc2q.jpg" alt="SWIRL IMAGE" width="800" height="531"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;span&gt;Photo by &lt;a href="https://unsplash.com/@cassidykelley?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Cassidy Kelley&lt;/a&gt; on &lt;a href="https://unsplash.com/?utm_source=unsplash&amp;amp;utm_medium=referral&amp;amp;utm_content=creditCopyText" rel="noopener noreferrer"&gt;Unsplash&lt;/a&gt;&lt;/span&gt;




&lt;p&gt;When I noticed that, I stopped and said to myself ”Shani, one of the reasons you like TDD is because it makes you focus better. Currently, you are not focused at all”.&lt;/p&gt;

&lt;p&gt;So I decided to focus on &lt;strong&gt;just making my test pass&lt;/strong&gt;, ignoring that others will fail. And on that occasion make sure they do fail.&lt;/p&gt;

&lt;p&gt;If you think about this, I split TDD 2nd step into two:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;Make my test pass&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Make all the previous tests pass&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Why I did this?  Because I noticed thinking about those two together was mentally too much for me. (The number of objects an average human can hold in working memory is &lt;a href="https://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two" rel="noopener noreferrer"&gt;7 ± 2&lt;/a&gt;, I think for me is just 1 😅)&lt;/p&gt;

&lt;p&gt;So here it is, after a search for the relevant entry point for my code, &lt;strong&gt;I added one line with hard-coded values relevant only for my test&lt;/strong&gt;. Happily, Now some tests are red, time for the hard part: making it all work again.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5ae0dt45f3az3ccyvbtq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5ae0dt45f3az3ccyvbtq.png" alt="FOREST IMAGE" width="554" height="201"&gt;&lt;/a&gt;&lt;/p&gt;

start from a failing test and then make &lt;b&gt;only&lt;/b&gt; my test pass




&lt;p&gt;If my changes didn’t cause any tests to fail, it means I didn’t have tests testing different scenarios that were affected by my change (besides the bug scenario). Since I added one line with hard-coded values it probably should break some tests. If that was the case I should have added some green tests before I changed the code in order to catch regressions.&lt;/p&gt;

&lt;p&gt;Would love to hear your thoughts and about your personal methodologies.&lt;/p&gt;

</description>
      <category>tdd</category>
      <category>testing</category>
      <category>productivity</category>
      <category>programming</category>
    </item>
    <item>
      <title>Is the C# internal keyword a code smell?</title>
      <dc:creator>Shani Fedida</dc:creator>
      <pubDate>Fri, 04 Sep 2020 07:36:41 +0000</pubDate>
      <link>https://dev.to/shanif/is-the-c-internal-keyword-a-code-smell-2jn5</link>
      <guid>https://dev.to/shanif/is-the-c-internal-keyword-a-code-smell-2jn5</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flcsrduu0ccfy3ginppkf.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Flcsrduu0ccfy3ginppkf.jpg" alt="Alt Text" width="417" height="500"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;a href="https://www.freepik.com/photos/background" rel="noopener noreferrer"&gt;Background photo created by freepik - www.freepik.com&lt;/a&gt;




&lt;p&gt;In this post, I am going to show why I think the internal keyword, when put on class members, is a code smell and suggest better alternatives.&lt;/p&gt;

&lt;h2&gt;
  
  
  What is the internal keyword?
&lt;/h2&gt;

&lt;p&gt;In C# the &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/internal%29" rel="noopener noreferrer"&gt;internal keyword&lt;/a&gt; can be used on a class or its members. It is one of the C# &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/access-modifiers" rel="noopener noreferrer"&gt;access modifiers&lt;/a&gt;. Internal types or members are accessible &lt;strong&gt;only within files in the same assembly&lt;/strong&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why we need the internal keyword?
&lt;/h2&gt;

&lt;p&gt;“A common use of internal access is in component-based development because it &lt;strong&gt;enables a group of components to cooperate in a private manner without being exposed to the rest of the application code&lt;/strong&gt;. For example, a framework for building graphical user interfaces could provide Control and Form classes that cooperate by using members with internal access. Since these members are internal, they are not exposed to code that is using the framework.” (&lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/internal" rel="noopener noreferrer"&gt;C# internal keyword documentation&lt;/a&gt;)&lt;/p&gt;

&lt;p&gt;These are the use cases I saw for using the internal keyword on a class member:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Call a class’s private function within the same assembly.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In order to test a private function, you can mark it as internal and exposed the dll to the test DLL via &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.internalsvisibletoattribute?view=netframework-4.8" rel="noopener noreferrer"&gt;InternalsVisibleTo&lt;/a&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Both cases can be viewed as a &lt;a href="https://enterprisecraftsmanship.com/2017/10/23/unit-testing-private-methods/" rel="noopener noreferrer"&gt;code smell,&lt;/a&gt; saying that this private function should be public.&lt;/p&gt;

&lt;h2&gt;
  
  
  Let's see some examples
&lt;/h2&gt;

&lt;p&gt;Here is a simple example. a function in one class wants to access a private function of another class.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
 &lt;br&gt;
The solution is simple — just mark A::func2 as public.

&lt;p&gt;Let's look at a bit more complex example:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
 

&lt;p&gt;What’s the problem? just mark func2 as public as we did before.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
 

&lt;p&gt;But we can’t 😞. B is an internal class so it cannot be part of the signature of a public function of a public class.&lt;/p&gt;

&lt;p&gt;Those are the solutions I found, ordered by easiness:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Mark the function with the internal keyword&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Create an internal interface&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
 &lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Extract A.func2 to another internal class and use it instead of A.func2.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
 &lt;/li&gt;
&lt;li&gt;&lt;p&gt;Decouple the function from internal classes and make it public. This is much dependant on what the function is doing with its inputs. decouple the internal classes can be very easy, very hard, and even impossible (without ruing the design).&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  But we don’t have public classes we use interfaces…
&lt;/h3&gt;

&lt;p&gt;Let's look at some more real-world example:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
 

&lt;p&gt;Let's see how the previous solutions are adapted to this example:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;p&gt;Mark function with Internal. this means you will need to cast to class in order to call the function so &lt;em&gt;This will work only if class A is the only one that implements the interface&lt;/em&gt;, meaning IA is not mocked in tests and there isn’t another production class that implements IA.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Create an internal interface that extends the public interface.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Extract A.func2 to another internal class and use it instead of A.func2.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Decouple the function from internal classes and add it to the public interface.&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We can see that the &lt;strong&gt;internal keyword is the easiest solution&lt;/strong&gt;, but there are other solutions using the &lt;strong&gt;traditional building blocks of OOP: classes and interfaces&lt;/strong&gt;. We can see that the 2nd solution — adding an internal interface is not much harder than marking the function with the internal keyword.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why not use the internal keyword?
&lt;/h2&gt;

&lt;p&gt;As I showed in the previous examples, using the &lt;strong&gt;internal keyword is the easiest solution&lt;/strong&gt;. But you are going to have a hard time in the future if you will need to:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Move the public class A to another DLL (since the internal keyword will no longer apply to the same dll)&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Create another production class that implements IA&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Mock IA in tests&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You may think “But this is just one line of code, I or anyone else can change it easily if needed”. &lt;strong&gt;Now&lt;/strong&gt; you have &lt;strong&gt;one&lt;/strong&gt; line of code that looks like that:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;((MyClass)a).internalFunction
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;but if others will need to call this function too this &lt;strong&gt;line will be copy-pasted around&lt;/strong&gt; inside the DLL.&lt;/p&gt;

&lt;h2&gt;
  
  
  My Conclusion
&lt;/h2&gt;

&lt;p&gt;I think marking a class member with the internal keyword &lt;strong&gt;is a code smell&lt;/strong&gt;. In the examples I showed above it is the &lt;strong&gt;easiest&lt;/strong&gt; solution, BUT can cause problems in the future. Creating an &lt;strong&gt;internal interface is almost as easy and more explicit.&lt;/strong&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Compare to C++
&lt;/h2&gt;

&lt;p&gt;The C++ “friend” keyword is similar to the C# internal keyword. It allows a class or a function to access private members of a class. The difference is it allows access to &lt;strong&gt;specific&lt;/strong&gt; class or function and &lt;strong&gt;not all the classes in the same DLL&lt;/strong&gt;. In my opinion, this is a better solution than the C# internal keyword.&lt;/p&gt;

&lt;h2&gt;
  
  
  Further Reading
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://stackoverflow.com/questions/165719/practical-uses-for-the-internal-keyword-in-c-sharp" rel="noopener noreferrer"&gt;Practical uses for the "internal" keyword in C#&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;a href="https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword" rel="noopener noreferrer"&gt;Why does C# not provide the C++ style 'friend' keyword?&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>csharp</category>
      <category>codequality</category>
      <category>programming</category>
      <category>oop</category>
    </item>
    <item>
      <title>Write Clean Code Without Loops</title>
      <dc:creator>Shani Fedida</dc:creator>
      <pubDate>Sun, 30 Aug 2020 17:26:27 +0000</pubDate>
      <link>https://dev.to/shanif/write-clean-code-without-loops-26le</link>
      <guid>https://dev.to/shanif/write-clean-code-without-loops-26le</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F0%2AQ010nh59YRrvNBXp" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn-images-1.medium.com%2Fmax%2F1000%2F0%2AQ010nh59YRrvNBXp" width="800" height="640"&gt;&lt;/a&gt;&lt;/p&gt;

Loops are messy - Photo by 
&lt;a href="https://unsplash.com/@danielfazio" rel="noopener noreferrer"&gt;
Daniel Fazio
&lt;/a&gt; 
on
&lt;a href="https://unsplash.com" rel="noopener noreferrer"&gt;
Unsplash
&lt;/a&gt;




&lt;p&gt;A few years ago, I participated in a public workshop organized by Wix. We practiced TDD by implementing the &lt;a href="https://codingdojo.org/kata/GameOfLife/" rel="noopener noreferrer"&gt;Game Of Life kata&lt;/a&gt; with different constraints. One constraint was to &lt;strong&gt;write code without loops&lt;/strong&gt;. I was shocked and stuck, I could not grasp how it is possible. Eventually, I figured it out: &lt;strong&gt;map, filter, and reduce!&lt;/strong&gt; I knew this concept before but it wasn’t part of my daily programming (back then I wrote in C++). When I returned to C#, I started using this concept more and more and understood its benefits.&lt;/p&gt;

&lt;p&gt;In this post, I show how to write clean code by replacing foreach loops with map, filter, and reduce. &lt;strong&gt;This approach is relevant to all languages.&lt;/strong&gt; &lt;/p&gt;

&lt;h1&gt;
  
  
  TL;DR
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;  Declarative code written with map, filter, and reduce is more readable and concise than imperative code written with foreach loops.&lt;/li&gt;
&lt;li&gt;  Reduce boilerplate code and avoid stupid bugs.&lt;/li&gt;
&lt;li&gt;  Achieve clean code by separating between the logic of which items to operate on and the operation itself.&lt;/li&gt;
&lt;li&gt;  Code is better in terms of the Single Responsibility Principle&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  What Are Map, Filter &amp;amp; Reduce?
&lt;/h1&gt;

&lt;p&gt;Map, Filter and Reduce are functions that work on collections. They receive a collection and a function and return a new collection based on the result of the function.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  Map — maps each object in a collection into a new object. It returns a new collection with the same size as the given collection.&lt;/li&gt;
&lt;li&gt;  Filter — filters a collection according to a given condition. The new collection includes only the elements that pass the condition.&lt;/li&gt;
&lt;li&gt;  Reduce — reduces a collection down to a single value.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;iframe class="tweet-embed" id="tweet-741089564329054208-974" src="https://platform.twitter.com/embed/Tweet.html?id=741089564329054208"&gt;
&lt;/iframe&gt;

  // Detect dark theme
  var iframe = document.getElementById('tweet-741089564329054208-974');
  if (document.body.className.includes('dark-theme')) {
    iframe.src = "https://platform.twitter.com/embed/Tweet.html?id=741089564329054208&amp;amp;theme=dark"
  }



&lt;/p&gt;




&lt;p&gt;I wrote the code examples with &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/linq-to-objects" rel="noopener noreferrer"&gt;C# LINQ&lt;/a&gt; and simplified them for the post. In real-life systems the code is not clearly divided into functions, instead, most of the code is inside the loop.&lt;/p&gt;

&lt;h2&gt;
  
  
  Replace foreach with map
&lt;/h2&gt;

&lt;p&gt;Sometimes we see code with this structure:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now, let’s rewrite it using &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select?view=netcore-3.1#System_Linq_Enumerable_Select__2_System_Collections_Generic_IEnumerable___0__System_Func___0___1__" rel="noopener noreferrer"&gt;LINQ Select&lt;/a&gt; which is the LINQ version of map :&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;br&gt;
* I call &lt;code&gt;ToList()&lt;/code&gt; because &lt;a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/deferred-execution-and-lazy-evaluation-in-linq-to-xml" rel="noopener noreferrer"&gt;LINQ is lazy&lt;/a&gt;. 

&lt;p&gt;This code is shorter — a single line!&lt;/p&gt;
&lt;h2&gt;
  
  
  Replace if with filter
&lt;/h2&gt;

&lt;p&gt;Sometimes we see code with these structures:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;The loops contain two logics:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Which items to operate on.&lt;/li&gt;
&lt;li&gt; The operation itself.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;We can replace &lt;strong&gt;if&lt;/strong&gt; with &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where" rel="noopener noreferrer"&gt;&lt;strong&gt;LINQ Where&lt;/strong&gt;&lt;/a&gt;, which is the LINQ version of filter. When we replace &lt;code&gt;if (someCondition) continue;&lt;/code&gt; with &lt;code&gt;Where&lt;/code&gt; we write the negative form of the condition.&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;br&gt;
The two logics are now separated. Each logic has a single responsibility.
&lt;h2&gt;
  
  
  Replace Boilerplate Code with Any
&lt;/h2&gt;

&lt;p&gt;Sometimes we see code with these structures:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;These are patterns for “return true if &lt;strong&gt;at least one&lt;/strong&gt; of the items &lt;strong&gt;returns true&lt;/strong&gt; for a given condition” aka the &lt;strong&gt;Any function&lt;/strong&gt;. &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any" rel="noopener noreferrer"&gt;LINQ Any&lt;/a&gt; determines whether any element of a sequence exists or satisfies a condition. Any is a specific form of a reduce function.&lt;/p&gt;

&lt;p&gt;Even though we are used to writing these boilerplate patterns, there is always a chance to cause bugs by doing a wrong initialization or confusing between the AND operator and the OR operator.&lt;/p&gt;

&lt;p&gt;Let’s rewrite the code by using &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any" rel="noopener noreferrer"&gt;LINQ Any&lt;/a&gt;:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This code is clearer, shorter (single line!), and &lt;strong&gt;emphasizes the code’s meaning&lt;/strong&gt;. It is also more efficient, &lt;code&gt;Any&lt;/code&gt; stops as soon as the result can be determined.&lt;/p&gt;

&lt;h2&gt;
  
  
  Replace Boilerplate Code with All
&lt;/h2&gt;

&lt;p&gt;Sometimes we see code with these structures:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;These patterns mean “return true &lt;strong&gt;if &lt;em&gt;ALL&lt;/em&gt;&lt;/strong&gt; the items &lt;strong&gt;return true&lt;/strong&gt; for a given condition” aka the &lt;strong&gt;All function&lt;/strong&gt;. &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.all?view=netcore-3.1" rel="noopener noreferrer"&gt;LINQ All&lt;/a&gt; Determines whether all elements of a sequence satisfy a condition. All is a specific form of a reduce function.&lt;/p&gt;

&lt;p&gt;Similar to &lt;code&gt;Any&lt;/code&gt;, there is a chance to miswrite this boilerplate code and to cause bugs.&lt;/p&gt;

&lt;p&gt;Let’s rewrite the code by using &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.all" rel="noopener noreferrer"&gt;LINQ All&lt;/a&gt;.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;This code is clearer, shorter (single line!), and &lt;strong&gt;emphasizes the code’s meaning&lt;/strong&gt;.&lt;/p&gt;




&lt;h1&gt;
  
  
  Code Evolution
&lt;/h1&gt;

&lt;p&gt;In this section, I show how writing code with foreach loops can lead to spaghetti code while writing code with map, filter, and reduce results in clear, readable, and maintainable code.&lt;/p&gt;

&lt;p&gt;Let’s imagine we are building a fun system for organizing fun days. 💃 🎉 🍻&lt;br&gt;
Each employee should receive a welcome email for the fun day they registered to. Here is the code:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Now we discover that some people forgot to register. They were unaware of the fun days 😲. What should we do? Let’s send them a reminder email to register for a fun day.&lt;/p&gt;

&lt;p&gt;Sending a reminder also operates only on current employees. The current code already finds the fun day for each employee, so this functionality is quite simple to add.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Great! Now people will not miss out on the fun. 😃&lt;/p&gt;

&lt;p&gt;Now we discover that some people registered for a fun day but forgot to register for the optional activities. Let’s send them a reminder to register for the optional activities.&lt;/p&gt;

&lt;p&gt;The current code already finds the fun day for each employee, so let’s use it to add the new functionality.&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Yammi 😋 we got spaghetti…  code! 🤦‍♀&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5oyitymw2mkmiq78jgex.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F5oyitymw2mkmiq78jgex.jpeg" width="800" height="382"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;a href="https://www.freepik.com/vectors/computer" rel="noopener noreferrer"&gt;
Computer vector created by freepik — www.freepik.com
&lt;/a&gt;




&lt;h3&gt;
  
  
  The problems in the above code are:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;  Many logics mixed together aka violates the Single Responsibility Principle.&lt;/li&gt;
&lt;li&gt;  In each row, &lt;code&gt;employee&lt;/code&gt; passed different filters so it is hard to grasp which filters it passed.&lt;/li&gt;
&lt;li&gt;  Quite nested code (4 nesting levels)&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  Let’s Try Again — Rewrite 💣💣💣
&lt;/h2&gt;

&lt;p&gt;Now we start from scratch, writing the code with LINQ.&lt;/p&gt;

&lt;p&gt;Let’s rewrite the first feature —  welcome email.&lt;/p&gt;

&lt;p&gt;The original code:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;
&lt;br&gt;
Rewrite with LINQ:&lt;br&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  What are the differences?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;In both implementations &lt;code&gt;SendWelcomeEmail&lt;/code&gt; operates only on employes who are registered for a fun day. In the LINQ implementation, &lt;strong&gt;I separated the logic of whom to operates and the operation itself.&lt;/strong&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;I separated the filtering of current employees from the employes' loop. The filtering is done in a separate function called &lt;code&gt;GetCurrentEmployees&lt;/code&gt; which emphasizes the code's meaning. I replaced &lt;code&gt;if (IsPastEmployee(employee)) continue;&lt;/code&gt; and &lt;code&gt;if (IsFutureEmployee(employee)) continue;&lt;/code&gt; with &lt;code&gt;Where&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Instead of searching the fun day inside the employes' loop, I created a dictionary between an employee and a fun day called &lt;code&gt;employee2Funday&lt;/code&gt;. I replaced &lt;code&gt;if (funday.IsEmployeeRegistered(employee.Id))&lt;/code&gt; with &lt;code&gt;employee2Funday.Where&lt;/code&gt;.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;We assume that an employee is registered to a single fun day. The original code implicitly chooses the first fun day by using the &lt;code&gt;break&lt;/code&gt; statement. The new implementation uses LINQ &lt;code&gt;FirstOrDefault&lt;/code&gt; which is more explicit. &lt;code&gt;FirstOrDefault&lt;/code&gt; is a specific form of a reduce function.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Now let's implement the next feature — a reminder email to register for a fun day for employees who didn’t register for any fun day.&lt;/p&gt;

&lt;p&gt;The original code:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Rewrite with LINQ:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  What are the differences?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;I separated the logic of whom to operates and the operation itself. The function &lt;code&gt;SendUnregisteredToFunday&lt;/code&gt; operates only on employes who are unregistered for any fun day.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the original code, &lt;strong&gt;the two functionalities are tangled together&lt;/strong&gt;. In the rewritten code &lt;strong&gt;each functionality has its own method&lt;/strong&gt;. This is possible because the data this functionality operates on, aka the employees and whether they are registered to a fun day, exists outside of the first functionality implementation.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Now let's implement the last feature — a reminder email for registering to the optional activities.&lt;/p&gt;

&lt;p&gt;The original code:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;p&gt;Rewrite with LINQ:&lt;br&gt;
&lt;/p&gt;
&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;


&lt;h3&gt;
  
  
  What are the differences?
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Again, I separated between the logic of whom to operates and the operation itself. The function &lt;code&gt;SendEmailAboutOptionalActivities&lt;/code&gt; operates only on employees who are registered for a fun day but unregistered to any optional activity.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;In the original code, &lt;strong&gt;the functionalities are tangled together&lt;/strong&gt;. In the rewritten code &lt;strong&gt;each functionality has its own method&lt;/strong&gt;. This is possible because the data this functionality operates on, aka the employees and whether they are registered to a fun day, exists outside of the other functionalities implementation.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;IsUnregisteredToOptionalActivities&lt;/code&gt; is implemented with &lt;code&gt;Where&lt;/code&gt; and &lt;code&gt;Any&lt;/code&gt; instead of boilerplate code. It is shorter and clearer.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;This paradigm is part of the &lt;strong&gt;functional programming paradigm&lt;/strong&gt; which has some concepts that help write clean, readable, and less error-prone code. Some of these concepts are immutable classes, avoid variables reassignment, and avoid shared state.&lt;/p&gt;

&lt;p&gt;I currently write code in &lt;a href="https://www.youtube.com/watch?v=GeG9VPmUa28" rel="noopener noreferrer"&gt;Scala&lt;/a&gt; and I barely see foreach loops. Out of curiosity, I gathered some statistics from the codebase I work on: map has ~3500 occurrences, filter has ~3000 occurrences, and foreach has only ~500 occurrences.&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>programming</category>
      <category>functional</category>
      <category>codequality</category>
    </item>
    <item>
      <title>Why I Love TDD</title>
      <dc:creator>Shani Fedida</dc:creator>
      <pubDate>Fri, 22 May 2020 19:02:02 +0000</pubDate>
      <link>https://dev.to/shanif/why-i-love-tdd-4d6</link>
      <guid>https://dev.to/shanif/why-i-love-tdd-4d6</guid>
      <description>&lt;p&gt;In this post, I show the &lt;strong&gt;day to day differences&lt;/strong&gt; between TDD (Test Driven Development) and development without tests or write tests after the feature is complete (TLD) .&lt;/p&gt;

&lt;h2&gt;
  
  
  TL;DR
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;TDD takes &lt;strong&gt;less time&lt;/strong&gt; than non-TDD approaches because it reduces manual testing,  which takes a lot of time.&lt;/li&gt;
&lt;li&gt;Tests are a &lt;strong&gt;safety net&lt;/strong&gt;. In TDD, we have a &lt;strong&gt;safety net while coding&lt;/strong&gt;, not only after we finish the development.&lt;/li&gt;
&lt;li&gt;TDD is a methodology that helps developers to &lt;strong&gt;focus&lt;/strong&gt; and work in baby  steps,  those &lt;strong&gt;reducing the cognitive load.&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;TDD encourages &lt;strong&gt;clean code&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Life is easier&lt;/strong&gt; with TDD because we start with a small amount of code, which slowly grows.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  Non-TDD Approaches
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Development Without Tests
&lt;/h3&gt;

&lt;p&gt;In this approach, we repeatedly:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Choose scenarios for testing.&lt;/li&gt;
&lt;li&gt; Write code for those scenarios.&lt;/li&gt;
&lt;li&gt; Test from outside and manually examine that the scenario works correctly by, for example, viewing the data in the UI, looking at the results of API calls, and performing DB queries.&lt;/li&gt;
&lt;li&gt; Fix the code until the scenario works as planned.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;When do we check previous scenarios still work? I guess each developer checks at a different time: when finish to develop the feature, after each scenario, and even by the number of code changes.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tests Last Development
&lt;/h3&gt;

&lt;p&gt;This approach is similar to development without tests except that we write tests after we developed the feature in order to validate the feature works correctly.&lt;/p&gt;




&lt;h2&gt;
  
  
  TDD 101
&lt;/h2&gt;

&lt;p&gt;The overall idea is to write code incrementally. We write code for a specific scenario while &lt;strong&gt;always validating that other scenarios still work&lt;/strong&gt;. Also, we care about clean code, but at a separate stage.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbxq3gjn3davu0e84tlxg.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2Fbxq3gjn3davu0e84tlxg.png" alt="Alt Text" width="407" height="401"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For each scenario, we:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt; Write a test that represents one scenario. We run the test, and it fails* because we didn’t write any code for it to pass(Compilation errors count as failures)&lt;/li&gt;
&lt;li&gt; Write the minimal code for the test to pass.&lt;/li&gt;
&lt;li&gt; Refactor the code.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;*If the test doesn’t fail, it usually means that we wrote more than the minimal code at a previous iteration, or that the test is equivalent to an existing one.&lt;/p&gt;




&lt;h2&gt;
  
  
  TDD vs. Non-TDD Approaches
&lt;/h2&gt;

&lt;h3&gt;
  
  
  Tests Duration
&lt;/h3&gt;

&lt;p&gt;In non-TDD approaches, we test our code &lt;strong&gt;manually&lt;/strong&gt; by reproducing the same flow over and over again. Reproduction of the flow can include: application loading, login, get to the relevant screen and press a button. &lt;strong&gt;The feedback is slow&lt;/strong&gt; and requires us to remember a sequence of actions.&lt;/p&gt;

&lt;p&gt;In TDD, we run all the tests  with a &lt;strong&gt;press of a button&lt;/strong&gt;. A unit test usually takes a few milliseconds; an integration test usually takes a few seconds.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;TDD takes less time than writing tests in the end&lt;/strong&gt; because the outcome is the same, but while coding, we still need to test somehow, so we perform manual testing. I believe that TDD also &lt;strong&gt;takes less time than develop without tests&lt;/strong&gt; because the manual tests take more time than write tests.&lt;/p&gt;

&lt;p&gt;TDD gives us a &lt;strong&gt;simpler and faster&lt;/strong&gt; way to test our code.&lt;/p&gt;

&lt;h3&gt;
  
  
  Tests Are a Safety Net
&lt;/h3&gt;

&lt;p&gt;We tested a few scenarios, and we are now implementing the next one. We changed the code, so we &lt;strong&gt;should retest the existing scenarios&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;In the Non-TDD approach, we test manually. Manually testing takes time, and it’s a repetitive and precise task — not something we humans excel at. In the best case, we documented the scenarios; in the worst case, they are inside our head. &lt;strong&gt;What are the chances we really retest all scenarios?&lt;/strong&gt; Even if we documented the scenarios, do we really retest them all? Or do we skip some because the process is long and repetitive? (I would even say boring).&lt;/p&gt;

&lt;p&gt;In TDD, with a press of a button, we &lt;strong&gt;test all existing scenarios&lt;/strong&gt; after each code change.&lt;/p&gt;

&lt;h3&gt;
  
  
  Focus — Less Context Switch
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F9f7nb1viu0ppgwl951wc.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F9f7nb1viu0ppgwl951wc.jpeg" alt="Alt Text" width="800" height="340"&gt;&lt;/a&gt;&lt;/p&gt;
Focus VS Cognitive Overload



&lt;p&gt;TDD is a methodology that defines a work order. Each task has its time: write a test, write production code, and refactor.&lt;/p&gt;

&lt;p&gt;In non-TDD approaches, everyone has their methodology, even if they are not aware of it.&lt;/p&gt;

&lt;p&gt;Focusing on a specific scenario and the three stages create a process of small and defined steps — Baby steps 👶. This kind of process creates focus and lowers the cognitive load.&lt;/p&gt;

&lt;p&gt;I noticed that for me:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;  The refactor part helps me to avoid refactoring while coding. More than once, I started to refactor while writing code and ended with messy and broken code. I had to discard the code. 😢&lt;/li&gt;
&lt;li&gt;  Focusing on a specific scenario helps me ignore other scenarios while implementing it, which reduces my cognitive load.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Clean Code
&lt;/h3&gt;

&lt;p&gt;In non-TDD approaches, every developer decides when to refactor. From my experience, we postpone the refactor to the end of the feature. The problem is that at some point soon, we &lt;strong&gt;suffer from the mess we made during the development.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;In TDD, there is a dedicated time for refactoring. Because it is at the end of each cycle, we work with &lt;strong&gt;more maintainable code while developing&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;There is a better chance that working in TDD will produce a &lt;strong&gt;cleaner code&lt;/strong&gt; than the non-TDD approaches, but &lt;strong&gt;it depends a lot on the developer&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  In TDD the Code Is Written Slower
&lt;/h3&gt;

&lt;p&gt;I know it sounds like a disadvantage, but…&lt;/p&gt;

&lt;p&gt;In TDD, we start with a small amount of code, which slowly grows. &lt;strong&gt;At every stage in the development, we have less code:&lt;/strong&gt; less code to read, less code to debug, less code to navigate through =&amp;gt;&lt;strong&gt;Life is easier.&lt;/strong&gt; 😌&lt;/p&gt;




&lt;p&gt;I hope I convinced you to try TDD. You are welcome to &lt;a href="https://twitter.com/fedidashani" rel="noopener noreferrer"&gt;contact me&lt;/a&gt;, and I will be happy to help you adopt it.&lt;/p&gt;

</description>
      <category>tdd</category>
      <category>productivity</category>
      <category>codequality</category>
      <category>development</category>
    </item>
  </channel>
</rss>
