<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="https://angrynerds.co/blog/rss/xslt"?>
<rss xmlns:a10="http://www.w3.org/2005/Atom" version="2.0">
  <channel>
    <title>Blog</title>
    <link>https://angrynerds.co/blog</link>
    <description />
    <generator>Articulate, blogging built on Umbraco</generator>
    <item>
      <guid isPermaLink="false">3620</guid>
      <link>https://angrynerds.co/blog/chain-of-responsibility-design-pattern-with-examples/</link>
      <category>Development</category>
      <title>Chain of Responsibility design pattern – with examples</title>
      <description>&lt;p&gt;Design patterns can be divided into three groups: &lt;strong&gt;creational, structural, and behavioral.&lt;/strong&gt; Chain of Responsibility belongs to the behavioral one – which is a group of design patterns that help with better interaction between objects in your code. &lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;&lt;b&gt;TIP:&lt;/b&gt; There is a classic book discussing this topic and describing 23
design patterns - &amp;quot;Design Patterns: Elements of Reusable
Object-Oriented Software&amp;quot;. You should definitely read it if you are
not familiar with the matter.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;div align="center"&gt;
&lt;img alt="design patterns" src="https://i.pinimg.com/736x/26/8a/61/268a61596644fced06fd40f75f09e450.jpg"&gt;&lt;/div&gt;&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;h3&gt;Let's learn more about the Chain of Responsibility with some practical examples&lt;/h3&gt;
&lt;p&gt;The Chain of Responsibility pattern is used to replace statements like &lt;em&gt;if ... else if ... else&lt;/em&gt; with more object-oriented form. Let's consider calculating a tax amount that is different for each country. The first version of the method handling this calculation could look like this:&lt;/p&gt;
&lt;p&gt;&lt;script src="https://gist.github.com/angrynerds-marcin/5a7ae52dccd9469086dd3e0a7e2d5f6e.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;It does not look that complicated, but the code can easily become longer and more laborious with time. In the next version, the tax may be calculated differently for various types of products, we may also have more countries that we want to calculate tax for. Moreover, at some point in the future, the law may be changed and that will result in different formulas based on date. This is a perfect example to use the Chain of Responsibility pattern. Take a look at the tax calculation problem implemented with this pattern:&lt;/p&gt;
&lt;p&gt;&lt;script src="https://gist.github.com/angrynerds-marcin/786b79f41fe3db7433f96ffb17cc342e.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;In this version, we don't have five &lt;em&gt;if&lt;/em&gt; statements in one method and each type of tax is calculated by its own class. That way our code follows the Single Responsibility Principle, which is &lt;strong&gt;one of the most important rules in clean coding&lt;/strong&gt;. To use these new classes, we have to create an instance of each class and set value for &lt;code&gt;Next&lt;/code&gt; property. See an example here:&lt;/p&gt;
&lt;p&gt;&lt;script src="https://gist.github.com/angrynerds-marcin/404309e81f5e68a14aa48d7f35f339fd.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;If you had trouble with understanding how it works, I recommend you set a breakpoint and use a debugger to check which instructions are executed.
​&lt;br /&gt;&lt;br /&gt;
Here is another example – an algorithm that recommends you the next video to watch based on your age. This is a really simple example because it always returns the same video, but it fits nicely into the Chain of Responsibility pattern.&lt;/p&gt;
&lt;p&gt;&lt;script src="https://gist.github.com/angrynerds-marcin/3dd10dda361c43b576a6980d3654556b.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;And the third example – it's the code for an ATM that checks if it can dispense cash using a finite number of notes inside the machine. In this case, we will have just one implementation of an abstract class, but we will define a chain consisting of three links using that one class.&lt;/p&gt;
&lt;p&gt;&lt;script src="https://gist.github.com/angrynerds-marcin/9e3571ba29bf891d7d13ae4846fa05ec.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;Here is how we can use it:&lt;/p&gt;
&lt;p&gt;&lt;script src="https://gist.github.com/angrynerds-marcin/d3943e64c22ba097da86c04de8858585.js"&gt;&lt;/script&gt;&lt;/p&gt;
&lt;p&gt;​
By now, I think you have already grasped the concept of the Chain of Responsibility pattern. Here is a class diagram and a sequence diagram that presents it:&lt;/p&gt;
&lt;div style="display: block; width: 700px; margin: 0 auto;"&gt;
&lt;img src="https://angrynerds.co/media/2082/w3sdesign_chain_of_responsibility_design_pattern_uml.jpg"&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;div align="center"&gt;
&lt;i&gt;Photo via &lt;a href="https://upload.wikimedia.org/wikipedia/commons/6/6a/W3sDesign_Chain_of_Responsibility_Design_Pattern_UML.jpg" target="_blank" rel="nofollow"&gt;Wikimedia Commons&lt;/a&gt;&lt;/i&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;
​&lt;/p&gt;
&lt;h3&gt;Chain of Responsibility vs other patterns&lt;/h3&gt;
&lt;h4&gt;Chain of Responsibility vs Decorator&lt;/h4&gt;
&lt;p&gt;The Chain of Responsibility design pattern may appear similar to the Decorator design pattern but the key difference is that the former can be stopped at any part of the processing, and the latter executes all steps (assuming that passed data was valid and it didn't throw an exception). Decorator adds something with each step.
​&lt;/p&gt;
&lt;h4&gt;Chain of Responsibility vs Strategy&lt;/h4&gt;
&lt;p&gt;With the Chain of Responsibility pattern, each object is responsible for executing an action on the next object, whereas, with the Strategy pattern, the client of that code has to decide which implementation should be used.
​&lt;/p&gt;
&lt;h3&gt;What next?&lt;/h3&gt;
&lt;p&gt;I strongly recommend you to read the book mentioned in the intro: &lt;em&gt;Design Patterns: Elements of Reusable Object-Oriented Software&lt;/em&gt;. You can also watch a &lt;a href="https://www.pluralsight.com/paths/design-patterns-in-c"&gt;series of courses on Pluralsight&lt;/a&gt; in the design patterns path. There is also a fun experiment that you can check out on GitHub: &lt;a href="https://github.com/EnterpriseQualityCoding/FizzBuzzEnterpriseEdition"&gt;FizzBuzz Enterprise Edition&lt;/a&gt; is a no-nonsense implementation of FizzBuzz made by serious businessmen for serious business purposes.&lt;/p&gt;
&lt;h3&gt;Feel free to share your thoughts or questions in the comments!&lt;/h3&gt;
&lt;h4&gt;You may be also interested in:&lt;/h4&gt;
&lt;p&gt;➤ &lt;a href="/blog/11-extremely-useful-git-commands-every-developer-should-know/" target="_blank"&gt;11 extremely useful Git commands every developer should know&lt;/a&gt;&lt;br /&gt;
➤ &lt;a href="/blog/avoiding-anemic-domain-model/" target="_blank"&gt;Avoiding Anemic Domain Model&lt;/a&gt;&lt;br /&gt;
➤ &lt;a href="/blog/master-your-git-log-with-conventional-commits-in-6-steps/" target="_blank"&gt;Master your git log with Conventional Commits in 6 steps&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;&lt;br /&gt; &lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;strong&gt;About the Author&lt;/strong&gt;&lt;br /&gt; 
&lt;a href="https://www.linkedin.com/in/marcin-zarebski/" target="_blank"&gt;Marcin Zarębski&lt;/a&gt; is an experienced back-end developer, specializing in. .NET platform. He has amazing skills in building complex backend solutions and infrastructure. Marcin is also interested in space exploration and the role of computer science in it. He likes to spend his free time in the mountains or playing board games. &lt;/p&gt;
</description>
      <pubDate>Mon, 31 Aug 2020 10:04:59 Z</pubDate>
      <a10:updated>2020-08-31T10:04:59Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">3567</guid>
      <link>https://angrynerds.co/blog/avoiding-anemic-domain-model/</link>
      <category>Development</category>
      <title>Avoiding Anemic Domain Model</title>
      <description>&lt;p&gt;&lt;strong&gt;Anemic Domain Model&lt;/strong&gt; is a software pattern where classes representing domain objects contain only data and little or no logic in methods. Does it sound familiar? Maybe it is a consequence of using one of the most popular ways of organizing application logic into layers.
&lt;br&gt;&lt;/p&gt;
&lt;div align="center"&gt;
&lt;img src="https://angrynerds.co/media/2051/layers.png"&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;
You see the data layer and it may be quite natural to think of this as a table in a relational database. It is true that the objects from the data layer will be often used to preserve some data in a relational database but additional work is required to send data from those objects. The bottom line is that objects are not tables. 
&lt;br&gt;&lt;/p&gt;
&lt;div align="center"&gt;
&lt;img src="https://angrynerds.co/media/2052/meme.png"&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br&gt;
Using Anemic Domain Models is a direct violation of one of the core concepts in object-oriented programming. Having Anemic Domain Models leads to code duplication and a lack of encapsulation. Check out &lt;a href="https://martinfowler.com/bliki/AnemicDomainModel.html"&gt;this excellent blog post&lt;/a&gt; by Martin Fowler. Let's see some examples. &lt;/p&gt;
&lt;p&gt;&lt;em&gt;All examples in this post are in C#.&lt;/em&gt;&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Company
{
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal ShareCapital { get; set; }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;
&lt;code&gt;Company&lt;/code&gt; class is used by a service layer to create/update new companies, and that service is injected in some API controller. &lt;code&gt;CompanyService&lt;/code&gt; class contains the necessary logic - here is a draft of that service. Let's omit the controller class as it is straightforward.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class CompanyService
{
    public void Create(CreateCompanyModel model)
    {
        if (!string.IsNullOrWhiteSpace(model.Name))
        {
            throw new Exception(&amp;quot;name is required&amp;quot;);
        }

        Company company = new Company
        {
            Id = ... //generate Id
            CreatedAt = DateTime.UtcNow,
            Name = model.Name
        };

        // save company in database
    }

    public void Update(UpdateCompanyModel model)
    {
        // validate model if necessary

        Company company = ... // get company from database
        company.Description = model.Description;
        company.ShareCapital = model.ShareCapital;

        // update company in database
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;
Potentially, there could be a couple of scenarios where new companies will be created or updated. Maybe we want to create a Business Corporation by following a different path than the path for General Partnership or a Limited Liability Company. This is something that will be defined by business needs. &lt;/p&gt;
&lt;p&gt;Right now, there is nothing in the &lt;code&gt;Company&lt;/code&gt; class that helps you understand what are the required properties and what are the optional properties. There are no validation rules included. Probably the &lt;code&gt;Name&lt;/code&gt; and &lt;code&gt;CreatedAt&lt;/code&gt; should be required - and it may be obvious to someone but when you have a model with 20 properties it may be harder to choose a subset of required properties. &lt;/p&gt;
&lt;p&gt;Moreover, sometimes properties' values could be automatically deduced when a new instance is created, e.g. &lt;code&gt;CreatedAt&lt;/code&gt; seems like something that could be set behind the scenes. If only we defined a constructor, we would make creating a company easier. We could replace the above code with:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Company
{
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public decimal ShareCapital { get; set; }

    public Company(string name)
    {
        if (!string.IsNullOrWhiteSpace(name))
        {
            throw new Exception(&amp;quot;name is required&amp;quot;);
        }

        Id = ... //generate Id
        Name = name;
        CreatedAt = DateTime.UtcNow;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;
Now our client can't create a new company using default constructor without &lt;code&gt;Name&lt;/code&gt; or &lt;code&gt;CreatedAt&lt;/code&gt; values. This is good because it is a business rule that we want to enforce in our domain. However, he can still update &lt;code&gt;Name&lt;/code&gt; or &lt;code&gt;CreatedAt&lt;/code&gt; date. Does it make sense? As always, it depends. Let's assume that business rule is that we should change neither &lt;code&gt;CreatedAt&lt;/code&gt; nor &lt;code&gt;Name&lt;/code&gt; values. To do that, we will replace public setters with private setters in &lt;code&gt;Company&lt;/code&gt; class.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Company
{
    public int Id { get; private set; }
    public DateTime CreatedAt { get;  private set; }
    public string Name { get;  private set; }
    public string Description { get;  private set; }
    public decimal ShareCapital { get; private set; }

    public Company(string name)
    {
        if (!string.IsNullOrWhiteSpace(name))
        {
            throw new Exception(&amp;quot;name is required&amp;quot;);
        }

        Id = ... //generate Id
        Name = name;
        CreatedAt = DateTime.UtcNow;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;
A new problem arose that has to be addressed. In this version, we cannot set value for optional properties &lt;code&gt;Description&lt;/code&gt; and &lt;code&gt;ShareCapital&lt;/code&gt;. To fix that, we will add new methods: &lt;code&gt;UpdateDescription&lt;/code&gt;, &lt;code&gt;UpdateShareCapital&lt;/code&gt;. The idea is that for specific scenarios we want to have separate methods that will act accordingly. In more complex scenarios such a method would do more than setting value for one property, e.g. set more values, like the last update date.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Company
{
    public int Id { get; private set; }
    public DateTime CreatedAt { get; private set; }
    public string Name { get; private set; }
    public string Description { get; private set; }
    public decimal ShareCapital { get; private set; }

    public Company(string name)
    {
        if (!string.IsNullOrWhiteSpace(name))
        {
            throw new Exception(&amp;quot;name is required&amp;quot;);
        }

        Id = ... //generate Id
        Name = name;
        CreatedAt = DateTime.UtcNow;
    }

    public void UpdateDescription(string description)
    {
        Description = description;
    }

    public void UpdateShareCapital(decimal shareCapital)
    {
        ShareCapital = shareCapital;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;
Another advantage of this approach is discoverability - i.e. when you look at the object, you discover what you can do with that object. With an Anemic Domain Model, this is harder and potentially more confusing.&lt;/p&gt;
&lt;h3&gt;Value objects&lt;/h3&gt;
&lt;p&gt;We will define the concept of value objects that are useful building blocks in creating rich domain models. Eric Evans defines value objects this way: &lt;/p&gt;
&lt;blockquote&gt;
&lt;p&gt;An object that represents a descriptive aspect of the domain with no
conceptual identity is called a VALUE OBJECT. VALUE OBJECTS are
instantiated to represent elements of the design that we care about
only for what they are, not who or which they are.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;&lt;em&gt;[Excerpt from &amp;quot;Domain-Driven Design: Tackling Complexity in the Heart of Software&amp;quot;, p. 59]&lt;/em&gt;&lt;/p&gt;
&lt;p&gt;Examples of value objects are numbers, strings, money, addresses, colors, etc. When you think about it, there is quite a natural distinction between entities and value objects. For example, if you have a product that costs $100, it doesn't matter which $100 it is. When you design a value object, you have to make them immutable. Fulfilling the immutability requirement can be a little tedious. We will use value object implementation proposed by msdn (check &lt;a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/implement-value-objects"&gt;here&lt;/a&gt;).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public abstract class ValueObject
{
    protected static bool EqualOperator(ValueObject left, ValueObject right)
    {
        if (ReferenceEquals(left, null) ^ ReferenceEquals(right, null))
        {
            return false;
        }
        return ReferenceEquals(left, null) || left.Equals(right);
    }

    protected static bool NotEqualOperator(ValueObject left, ValueObject right)
    {
        return !(EqualOperator(left, right));
    }

    protected abstract IEnumerable&amp;lt;object&amp;gt; GetAtomicValues();

    public override bool Equals(object obj)
    {
        if (obj == null || obj.GetType() != GetType())
        {
            return false;
        }

        ValueObject other = (ValueObject)obj;
        IEnumerator&amp;lt;object&amp;gt; thisValues = GetAtomicValues().GetEnumerator();
        IEnumerator&amp;lt;object&amp;gt; otherValues = other.GetAtomicValues().GetEnumerator();
        while (thisValues.MoveNext() &amp;amp;&amp;amp; otherValues.MoveNext())
        {
            if (ReferenceEquals(thisValues.Current, null) ^
                ReferenceEquals(otherValues.Current, null))
            {
                return false;
            }

            if (thisValues.Current != null &amp;amp;&amp;amp;
                !thisValues.Current.Equals(otherValues.Current))
            {
                return false;
            }
        }
        return !thisValues.MoveNext() &amp;amp;&amp;amp; !otherValues.MoveNext();
    }

    public override int GetHashCode()
    {
        return GetAtomicValues()
         .Select(x =&amp;gt; x != null ? x.GetHashCode() : 0)
         .Aggregate((x, y) =&amp;gt; x ^ y);
    }
    // Other utility methods
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;
We can inherit from &lt;code&gt;ValueObject&lt;/code&gt; class to define &lt;code&gt;Money&lt;/code&gt; value object.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Money : ValueObject
{
    public string Currency { get; private set; }
    public decimal Value { get; private set; }

    private Money() { }

    public Money(string currency, string value)
    {
        Currency = currency;
        Value = value;
    }

    protected override IEnumerable&amp;lt;object&amp;gt; GetAtomicValues()
    {
        yield return Currency;
        yield return Value;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;
A word of caution must be mentioned here. Initially, you may be tempted to use struct as a value object. Even though it may seem like a good idea, it has major disadvantages. Read &lt;a href="https://enterprisecraftsmanship.com/posts/net-value-type-ddd-value-object/"&gt;this blog post&lt;/a&gt; to learn why. We can use &lt;code&gt;Money&lt;/code&gt; class in &lt;code&gt;ShareCapital&lt;/code&gt; property of &lt;code&gt;Company&lt;/code&gt; class. With that change, we completed transforming an anemic model into a rich model. This is a new version of &lt;code&gt;Company&lt;/code&gt; class:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class Company
{
    public int Id { get; private set; }
    public DateTime CreatedAt { get; private set; }
    public string Name { get; private set; }
    public string Description { get; private set; }
    public Money ShareCapital { get; private set; }

    public Company(string name)
    {
        if (!string.IsNullOrWhiteSpace(name))
        {
            throw new Exception(&amp;quot;name is required&amp;quot;);
        }

        Id = ... //generate Id
        Name = name;
        CreatedAt = DateTime.UtcNow;
    }

    public void UpdateDescription(string description)
    {
        Description = description;
    }

    public void UpdateShareCapital(Money shareCapital)
    {
        ShareCapital = shareCapital;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;
We could benefit from using value objects instead of primitive types. The code will be well-organized and understandable, and it will help us avoid code duplication. There is even a term for the situation when your domain code relies heavily on primitive types - we call it a primitive obsession.&lt;/p&gt;
&lt;h3&gt;Refactor CompanyService&lt;/h3&gt;
&lt;p&gt;We can simplify &lt;code&gt;CompanyService&lt;/code&gt; by using a new version of &lt;code&gt;Company&lt;/code&gt; class and by removing company logic that is encapsulated inside &lt;code&gt;Company&lt;/code&gt; class. Here is the result of that change:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public class CompanyService
{
    public void Create(CreateCompanyModel model)
    {
        Company company = new Company(model.Name);

        // save company in database
    }

    public void UpdateDescription(string description, int companyId)
    {
        Company company = ...// get company from database
        company.UpdateDescription(description);

        // update company in database
    }

    public void UpdateShareCapital(Money money, int companyId)
    {
        Company company = ...// get company from database
        company.UpdateShareCapital(money);

        // update company in database
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;br&gt;
This code is much cleaner than the original version, and more object-oriented. It is also more expressive.&lt;/p&gt;
&lt;h3&gt;Potential problems&lt;/h3&gt;
&lt;p&gt;▶ When you develop a small application, transforming it into rich models may not be worth it. &lt;br&gt;&lt;br&gt;
▶ Additional work has to be done to make it work with popular ORM frameworks, e.g. NHibernate or Entity Framework. It is possible but it is not out of the box support. &lt;br&gt;&lt;br&gt;
▶ The setup of your tests may become more complex. It can also be a good thing because your tests are closer to real-world scenarios. When you create your domain models in test, then you are forced to comply with all business rules that are implemented in your application. &lt;/p&gt;
&lt;p&gt;In general, I believe it is worth going the extra mile if you know that a project will be developed in a longer perspective.&lt;/p&gt;
&lt;h3&gt;Where to go next?&lt;/h3&gt;
&lt;p&gt;I highly recommend you a Pluralsight course &lt;i&gt;&lt;a href="https://www.pluralsight.com/courses/refactoring-anemic-domain-model"&gt;Refactoring from Anemic Domain Model Towards a Rich One&lt;/i&gt; by Vladimir Khorikov&lt;/a&gt;. You should also read &lt;a href="http://www.kamilgrzybek.com/"&gt;Kamil Grzybek's blog&lt;/a&gt;, especially posts related to Domain-Driven Design. If you want to learn more about Domain-Driven Design, you can start by reading the book &lt;em&gt;Implementing Domain-driven Design&lt;/em&gt; by Vaughn Vernon. &lt;/p&gt;
&lt;h4&gt;If you have any questions, feel free to leave us a comment!&lt;/h4&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;strong&gt;About the Author&lt;/strong&gt;&lt;br /&gt; 
&lt;a href="https://www.linkedin.com/in/marcin-zarebski/" target="_blank"&gt;Marcin Zarębski&lt;/a&gt; is an experienced back-end developer, specializing in. .NET platform. He has amazing skills in building complex backend solutions and infrastructure. Marcin is also interested in space exploration and the role of computer science in it. He likes to spend his free time in the mountains or playing board games. &lt;/p&gt;
</description>
      <pubDate>Thu, 18 Jun 2020 10:16:11 Z</pubDate>
      <a10:updated>2020-06-18T10:16:11Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">3222</guid>
      <link>https://angrynerds.co/blog/11-extremely-useful-git-commands-every-developer-should-know/</link>
      <category>Development</category>
      <title>11 extremely useful Git commands every developer should know</title>
      <description>&lt;blockquote&gt;
&lt;p&gt;Git is a free and open-source distributed version control system designed to handle everything from small to very large projects with speed and efficiency.&lt;/p&gt;
&lt;/blockquote&gt;
&lt;p&gt;To take advantage of this speed and efficiency you should learn some useful commands. In this blogpost, I'd like to share with you some of the most interesting Git commands - and my personal favorites. Let's explore them!&lt;/p&gt;
&lt;div style="display: block; width: 500px; margin: 0 auto;"&gt;
&lt;img src="https://angrynerds.co/media/1774/fire.png"&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;h4&gt;1. git stash -u&lt;/h4&gt;
&lt;p&gt;You may have used git stash command (this command takes modified files in your working directory and saves them in a separate place) and you may have been annoyed that the new files were not stashed. By using -u option you can move your new files to the stash.&lt;/p&gt;
&lt;h4&gt;2. git filter-branch --force --index-filter \&lt;br&gt; 'git rm --cached --ignore-unmatch Filename' \&lt;br&gt; --prune-empty --tag-name-filter cat -- --all&lt;/h4&gt;
&lt;p&gt;Have you ever discovered that there's a big unnecessary file in your repository? You could just remove it from your local directory and push that change to the remote. However, there is one problem with this approach: the file still exists in the repository history. Good news - it's possible to remove such file permanently! See &lt;a href="https://help.github.com/en/github/authenticating-to-github/removing-sensitive-data-from-a-repository" target="_blank"&gt;here&lt;/a&gt; for details.&lt;/p&gt;
&lt;h4&gt;3. git add --renormalize&lt;/h4&gt;
&lt;p&gt;Have you ever heard of the wall of pink? It is a situation when someone commited a small change to your repository, but all the files in this change have all the lines changed. In GUI tool, you may see all the lines pink (removed) and right below all the lines green (added). But how did it happen? The answer to this problem may be different line endings (CR LF vs LF). Read more about it &lt;a href="https://www.hanselman.com/blog/YoureJustAnotherCarriageReturnLineFeedInTheWall.aspx" target="_blank"&gt;here&lt;/a&gt; and &lt;a href="https://www.hanselman.com/blog/CarriageReturnsAndLineFeedsWillUltimatelyBiteYouSomeGitTips.aspx" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;&lt;img src="https://angrynerds.co/media/1779/1.jpg" /&gt;&lt;/p&gt;
&lt;h4&gt;4. git log --graph --decorate --abbrev-commit --all --format=format:&amp;quot;%C(magenta)%h%n%C(green)%t%n%C(yellow)%an%n%C(red)%ae%n%C(blue)%ad%n%C(cyan)%s&amp;quot;&lt;/h4&gt;
&lt;p&gt;Did you know that you can customize git log appearance? Read more about possible formatting options &lt;a href="https://git-scm.com/docs/pretty-formats" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;h4&gt;5. git shortlog -s -n --all --no-merges&lt;/h4&gt;
&lt;p&gt;This command will show how many commits you and your teammates pushed to the repository.&lt;/p&gt;
&lt;h4&gt;6. git push --force-with-lease&lt;/h4&gt;
&lt;p&gt;More polite version of git push --force. Remote branch won't be overwritten if someone pushed some changes to it.&lt;/p&gt;
&lt;p&gt;&lt;img src="https://angrynerds.co/media/1777/2.jpg" /&gt;&lt;/p&gt;
&lt;h4&gt;7. git branch --merged | egrep -v &amp;quot;(^\*|master|dev)&amp;quot; | xargs git branch -d&lt;/h4&gt;
&lt;p&gt;Delete branches that were merged to current branch, except for branches excluded in the filter (master and dev in this example).&lt;/p&gt;
&lt;h4&gt;8. git reflog&lt;/h4&gt;
&lt;p&gt;Using this command, you can find a log of what you did in the repository. You can use it for example to restore a commit from a branch that was deleted.&lt;/p&gt;
&lt;h4&gt;9. git commit --amend --no-edit&lt;/h4&gt;
&lt;p&gt;If you forgot to commit one extra change, you can use this command to edit your commit. Use it only if you &lt;strong&gt;did not&lt;/strong&gt; push your commit!&lt;/p&gt;
&lt;p&gt;&lt;img src="https://angrynerds.co/media/1778/3.jpg" alt="enter image description here" /&gt;&lt;/p&gt;
&lt;h4&gt;10. git-bisect&lt;/h4&gt;
&lt;p&gt;Imagine that you find a bug in the current version, and you know that this feature worked in some old commit. There are probably dozens of commits between the current version with the bug and the working one. If you have trouble with identifying what part of code and what commit is responsible for that bug, you can use git-bisect to identify the root cause of the issue. You start by marking two commits as bad and good, and use git-bisect to perform binary search in the repository history. More details can be found in &lt;a href="https://git-scm.com/docs/git-bisect" target="_blank"&gt;the documentation&lt;/a&gt;.&lt;/p&gt;
&lt;h4&gt;11. git grep&lt;/h4&gt;
&lt;p&gt;You probably know that you can search your working directory with grep function. Did you know you can do the same in the repository history? If you remember some part of code that was deleted and you need it now, use git grep. Usage is similar to grep function. Find out more &lt;a href="https://git-scm.com/docs/git-grep" target="_blank"&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;hr /&gt;
&lt;h4&gt;I hope you find these commands useful and they will make your daily work more efficient. If you want to learn more about Git and how it works, I highly recommend you this awesome presentation: &lt;a href="https://www.youtube.com/watch?v=fBP18-taaNw" target="_blank"&gt;Deep Dive into Git by Edward Thomson&lt;/a&gt;.&lt;/h4&gt;
&lt;h4&gt;Feel free to share your favorite Git commands in the comments!&lt;/h4&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;strong&gt;About the Author&lt;/strong&gt;&lt;br /&gt; 
&lt;a href="https://www.linkedin.com/in/marcin-zarebski/" target="_blank"&gt;Marcin Zarębski&lt;/a&gt; is an experienced back-end developer, specializing in. .NET platform. He has amazing skills in building complex backend solutions and infrastructure. Marcin is also interested in space exploration and the role of computer science in it. He likes to spend his free time in the mountains or playing board games. &lt;/p&gt;
</description>
      <pubDate>Thu, 05 Dec 2019 15:25:55 Z</pubDate>
      <a10:updated>2019-12-05T15:25:55Z</a10:updated>
    </item>
    <item>
      <guid isPermaLink="false">3210</guid>
      <link>https://angrynerds.co/blog/black-holes-and-algorithms-how-computer-science-helped-us-see-a-black-hole-for-the-first-time/</link>
      <category>Development</category>
      <title>Black holes and algorithms. How computer science helped us see a black hole for the first time</title>
      <description>&lt;p&gt;Its image was not created like an ordinary image. In some articles, you may find misleading headlines saying it's &lt;em&gt;a photo&lt;/em&gt; of a black hole. If you think that people zoomed in an image from one of the telescopes, then you couldn't be further from the truth. To create this image large amount of observation data was collected from several telescopes performing parallel observations. Next, all the data were combined and used to reconstruct the image that we saw in the news. In this post, I will describe this process, showing the role of image processing algorithms in this experiment.&lt;/p&gt;
&lt;div style="display: block; width: 500px; margin: 0 auto;"&gt;
&lt;img src="https://angrynerds.co/media/1604/giphy.gif"&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p&gt;&lt;em&gt;This post was written based on the article &lt;a href="https://iopscience.iop.org/article/10.3847/2041-8213/ab0e85" target="_blank"&gt;&amp;quot;First M87 Event Horizon Telescope Results. IV. Imaging the Central Supermassive Black Hole&amp;quot;&lt;/a&gt;. We only scratched the surface here, so if you want to go into depth you should read this paper (see sources at the end).&lt;/em&gt;&lt;/p&gt;
&lt;h2&gt;What is a black hole?&lt;/h2&gt;
&lt;p&gt;To fully appreciate this result we should remind ourselves what a black hole is exactly. A black hole is a region of space within which gravity pulls so much that nothing, not even light, can escape. This implies that black cannot be seen directly, though we can see gravity effects near the black hole. Strong gravity is a result of squeezing huge mass into a tiny space. To become a black hole, a star has to be massive (at least 20 times heavier than the Sun). There is a formula for calculating the radius of the created black hole. If hypothetically the Sun became a black hole, its radius would be reduced to 3 km. &lt;/p&gt;
&lt;p&gt;In 1916, Einstein completed his work where he described the general relativity theory. He characterized gravity using geometric concepts - geometric theory of gravitation. Einstein proposed that spacetime is curved around heavy objects. One of the consequences of Einstein's theory is that the time isn't the same in every place of the universe. One of the real-world application is the calculation of coordinates by navigation devices that communicate with GPS satellites. Amendment resulting from general relativity theory is crucial to obtain a precise result for coordinates calculations. If you want to explore black hole concepts further, I recommend you to watch this video - it's originally in Polish, but you can turn on English subtitles:&lt;/p&gt;
&lt;div align="center"&gt;&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/63qdJfWENNg" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen&gt;&lt;/iframe&gt;&lt;/div&gt;
&lt;p&gt;&lt;/br&gt;&lt;/p&gt;
&lt;h2&gt;Observation description&lt;/h2&gt;
&lt;p&gt;To observe such distant object scientists came up with the idea of combining data from several telescopes distributed around the Earth. This array of telescopes is called the Event Horizon Telescope (EHT). Here is a list of all facilities that collaborated in the black hole observations:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;the phased Atacama Large Millimeter/submillimeter Array (ALMA), &lt;/li&gt;
&lt;li&gt;Atacama Pathfinder Experiment telescope (APEX) in the Atacama Desert in Chile,&lt;/li&gt;
&lt;li&gt;the James Clerk Maxwell Telescope (JCMT),&lt;/li&gt;
&lt;li&gt;the phased Submillimeter Array (SMA) on Maunakea in Hawai'i, &lt;/li&gt;
&lt;li&gt;the Arizona Radio Observatory Sub-Millimeter Telescope (SMT) on Mt. Graham in Arizona, &lt;/li&gt;
&lt;li&gt;the IRAM 30 m (PV) telescope on Pico Veleta in Spain, &lt;/li&gt;
&lt;li&gt;the Large Millimeter Telescope Alfonso Serrano (LMT) on Sierra Negra in Mexico,&lt;/li&gt;
&lt;li&gt;the South Pole Telescope (SPT).&lt;/li&gt;
&lt;/ul&gt;
&lt;div style="display: block; width: 800px; margin: 0 auto;"&gt;
&lt;img src="https://angrynerds.co/media/1600/focus_figure_2_resized_opt.jpg"&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;div align="center"&gt;
&lt;i&gt;Photo via &lt;a href="https://iopscience.iop.org/article/10.3847/2041-8213/ab0e85" target="_blank" rel="nofollow"&gt;IOPscience&lt;/a&gt;&lt;/i&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p&gt;The biggest advantage of this virtual telescope is that its diameter is equal to the longest distance between the telescopes in array, i.e. distance between Spain and the South Pole. The biggest challenge is different weather conditions around the globe that could prevent you from gathering data from all places. EHT team decided that the best dates for observation were April 5, 6, 10, and 11 in 2017. On these days different target observations interleaved with black hole observation and results were later used for comparison. The number of scans on individual days is 18, 25, 7 and 22. A single scan is an observation between 4 and 7 minutes. Here is a picture in which you can see coverage for EHT observations of M87. &lt;/p&gt;
&lt;div style="display: block; width: 800px; margin: 0 auto;"&gt;
&lt;img src="https://angrynerds.co/media/1605/figure-1_opt.jpg"&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;div align="center"&gt;
&lt;i&gt;Photo via &lt;a href="https://iopscience.iop.org/article/10.3847/2041-8213/ab0c96" target="_blank" rel="nofollow"&gt;IOPscience&lt;/a&gt;&lt;/i&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p&gt;If the EHT team put telescopes all around the Earth, they would record data for every point, and then it would be relatively easy to make an image using known image processing algorithms, e.g. Fourier transformation. But since they only have telescopes at several places they only get a scarce number of measurements. Earth rotation helped us to expand observation coverage. Team working at each facility recorded petabytes of data. At some point, all this data had to be transported to one location. Sending it over the Internet network would take longer than moving it physically. Then the data analysis could begin. &lt;/p&gt;
&lt;h2&gt;How computer science was applied to generate the image?&lt;/h2&gt;
&lt;p&gt;Due to a limited set of samples in the visibility domain, we cannot reconstruct the image accurately. The team had to enforce constraints that were not implied by the measurements. That's how you may see different images that were reconstructed at different steps.&lt;/p&gt;
&lt;p&gt;In the first step, the team worked on correlating data from observation and replacing a weak signal by a stronger one hidden in that correlated data. This reduced data size from petabytes to terabytes. Observed data can be expressed by convolution formula f = g * h. In other words, we know that observed image f is equal to actual image g convoluted with factors that deformed observed image h, i.e. f = g * h, where f, g, h are functions and * stands for convolution. Factors that deformed black hole observed data are mainly caused by the atmosphere (different weather conditions among observatories) and calibration errors. We know f, more or less h and we have to solve this equation for g.&lt;/p&gt;
&lt;p&gt;In the second step, four teams were formed and they worked independently using different algorithms to produce the black hole image. Imaging algorithms can be generally divided into two categories: forward modeling and inverse modeling. In forward modeling, you take the current state of some object and you run your algorithm to see how your object changes in the future. Inverse modeling is the opposite of forward modeling, i.e. your model is in some state and you want to calculate what state can produce the initial state. The team used algorithms based on CLEAN for inverse modeling and RML - regularized maximum likelihood for forward modeling. Both are image reconstruction techniques that reverse the result effects of convolution on observed data. To learn more about these algorithms you can see &lt;a href="https://www.cv.nrao.edu/~abridle/deconvol/node1.html" target="_blank"&gt;this website&lt;/a&gt;. 
Here is a comparison of the images reconstructed by each team:&lt;/p&gt;
&lt;div style="display: block; width: 800px; margin: 0 auto;"&gt;
&lt;img src="https://angrynerds.co/media/1603/figure-4_opt.jpg"&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;div align="center"&gt;
&lt;i&gt;Photo via &lt;a href="https://iopscience.iop.org/article/10.3847/2041-8213/ab0e85" target="_blank" rel="nofollow"&gt;IOPscience&lt;/a&gt;&lt;/i&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;p&gt;In the third step, the team worked on choosing imaging parameters that produce in some sense the best picture. Among other things they tested different parameter values for synthetic images and restored images using those parameters. They selected geometric models that are similar to those observed in M87, e.g. ring, crescent, disk. See the image below for comparison of different algorithms that were run with the best-selected parameters. The last step was the final image validation. The team performed additional tests to assess the reliability of the created image.&lt;/p&gt;
&lt;div style="display: block; width: 800px; margin: 0 auto;"&gt;
&lt;img src="https://angrynerds.co/media/1602/figure-10_opt.jpg"&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;div align="center"&gt;
&lt;i&gt;Photo via &lt;a href="https://iopscience.iop.org/article/10.3847/2041-8213/ab0e85" target="_blank" rel="nofollow"&gt;IOPscience&lt;/a&gt;&lt;/i&gt;
&lt;/div&gt;
&lt;p&gt;&lt;br /&gt;&lt;/p&gt;
&lt;h2&gt;Summary&lt;/h2&gt;
&lt;p&gt;This procedure took almost two years to complete it. The final image is a result of a joint effort of &lt;a href="https://twitter.com/APSphysics/status/1116697842280693762" target="_blank"&gt;more than 200 researchers&lt;/a&gt;!&lt;/p&gt;
&lt;p&gt;If you want to see the black hole image in original size 7416 x 4320 px, follow &lt;a href="https://www.eso.org/public/images/eso1907a" target="_blank"&gt;this link&lt;/a&gt;. In the future, we can expect more detailed images as more telescopes are added to EHT array. Perhaps space telescopes could be used to enhance this image and maybe record video. The future is going to be exciting!&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;strong&gt;Sources:&lt;/strong&gt;&lt;/br&gt;
1. &lt;a href="https://iopscience.iop.org/article/10.3847/2041-8213/ab0e85" target="_blank"&gt;The Event Horizon Telescope Collaboration et al 2019 ApJL 875 L4&lt;/a&gt;&lt;/br&gt;
2. Katie Bouman - &lt;a href="https://www.youtube.com/watch?v=UGL_OL3OrCE" target="_blank"&gt;Imaging a Black Hole with the Event Horizon Telescope&lt;/a&gt;
&lt;br /&gt;&lt;/p&gt;
&lt;hr /&gt;
&lt;p&gt;&lt;strong&gt;About the Author&lt;/strong&gt;&lt;br /&gt; 
&lt;a href="https://www.linkedin.com/in/marcin-zarebski/" target="_blank"&gt;Marcin Zarębski&lt;/a&gt; is an experienced back-end developer, specializing in. .NET platform. He never ceases to amaze us with his skills in building complex backend solutions and infrastructure. Marcin is also interested in space exploration and the role of computer science in it. He likes to spend his free time in the mountains or playing board games. &lt;/p&gt;
</description>
      <pubDate>Thu, 09 May 2019 08:09:05 Z</pubDate>
      <a10:updated>2019-05-09T08:09:05Z</a10:updated>
    </item>
  </channel>
</rss>