<?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: Filip Kisić</title>
    <description>The latest articles on DEV Community by Filip Kisić (@filipkisic).</description>
    <link>https://dev.to/filipkisic</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%2F793837%2F6ebc2f7b-fae6-4a78-be19-fc5bce63bcc7.jpeg</url>
      <title>DEV Community: Filip Kisić</title>
      <link>https://dev.to/filipkisic</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/filipkisic"/>
    <language>en</language>
    <item>
      <title>Design patterns - Part II</title>
      <dc:creator>Filip Kisić</dc:creator>
      <pubDate>Wed, 14 Jun 2023 11:14:32 +0000</pubDate>
      <link>https://dev.to/filipkisic/design-patterns-part-ii-16b1</link>
      <guid>https://dev.to/filipkisic/design-patterns-part-ii-16b1</guid>
      <description>&lt;h2&gt;
  
  
  Intro
&lt;/h2&gt;

&lt;p&gt;So this is the second part of the blog series Design Patterns. In the first part, we took a look at the five popular design patterns which are Factory, Builder, Singleton, Adapter and Bridge. Let's take a look at the next five. First, we shall start with the Decorator pattern.&lt;/p&gt;

&lt;h2&gt;
  
  
  #6 Decorator
&lt;/h2&gt;

&lt;p&gt;A decorator is a very simple pattern because all it does is change the behaviour of an object. It is also very useful when we want to obey SRP (Single Responsibility Pattern) as it allows the division of functionalities between classes. A real-world example would be a car trip. There is a regular car when we are driving around the city, but when we go on a trip and more space is needed, often roof boxes are placed on cars and then they are ready for a trip. What is neat about those roof boxes is that they can be placed or removed when needed. The same thing is with the decorator. It can modify some behaviour at the runtime, so when it is needed. Let's code the example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;abstract class Car {
  void drive();
  void packStuff();
  void unpackStuff();
}

class CarWagon implements Car {
  @override
  void drive() =&amp;gt; print('Driving freely...');

  @override
  void packStuff() =&amp;gt; print('Opening trunk, putting stuff...');

  @override
  void unpackStuff() =&amp;gt; print('Opening trunk, taking stuff...');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here above are Car interface and the implementation of that interface is &lt;code&gt;CarWagon&lt;/code&gt;. Now what if we want to go to the seaside, we don't want a new car for that. We want to equip our car with a roof box and we will do it this way:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CarWagonRoofBox implements Car {
  final CarWagon carWagon;

  CarWagonRoofBox(this.carWagon);

  @override
  void drive() =&amp;gt; carWagon.drive();

  @override
  void packStuff() {
    carWagon.packStuff();
    print('Opening roof box too, putting stuff...');
  }

  @override
  void unpackStuff() {
    carWagon.unpackStuff();
    print('Opening roof box too, taking stuff...');
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Using DI (Dependency Injection) we equip our car with a roof box. That is it, the decorator pattern is finished. The final result:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;final CarWagon carWagon = CarWagon();
carWagon.packStuff();
carWagon.unpackStuff();

print('Going to seaside...');

final CarWagonRoofBox carWagonWithRoofBox = CarWagonRoofBox(carWagon);
carWagonWithRoofBox.packStuff();
carWagonWithRoofBox.unpackStuff();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And this is the output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Opening trunk, putting stuff...
Opening trunk, taking stuff...
Going to seaside...
Opening trunk, putting stuff...
Opening roof box too, putting stuff...
Opening trunk, taking stuff...
Opening roof box too, taking stuff...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This was an easy one, agree? The next pattern we will examine is the Facade pattern.&lt;/p&gt;

&lt;h2&gt;
  
  
  #7 Facade
&lt;/h2&gt;

&lt;p&gt;The facade pattern is by the book the following: "Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use." What it means by that is the facade is something like a higher-order interface. Here is an explanation with a real-world example. When you are shopping for a new car, a salesperson is like a facade person to you because you are not aware of the complex processes needed to sell you a car, all you have to do is pick a model, customize it and after some time it will arrive, waiting for you. How cars are ordered and produced is not your concern. Some material inputs are processed on the manufacturing line, the engine is connected to a chassis, interior parts are stitched, the onboard computer is programmed and at the end, there is a quality check. That is how the car is produced, but the whole process is hidden from you as a user, that is what facade pattern is. Let's code the example straightforward.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class ChassisWorker {
  void processInputMaterial() =&amp;gt; print('Welding the chassis...');
  void paint() =&amp;gt; print('Painting the chassis...');
  void finish() =&amp;gt; print('Finishing the final details...');
}

class EngineWorker {
  void makeCylinders() =&amp;gt; print('Making the cylinders...');
  void assembleEngine() =&amp;gt; print('Assembling the engine...');
  void testEngine() =&amp;gt; print('Testing the engine...');
}

class InteriorWorker {
  void cleanLeatherPelts() =&amp;gt; print('Cleaning leather pelts...');
  void stitchLeather() =&amp;gt; print('Stitching the leather...');
  void coatLeather() =&amp;gt; print('Coating the leather...');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;For a clearer explanation, I used concrete classes rather than interfaces. The classes above describe the smaller, more complex process of car manufacturing. The class below wraps those processes behind the high-level class, &lt;code&gt;CarFactoryFacade&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CarFactoryFacade {
  final ChassisWorker chassisWorker = ChassisWorker();
  final EngineWorker engineWorker = EngineWorker();
  final InteriorWorker interiorWorker = InteriorWorker();

  void produceCar() {
    _startManufacturingProcess();
    _assembleComponents();
    _qualityCheck();
  }

  void _startManufacturingProcess() {
    chassisWorker.processInputMaterial();
    engineWorker.makeCylinders();
    interiorWorker.cleanLeatherPelts();
  }

  void _assembleComponents() {
    chassisWorker.paint();
    engineWorker.assembleEngine();
    interiorWorker.stitchLeather();
  }

  void _qualityCheck() {
    chassisWorker.finish();
    engineWorker.testEngine();
    interiorWorker.coatLeather();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, when the client or someone else needs to use or describe the whole process, all it needs is just this one high-level method. The final step is to call that facade in the app.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;final CarFactoryFacade facade = CarFactoryFacade();

facade.produceCar();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The output is the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Welding the chassis...
Making the cylinders...
Cleaning leather pelts...

Painting the chassis...
Assembling the engine...
Stitching the leather...

Finishing the final details...
Testing the engine...
Coating the leather...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There you go, this is the facade design pattern. The next pattern we will cover is the Service locator, Singleton on steroids.&lt;/p&gt;

&lt;h2&gt;
  
  
  #8 Service locator (Singleton on steroids)
&lt;/h2&gt;

&lt;p&gt;Service Locator is used to decouple client and interface implementation. It is also a Singleton, but instead of returning itself as an instance, it returns something we are looking for, a service for example. An example from real life would be the DNS server. We as a client want to get the remote website. What DNS gets is a readable web address, then it looks up the IP address in its pool of addresses, if it is found, it is returned to us and we do the rest that we want. We as a client don't know where the wanted website is located, we ask a DNS server and it gets it for us, the same is with the service locator. Here is an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;abstract class Website {
  String getUrl();
  void render();
}

class PageOne implements Website {
  final String url = 'www.page-one.com';

  @override
  String getUrl() =&amp;gt; url;

  @override
  void render() =&amp;gt; print('Rendering page one... ');
}

class PageTwo implements Website {
  final String url = 'www.page-two.com';

  @override
  String getUrl() =&amp;gt; url;

  @override
  void render() =&amp;gt; print('Rendering page two...');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have a website interface that can return its URL and render itself. Beneath we create only two websites.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class WebsiteServiceLocator {
  static final WebsiteServiceLocator _instance = WebsiteServiceLocator._privateConstructor();
  WebsiteServiceLocator._privateConstructor();
  static WebsiteServiceLocator get instance =&amp;gt; _instance;

  final HashSet _websites = HashSet&amp;lt;Website&amp;gt;.from([PageOne(), PageTwo()]);

  void registerWebsite(Website websiteToRegister) =&amp;gt; _websites.add(websiteToRegister);

  Website? findWebsite(String url) {
    try {
      return _websites.firstWhere((website) =&amp;gt; website.getUrl() == url);
    } catch (e) {
      return null;
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, there is a service locator which is a singleton and it holds the HashSet of all known pages. There is also an option to register a new one when needed. The most important method is &lt;code&gt;findWebsite&lt;/code&gt; which returns the wanted website. This way, a client only needs to communicate with a &lt;code&gt;WebServiceLocator&lt;/code&gt; without any worries about how many websites are there, the service locator will do the job for it. And there it is, you can memorize the service locator as a DNS server. However, some issues appear when you are using this pattern, so if it isn't necessary, do not use this pattern. Firstly, it makes unit testing harder because it is a static singleton class, so there are no mocked objects. It also creates hidden dependencies which can cause runtime client breaks. A solution to these problems is using the Dependency Injection pattern. If you are a Flutter developer, then you probably heard of the well-known &lt;code&gt;get_it&lt;/code&gt; package. It is the implementation of the Service Locator design pattern. Alternatives for &lt;code&gt;get_it&lt;/code&gt; are for example &lt;code&gt;riverpod&lt;/code&gt; and &lt;code&gt;provider&lt;/code&gt; packages. I personally prefer the &lt;code&gt;riverpod&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  #9 Observer
&lt;/h2&gt;

&lt;p&gt;For this design pattern, I'll give an example for the Flutter framework, but first the real-world example. In the restaurant, a waiter observes all the tables and if there is a new guest, he/she welcomes the guest and takes an order. While the guest is eating, the waiter still observes all tables and when another guest is finished, he/she charges the guest and cleans the table, then all over again. So, the waiter observes and when there is a new event, he/she reacts to it. This will be a classic OOP example, let's code it.&lt;/p&gt;

&lt;p&gt;In Flutter, this pattern is used in almost any application. Any interactive widget has a listener, for example, GestureDetector has an onTap listener. If you have to show data changes from a local database or a WebSocket as an input, the observer is also implemented as a Stream. The most important example is state management. Let's see the &lt;code&gt;provider&lt;/code&gt; since it is the most basic state management solution. The following code snippet notifies the UI when a fuel tank level changes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class FuelTankModel extends ChangeNotifier {
  int tankLevelPercentage = 100;

  void decreaseLevel() {
    tankLevelPercentage--;
    notifyListeners();
  }

  void increaseLevel() {
    tankLevelPercentage++;
    notifyListeners();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have to rebuild UI every time it is notified about the change.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
child: Center(
  child: Consumer&amp;lt;FuelTankModel&amp;gt;(builder: ((context, tankLevel, child) {
      return Text('Current fuel level: $tankLevel%');
    }),
  ),
),
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This was the observer pattern. It can be implemented in various use cases and it is easy to implement. The next pattern is the State pattern. At first, it will seem very similar to the Observer pattern, but there are some differences that you'll see in the next chapter.&lt;/p&gt;

&lt;h2&gt;
  
  
  #10 State
&lt;/h2&gt;

&lt;p&gt;State is a behavioral design pattern, its observers change their behavior when the state of that object changes, so let's make an example of human behavior. In the morning we are in our pajamas and our actions are focused on preparing for the day ahead of us. Next, before work, in the gym, we are in sports clothes and focused on exercises and how many reps/series we do. Later in the office, we are in our formal clothes and front of the clients trying to behave as professionally as possible. After work, hanging out with our friends, we are relaxed and we behave appropriately. So our behavior changes based on the events and environments that surround us, the same is with the state design pattern. Let's code the given example above.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;abstract class State {
  void change();
  void behave();
}

class MorningState implements State {
  final Person person;

  MorningState(this.person) {
    change();
  }

  @override
  void change() {
    person.clothes = 'pajamas';
  }

  @override
  void behave() {
    print('Wearing ${person.clothes}, preparing for the day...');
  }
}

class GymState implements State {
  final Person person;

  GymState(this.person) {
    change();
  }

  @override
  void change() {
    person.clothes = 'sports clothes';

  }

  @override
  void behave() {
    print('Wearing ${person.clothes}, working out...');
  }
}

class BusinessState implements State {
  final Person person;

  BusinessState(this.person) {
    change();
  }

  @override
  void change() {
    person.clothes = 'suit';
  }

  @override
  void behave() {
    print('Wearing ${person.clothes}, focusing on productivity...');
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, we created three states in which a person will be throughout the day, now let's create that person.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Person {
  late String clothes;
  late State behaviour;

  Person() {
    clothes = 'pajamas';
    behaviour = MorningState(this);
  }

  void doDailyTask(State state) {
    behaviour = state;
    state.behave();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The person wears clothes and has some behavior based on the state it is. Every person starts the day in the morning, therefore the &lt;code&gt;MorningState&lt;/code&gt; in the constructor. There is also a method &lt;code&gt;doDailyTask&lt;/code&gt; which takes a new state as a parameter and puts that person in the passed state. This is the main part of the code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void main() {
  final person = Person();
  person.doDailyTask(MorningState(person));
  person.doDailyTask(GymState(person));
  person.doDailyTask(BusinessState(person));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is the output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Wearing pajamas, preparing for the day...
Wearing sports clothes, working out...
Wearing suit, focusing on productivity...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This was the final design pattern to cover. The state design pattern should be used when our object has to change its behavior if its internal state changes. One of the examples would be UI rendering. If the UI state is loading, the loading indicator should be displayed on the UI, if the state is an error, the error message should be displayed and finally if everything was fine, the result should be displayed to the user.&lt;/p&gt;

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

&lt;p&gt;Here is the end of the blog. This was an opportunity to learn new things and better understand already known. If you like the content of this blog, I recommend you to read the book "Design Patterns: Elements of Reusable Object-Oriented Software". It covers all this, but with greater depth. Thank you for your time and happy coding! :D&lt;/p&gt;

</description>
      <category>programming</category>
      <category>tutorial</category>
      <category>designpatterns</category>
      <category>cleancode</category>
    </item>
    <item>
      <title>Design patterns - Part I</title>
      <dc:creator>Filip Kisić</dc:creator>
      <pubDate>Tue, 06 Jun 2023 09:08:47 +0000</pubDate>
      <link>https://dev.to/filipkisic/design-patterns-part-i-1pcg</link>
      <guid>https://dev.to/filipkisic/design-patterns-part-i-1pcg</guid>
      <description>&lt;h2&gt;
  
  
  What are design patterns?
&lt;/h2&gt;

&lt;p&gt;On a daily basis, we encounter problems that we solve as engineers, that is our passion. With some experience, you'll see that some problems share the same pattern and therefore we have solution patterns and design patterns that serve as a blueprint to solve those problems.&lt;/p&gt;

&lt;h2&gt;
  
  
  Difference between the algorithm and the design pattern
&lt;/h2&gt;

&lt;p&gt;From the text above, you could also say the same for the algorithms, but the difference is that a design pattern is a higher level concept or a guide how to solve the problem. You can't simply copy/paste the pattern, but you have to think and follow the steps to implement it. On the other hand an algorithm can be copy/pasted in the code to make it work and it is a low level, detailed solution.&lt;/p&gt;

&lt;h2&gt;
  
  
  Types of patterns
&lt;/h2&gt;

&lt;p&gt;There are three types of design patterns:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Creational&lt;/li&gt;
&lt;li&gt;Structural&lt;/li&gt;
&lt;li&gt;Behavioural&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Creational patterns provide various creational methods that can result in more flexible and reusable code. When you need large data structures made of multiple objects and classes, structural patterns are there to help. Lastly, there are behavioural patterns which can help solve algorithmically problems as well as responsibilities between the objects. All of the examples below are written in Dart programming language.&lt;/p&gt;

&lt;h2&gt;
  
  
  #1 Factory method
&lt;/h2&gt;

&lt;p&gt;From a standpoint of a mobile developer, cross-platform developer specifically, each OS has its components/widgets. Let's use Android and iOS as an example. Android has a button widget that follows Material design, so as iOS button follows Apple Human Interface Guidelines. That requires two different widgets which have the same properties and behaviours. For example these:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  Color color;
  String label;
  Function onPressed;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's say the Windows Phone is still an alive project, it would require another widget, you see where I am going. We write the code for those, but new platforms arrive on the market, and therefore new code to write. It is repetitive, with lot of the same code and that is a problem. A solution for this kind of problem is a factory method pattern. What the factory method does is it extracts common properties and behaviours to an abstract class. Why? Well, as always, we should lean towards abstractions, that make our code more flexible and depend upon abstractions, not concrete implementations. This way, we define what one button should be and have, hence every button on the new platform should extend that abstract button. For better understanding, take a look at the following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;abstract class AdaptiveButton {
  final VoidCallback? onPressed;
  final String label;
  Widget create();

  AdaptiveButton({required this.onPressed, this.label = 'Button'});
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Every button on every platform should have its own onPressed callback, label and method create in which later we'll define how to create the button for the given platform. The &lt;code&gt;create()&lt;/code&gt; method is the most important one. Let's see what would Android button look like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class AndroidButton extends AdaptiveButton {
  AndroidButton({required VoidCallback? onPressed, required String label,}) : super(onPressed: onPressed, label: label,);

  @override
  Widget create() {
    return ElevatedButton(
            onPressed: onPressed,
            child: Text(label),
        );
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We let the fellow developer define the label and callback method, but what we defined is how the Android button should be created. The same applies to the iOS button.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class IOSButton extends AdaptiveButton {
  IOSButton({required VoidCallback? onPressed, required String label})
      : super(onPressed: onPressed, label: label);

  @override
  Widget create() {
    return CupertinoButton.filled(
            child: Text(label),
            onPressed: onPressed,
        );
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If abstract classes aren't something you are good with, think of them like a contract. If you want to be a button, you have to sign the AdaptiveButton contract, by that, you have to have certain properties and behaviours.&lt;/p&gt;

&lt;p&gt;We defined how to create buttons, now let's render them on the screen. In this demo app, based on which platform is being run, it will render an appropriate button, if the platform is not supported, an exception will be thrown.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;abstract class ButtonFactory {
  AdaptiveButton showButton(final VoidCallback callback, final String label);
}

class ButtonFactoryImpl implements ButtonFactory {
  @override
  AdaptiveButton showButton(final VoidCallback callback, final String label) {
    if (Platform.isAndroid) {
      return AndroidButton(onPressed: callback, label: label);
    } else if (Platform.isIOS) {
      return IOSButton(onPressed: callback, label: label);
    } else {
      throw Exception('OS not supported');
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And when we figured out which button to render, now we just have to create it and be done. This whole screen looks like this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class LoginScreen extends StatelessWidget {
  final ButtonFactory buttonFactory;

  const LoginScreen({Key? key, required this.buttonFactory}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    ...
    buttonFactory.showAppropiateButton(login, 'Login').create();
    ...
  }

  void login() {
    ...
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And there it goes, now to add support for a new platform, e.g. for Huawei's Harmony OS, all we have to do is create HarmonyButton class which must extend AdaptiveButton class and add a case in the &lt;code&gt;showButton&lt;/code&gt; method. As a mobile developer, this pattern is quite a helpful and neat way to manage different platforms in a clean and easy-to-maintain way.&lt;/p&gt;

&lt;h2&gt;
  
  
  #2 Builder
&lt;/h2&gt;

&lt;p&gt;We covered the Factory Method, now let's see what Builder Design Pattern is. First what it is used for is for creating complex objects. Cars are complex objects for example, and imagine having a special constructor for each type of car, a lot of code and not being flexible at all. The builder approach is to extract common building parts in methods. Let's do the example. The average car configuration has millions, probably billions options when combined, so let's create two cars, one is a daily driver, and the other is for weekend drives.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Car {
  final String? color;
  final int? wheelSizeInInches;
  final bool? hasBadges;
  final EquipmentTrim? equipmentTrim;
  final ChassisType? chassisType;
  final EngineType? engineType;
  final InteriorTrim? interiorTrim;

  Car(
    this.color,
    this.wheelSizeInInches,
    this.hasBadges,
    this.equipmentTrim,
    this.chassisType,
    this.engineType,
    this.interiorTrim,
  );

  @override
  String toString() =&amp;gt; 'This is $color $chassisType with $wheelSizeInInches inch wheels, $interiorTrim interior and $engineType engine under the hood.';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the example above, the constructor is too long, so the process of object creation will be too long, therefore not readable. When you want to create a new car, every time you have to set all those properties over and over through the constructor which can be a lot of work. This is where a builder pattern comes to the rescue.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class CarBuilder {
  String? color;
  int? wheelSizeInInches;
  bool? hasBadges;
  EquipmentTrim? equipmentTrim;
  ChassisType? chassisType;
  EngineType? engineType;
  InteriorTrim? interiorTrim;

  CarBuilder withColor(String? color) {
    this.color = color;
    return this;
  }

  CarBuilder withWheelSizeInInches(int? wheelSizeInInches) {
    this.wheelSizeInInches = wheelSizeInInches;
    return this;
  }

  CarBuilder withHasBadges(bool? hasBadges) {
    this.hasBadges = hasBadges;
    return this;
  }

  CarBuilder withEquipmentTrim(EquipmentTrim? equipmentTrim) {
    this.equipmentTrim = equipmentTrim;
    return this;
  }

  CarBuilder withChassisType(ChassisType? chassisType) {
    this.chassisType = chassisType;
    return this;
  }

  CarBuilder withEngineType(EngineType? engineType) {
    this.engineType = engineType;
    return this;
  }

  CarBuilder withInteriorTrim(InteriorTrim? interiorTrim) {
    this.interiorTrim = interiorTrim;
    return this;
  }

  Car build() {
    return Car(this); 
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Because Dart is a null-safe language, we have to define every parameter to be nullable. Now let's modify the &lt;code&gt;Car&lt;/code&gt; class which will take &lt;code&gt;CarBuilder&lt;/code&gt; as a constructor parameter.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Car {
  ...
  Car(CarBuilder builder)
      : color = builder.color,
        wheelSizeInInches = builder.wheelSizeInInches,
        hasBadges = builder.hasBadges,
        equipmentTrim = builder.equipmentTrim,
        chassisType = builder.chassisType,
        engineType = builder.engineType,
        interiorTrim = builder.interiorTrim;
  ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What we've done here is passed &lt;code&gt;CarBuilder&lt;/code&gt; as a parameter by which we initialize all parameters that the &lt;code&gt;Car&lt;/code&gt; class has, but this is one case, what if we don't have the freedom to edit the &lt;code&gt;Car&lt;/code&gt; constructor and its constructor looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Car {
  String? color;
  int? wheelSizeInInches;
  bool? hasBadges;
  EquipmentTrim? equipmentTrim;
  ChassisType? chassisType;
  EngineType? engineType;
  InteriorTrim? interiorTrim;

  Car(this.color, this.equipmentTrim, this.chassisType);

  @override
  String toString() =&amp;gt; 'This is $color $chassisType with $wheelSizeInInches inch wheels, $interiorTrim interior and $engineType engine under the hood.';
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now only three properties are needed to construct an object. With the builder pattern, all we have to do is modify the &lt;code&gt;build&lt;/code&gt; method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  Car build() {
    return Car(this.color, this.equipmentTrim, this.chassisType); 
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We defined what the constructor asked us to do, but now we lost all other car properties, to fix we'll use setters and return the full object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Car build() {
    Car car = Car(this.color, this.equipmentTrim, this.chassisType);
    car.wheelSizeInInches = this.wheelSizeInInches;
    car.hasBadges = this.hasBadges;
    car.engineType = this.engineType;
    car.interiorTrim = this.interiorTrim;
    return car;
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The bottom line, the &lt;code&gt;build()&lt;/code&gt; method must do all necessary steps to create an object that then returns.&lt;br&gt;&lt;br&gt;
With everything setup, we should build our cars:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;final Car c63amg = CarBuilder()
    .withColor('Red')
    .withWheelSizeInInches(19)
    .withHasBadges(true)
    .withEquipmentTrim(EquipmentTrim.sport)
    .withChassisType(ChassisType.coupe)
    .withEngineType(EngineType.gasoline)
    .withInteriorTrim(InteriorTrim.alcantara)
    .build();

final Car granCoupe4 = CarBuilder()
    .withColor('Grey')
    .withWheelSizeInInches(18)
    .withHasBadges(false)
    .withEquipmentTrim(EquipmentTrim.luxury)
    .withChassisType(ChassisType.granCoupe)
    .withEngineType(EngineType.diesel)
    .withInteriorTrim(InteriorTrim.leather)
    .build();

print(c63amg.toString());
print(granCoupe4.toString());
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;When we print the result of this, here is what we get:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;This is Red coupe with 19 inch wheels, alcantara interior and gasoline engine under the hood.
This is Grey granCoupe with 18 inch wheels, leather interior and diesel engine under the hood.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In conclusion, a builder pattern is used when you have a lot of object creation in your code and with different properties. The pattern wraps the creation process and makes object creation and customization easy step by step, but with the price of additional classes and functions.&lt;/p&gt;

&lt;h2&gt;
  
  
  #3 Singleton
&lt;/h2&gt;

&lt;p&gt;Singleton is maybe the easiest design pattern to learn and implement. As the name suggests, there is a single instance of an object.&lt;br&gt;
Before I knew about this pattern, I always created static variables, but sometimes it wasn't a good solution since I could overwrite the object with another. With &lt;code&gt;NotificationService&lt;/code&gt; as an example, I'll try to explain why is Singleton good and why is not. I want to have only one instance of the &lt;code&gt;NotificationService&lt;/code&gt; class, so when someone needs to notify a user about something by accessing OS API, there won't be multiple instances of the same object which eventually accumulates operations for a garbage collector, but we will reuse the one instance only. There Singleton acts as a solution. Singleton class has ONE PRIVATE instance of its class and its getter. That makes that instance global and protected from being overridden. Let's try to implement it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class NotificationService {
  NotificationService._privateConstructor();
  static final NotificationService _instance = NotificationService._privateConstructor();
  static NotificationService get instance =&amp;gt; _instance;

  void showNotification() {
    ...
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the code above, these first three lines are all we need. We need to make our constructor private, so no one from the outside cannot create a new instance, we need then to create a private instance and expose it using the getter. The method &lt;code&gt;showNotification&lt;/code&gt; speaks with the OS and shows the notification to the user. Later, to test if the instance is a singleton, we check object references. Let's do it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void notifyUser() {
    final NotificationService _notificationService = NotificationService.instance;
    final NotificationService _notificationServiceTwo = NotificationService.instance;    

    log('${_notificationService == _notificationServiceTwo}', name: 'ARE EQUAL');

    _notificationService.showNotification();
  }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I used the most simple approach and just printed the equality result. Of course, it prints true. Since this is Dart, in Dart &lt;code&gt;==&lt;/code&gt; operator checks if the given objects references are the same. &lt;/p&gt;

&lt;p&gt;We covered why you should use the Singleton and what are the benefits of using it, but there are also some problems, so let's talk about them. Firstly and most importantly, it violates the Single Responsibility Pattern because its concerns are instance creation and lifecycle. Secondly, in the multithreaded environment using the Singleton pattern is not safe because if the data it holds is mutable when two threads access the data at the same time an error can happen. Let's look at an example, but this time in Java.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class NotificationService {
    private static NotificationService instance;

    private NotificationService();

    public static NotificationService getInstance() {
        if (instance == null) {
            instance = NotificationService();
        }
        return instance;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The solution is to make the &lt;code&gt;getInstance()&lt;/code&gt; method synchronized, that way only one thread can call a method at a time. It looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class NotificationService {
    private static NotificationService instance;

    private NotificationService();

    public static synchronized NotificationService getInstance() {
        if (instance == null) {
            instance = NotificationService();
        }
        return instance;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Since Dart is a single-threaded language running in one isolate, there are no worries as long as you don't create another isolate. Moreover, when creating a Singleton class, lazy initialization is the preferred way of doing it, so an instance is created when it is first needed. If it is done eagerly, an instance will be created while classes are being loaded and there is a possibility that a singleton instance won't be used in the app lifecycle.&lt;/p&gt;

&lt;p&gt;There is also one extreme, but very natural case of a singleton, it is a single-element enum. Look at this one here.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;enum EiffelTower {
  instance
}

const EiffelTower _parisTowerOne = EiffelTower.instance;
const EiffelTower _parisTowerTwo = EiffelTower.instance;

void testTowers() {
  print('ARE EQUAL: ${_parisTowerOne == _parisTowerTwo}');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There is only one original Paris Eiffel Tower, this enum ensures that is true. Fun fact, there are 12 Eiffel Towers around the world.&lt;/p&gt;

&lt;h2&gt;
  
  
  #4 Adapter
&lt;/h2&gt;

&lt;p&gt;Our notebooks are the most important tool in our everyday lives, we use them for a lot of things, but sometimes to make things done we need an adapter. For example, some notebooks don't have a microSD card slot to import our B-rolls. Then the adapter comes to the rescue, a microSD adapter to be exact. The same problem can be found while programming, one example would be working with REST API that provides data in certain model objects, which are not compatible with your app. Firstly, the API most of the time sends data in JSON format and sometimes its property names are not compatible with yours too. Here is an example of a such JSON object:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  'userId': 1,
  'username': 'phillip.k',
  'email': 'phillip@gmail.com',
  'dateOfBirth': '07-01-2000'
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And this is how our model class looks like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User {
  final int id;
  final String username;
  final String email;
  final Date birthday;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can notice, some property names are different and in JSON object dateOfBirth is a String, not a DateTime which we need. Here we can resolve our problem using the Adapter pattern in its simplest form, like a method. What we want is to create a method called &lt;code&gt;fromJson&lt;/code&gt; which takes the JSON object and returns the model object that we need. Here is the code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;factory User.fromJson(Map&amp;lt;String, dynamic&amp;gt; json) {
  return User(
    id: json['userId'] as int,
    username: json['username'] as String,
    email: json['email'] as String,
    birthday: DateTime.parse(json['dateOfBirth'] as String),
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What we did up there is we took JSON from REST API in the form of a Map where keys are strings and values are dynamic, we can't know their datatype. So, we got one data format, but we want data formatted as User class, that is why we return a new instance of the User class. The constructor call is where everything is happening, &lt;code&gt;id&lt;/code&gt; takes value under the key of &lt;code&gt;userId&lt;/code&gt; and converts it to the integer. The process repeats for each property. Eventually, we return that created instance. The main purpose of the Adapter is to adapt the data format received from one data source to the format we find suitable to use in our application. To explain the concept better, here is a more complex example using multiple classes.&lt;br&gt;
We have a microSD card that can export data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MicroSDCard {
  void exportData() {
    print('Exporting B-roll from MicroSDCard...');
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our laptop will have only USB-C as input interface so let's create &lt;code&gt;USBInput&lt;/code&gt; interface.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;abstract class USBInput {
  void transferData();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Lastly, we need our laptop which should import data through USB-C input, it will look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Laptop {
  final USBInput usbInput;

  const Laptop(this.usbInput);

  void importData() {
    usbInput.transferData();
    print('B-roll imported!');
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now the problem is that we cannot connect our microSD card into USB-C port on our laptop.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void main() {
  MicroSDCard card = MicroSDCard();
  Laptop laptop = Laptop(); //We cannot create laptop object without USBInput  
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is the solution, our &lt;code&gt;MicroSDToUSBAdapter&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MicroSDToUSBAdapter implements USBInput {
  final MicroSDCard card;

  const MicroSDToUSBAdapter(this.card);

  @override
  void transferData() {
    card.exportData();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What we've done here is we defined that our adapter takes &lt;code&gt;MicroSDCard&lt;/code&gt; and it knows how to transfer data when connected to USB-C.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class MicroSDToUSBAdapter implements USBInput {
  final MicroSDCard card;

  const MicroSDToUSBAdapter(this.card);

  @override
  void transferData() {
    card.exportData();
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here is the final result.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;void main() {
  MicroSDCard card = MicroSDCard();
  MicroSDToUSBAdapter adapter = MicroSDToUSBAdapter(card);
  Laptop laptop = Laptop(adapter);
  laptop.importData();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This was an adapter, one of the most used patterns and also one of the easiest. In conclusion, the adapter design pattern is used when two incompatible classes cannot communicate, the adapter makes the communication possible. Let's go to the next one, the Bridge design pattern.&lt;/p&gt;

&lt;h2&gt;
  
  
  #5 Bridge
&lt;/h2&gt;

&lt;p&gt;The bridge was for me one of the more difficult to understand, so I'll do my best to explain it to you as easily as possible. At first, I thought it is similar to the Adapter, but it is a bit more complex because here we have an abstraction that depends upon another abstraction. By doing that you decouple an abstraction from its implementation completely and it can change independently. To keep it short, Bridge is like an Adapter but instead of concrete implementations, they are abstract. Let's make an example with a weapon that can have with gadgets.&lt;/p&gt;

&lt;p&gt;There are more types of weapons, like a handgun and an assault rifle. There are also plenty of gadgets, like a laser and a flashlight. Let's say we have abstract classes &lt;code&gt;Weapon&lt;/code&gt; and &lt;code&gt;Gadget&lt;/code&gt;, and concrete implementations like &lt;code&gt;Handgun&lt;/code&gt; and &lt;code&gt;Laser&lt;/code&gt;. Without the bridge pattern, what we would do is to create multiple classes, for each option possible, &lt;code&gt;FlashlightHandgun&lt;/code&gt;, &lt;code&gt;LaserHandgun&lt;/code&gt;, &lt;code&gt;LaserRifle&lt;/code&gt;, etc. But in real life, the gadget should be able to mount, work and unmount on any weapon. That is why &lt;code&gt;Weapon&lt;/code&gt; has a &lt;code&gt;Gadget&lt;/code&gt;, abstraction depends upon another abstraction and therefore they are decoupled and can change without any changes.&lt;br&gt;
Now here is the code example.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;abstract class Weapon {
  void pickup();
  void fire();
  void store();
}

abstract class Gadget {
  void mount();
  void use();
  void unmount();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here are those two abstractions, all we know is what they can do. Now let's take a look at the implementations.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Handgun extends Weapon {
  final Gadget _gadget;

  Handgun(this._gadget);

  @override
  void fire() {
    _gadget.use();
    print('Piu piu!');
  }

  @override
  void pickup() {
    _gadget.mount();
    print('Handgun in hands.');
  }

  @override
  void store() {
    _gadget.unmount();
    print('Handgun holstered.');
  }
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here we have &lt;code&gt;Handgun&lt;/code&gt;, an implementation of a &lt;code&gt;Weapon&lt;/code&gt; which depends on the &lt;code&gt;Gadget&lt;/code&gt; abstraction. That is the key difference compared to the Adapter. &lt;code&gt;Handgun&lt;/code&gt; can have any type of the &lt;code&gt;Gadget&lt;/code&gt;, now let's take a look at the &lt;code&gt;Gadget&lt;/code&gt; implementation.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Laser implements Gadget {
  @override
  void mount() =&amp;gt; print('Laser mounted.');

  @override
  void unmount() =&amp;gt; print('Laser unmounted.');

  @override
  void use() =&amp;gt; print('Laser pointing...');
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the final result:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;final Gadget laser = Laser();
final Weapon glock = Handgun(laser);

glock.pickup();
glock.fire();
glock.store();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is the output:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Laser mounted.
Handgun in hands.
Laser pointing...
Piu piu!
Laser unmounted.
Handgun holstered.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Honestly hope this pattern explanation was clear and easy to understand. If you are wondering where this pattern can be applied, here is an example. A repository is an abstraction, an interface to be exact and its implementation often can have two data sources, one is from the API, and the second one is from the database. Both the API and database are interfaces, so we have one abstraction which depends upon two other abstractions. If we want, we can easily add one more data source in the repository without touching other classes because abstraction depends upon another abstraction, that is the Bridge design pattern. Five patterns done, five to go. &lt;/p&gt;

&lt;p&gt;The next five patterns will be covered in Part II, there we shall see patterns like Decorator, Facade, Service Locator, Observer and State. Thank you for your time and attention, good luck with coding! :D&lt;/p&gt;

</description>
      <category>programming</category>
      <category>tutorial</category>
      <category>designpatterns</category>
      <category>cleancode</category>
    </item>
    <item>
      <title>How To Clean Code - Part II</title>
      <dc:creator>Filip Kisić</dc:creator>
      <pubDate>Tue, 25 Jan 2022 14:50:07 +0000</pubDate>
      <link>https://dev.to/biss/how-to-clean-code-part-ii-4757</link>
      <guid>https://dev.to/biss/how-to-clean-code-part-ii-4757</guid>
      <description>&lt;h2&gt;
  
  
  Intro
&lt;/h2&gt;

&lt;p&gt;Welcome to the next part of the clean code blog. In the first part, we were talking about naming, functions, comments, and formatting. In this part, we will talk about objects, data structures, unit testing, and classes. If you didn't read part one, I kindly recommend reading it because it is a great intro for what the clean code is and how to practice writing it.&lt;/p&gt;

&lt;h2&gt;
  
  
  Objects and Data Structures
&lt;/h2&gt;

&lt;h3&gt;
  
  
  TLDR
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Object hides its implementations, exposes its behaviors which manipulate the data inside&lt;/li&gt;
&lt;li&gt;Data structures expose their properties, has no behaviors&lt;/li&gt;
&lt;li&gt;Use objects when flexibility to add new object types is needed&lt;/li&gt;
&lt;li&gt;Use data structures when flexibility to add new behaviors is needed&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Back to the first days of our programming, our first usage of a data structure. It was introduced as a custom data type that can hold multiple different data types and that revealed a new way to manipulate data and to pass it through the program. It was an introduction to one of the most important concepts we can learn as software engineers, and that is a class. A class could also hold multiple different data types, but it also had functions or methods as it is said in the OOP world. We were taught that data structure has just properties while the class has properties and behaviors. Consider a toy car as a data structure, it has properties like color, material, size, etc., while a real car is a class that also has behaviors like turn on, rev, drive, park, turn off, etc. That is how we would describe the difference between them to a beginner. Let's describe it on a technical level. Here is an example:&lt;/p&gt;

&lt;h4&gt;
  
  
  Concrete Car
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class ToyCar {
    public String color;
    public int lenght;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Abstract Car
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public interface Car {    
    public String getColor() {...}
    public int getHorsepower() {...}
    public void drive() {...}
    public void rev() {...}
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The biggest and most important difference is their level of abstraction. &lt;code&gt;ToyCar&lt;/code&gt; exposes its implementation with public properties, while &lt;code&gt;Car&lt;/code&gt; hides its implementation with the interface. Why interface? Well, interface &lt;code&gt;Car&lt;/code&gt; represents behaviors of a data structure. When it implements &lt;code&gt;Car&lt;/code&gt; interface, it will become a full class, but the best part, as we still look at the &lt;code&gt;Car&lt;/code&gt;, we don't know its implementation, we don't know how do we drive a car because it depends on if it is automatic or a manual. We don't know how to rev and does it even rev because it is electric. A lot of questions to ask, but non to be concerned about. Here is what Uncle Bob says about the difference in the book &lt;em&gt;"Clean Code"&lt;/em&gt; :&lt;/p&gt;

&lt;p&gt;&lt;em&gt;"Objects hide their data behind abstractions and expose functions that operate on that data. Data structure expose their data and have no meaningful functions"&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Try to read it a couple of times. With an interface like a &lt;code&gt;Car&lt;/code&gt;, we can easily add a new class like &lt;code&gt;ElectricCar&lt;/code&gt; which implements the interface, and there we have a new object type, but if we want to add new behavior to a &lt;code&gt;Car&lt;/code&gt;, for example, &lt;code&gt;park()&lt;/code&gt;, we would have to define that in each class which implements the &lt;code&gt;Car&lt;/code&gt; interface. To make it short, it is easy to add a new object without changing a behavior, but hard to add new behavior. Data structures do the exact opposite, it is easy to add new behavior to an existing data structure, but hard to add a new data structure. In a conclusion, when the project requires flexibility to add new data types, use objects, when the project requires flexibility to add new behaviors, use data structures with procedures.&lt;/p&gt;

&lt;h2&gt;
  
  
  Error handling
&lt;/h2&gt;

&lt;h3&gt;
  
  
  TLDR
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Exceptions instead of returning codes&lt;/li&gt;
&lt;li&gt;Try-catch wrapping&lt;/li&gt;
&lt;li&gt;In the catch block, use defined and concrete classes&lt;/li&gt;
&lt;li&gt;Use unchecked exceptions rather than checked&lt;/li&gt;
&lt;li&gt;Don't return nor pass &lt;code&gt;null&lt;/code&gt; values&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Error happens, that's why it is important to know how to properly handle those errors. Sometimes, for precautions, big chunks of code are wrapped with error handling code and by that, code becomes hard to read. Error handling is very important, users can enter invalid input, API can be unreachable, or we simply cannot connect to a device. And because that is easily possible, we must know how to handle it right. If you come from the C or C++ world, at some point you probably saw a piece of code that returns the integer as an error code. While in some systems that is a standard, in the OOP world that is a bad practice, don't send error codes as integers. Instead, return an exception object. By returning the error code, when you call that function, the first thing you have to do is check if the result was an error. Checking is introducing if-else statements which can generate a lot of garbage code. Except that, everything has to be done manually, you have to know which function returns error codes, which one means what and that can be difficult to remember, and therefore it is possible to forget the error check and our code won't work as expected. Look at this example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void lockTheCar() {
    RemoteKey remoteKey = getKeyOutOfPocket();
    Integer result = remoteKey.lockTheCar();
    if (result == RemoteKey.OUT_OF_BATTERY) {
        logger.log("Remote key battery is empty...");
    } else if (result == RemoteKey.IR_NOT_WORKING) {
        logger.log("IR blaster is not working...");
    } else {
        blinkTheHazardLights();
    }      
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Quite messy, right? You have to check for every possible error code, and if in the future, the more is added, the more code to write for you. Let's see how it should be done:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void lockTheCar() {
    try {
        tryToLockTheCar();
    } catch (RemoteException e) {
        logger.log("Remote: " + e.toString());
    }
}

private void tryToLockTheCar() throws RemoteException {
    RemoteKey remoteKey = getKeyOutOfPocket();
    remoteKey.lockTheCar();
    blinkTheHazardLights();
}

public class RemoteKey {
    ...
    public void lockTheCar() {
        ...
        throw new RemoteException("Remote key battery is empty...");
        ...
        throw new RemoteException("IR blaster is not working...");
    }
    ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Easier to read, functions are separated and RemoteException is being thrown which makes this code clean and easy to understand. If there is a new place to throw an error, the catch block will catch it, there is no need to modify the code. Look one more time at the try-catch block above, it is short, it is wrapped only around the code which can throw the exception and the exception is concrete. Try to avoid using the Exception class in the catch block, the more concrete class is, the better. The next thing we are going to talk about is checked exceptions. If you don't know what checked exceptions are, here is a short explanation. Look at the function &lt;code&gt;tryToLockTheCar()&lt;/code&gt;, it has  &lt;code&gt;throws&lt;/code&gt; in the function signature and tells us which exceptions that function can throw. The benefits of using checked exceptions are readability and code won't compile if those exceptions aren't covered in the callers function. But there are more important flaws when using checked exceptions.&lt;/p&gt;

&lt;p&gt;Let's say we have 3 layers of application code, where level 1 is the lowest and level 3 is the highest. We want layers to communicate and work together, but they shouldn't know how other layers work. With checked exceptions, that isn't possible. If you define that level 1 throws &lt;code&gt;IOException&lt;/code&gt; and there is a &lt;code&gt;catch&lt;/code&gt; clause on level 3, level 2 also has to be changed, it also has to change its signature with the &lt;code&gt;throws&lt;/code&gt; word. This way, the Open-Closed principle is not done right, for change on the lower level, the higher level has to change too. Since we are talking about exceptions, we all can agree that &lt;code&gt;NullPointerException&lt;/code&gt; is one of the most common exceptions we came across so far. So just a short tip to avoid in the future as much as possible. Don't return &lt;code&gt;null&lt;/code&gt; values or even worse, don't pass them to functions. With that practice, there are fewer null checks to be done and therefore a smaller chance for you to not check some of the values that could be null. &lt;/p&gt;

&lt;p&gt;Thankfully, in more modern languages like Kotlin, Dart, etc. there are nullable and non-nullable types which helps us a lot with &lt;code&gt;null&lt;/code&gt; handling. If we follow these rules, error handling also becomes easy, readable and maintainable.&lt;/p&gt;

&lt;h2&gt;
  
  
  Unit test
&lt;/h2&gt;

&lt;h3&gt;
  
  
  TLDR
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;The Three Laws of TDD&lt;/li&gt;
&lt;li&gt;Clean tests, consistent quality&lt;/li&gt;
&lt;li&gt;F.I.R.S.T.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;All code above eventually ends up in the production code, so it is important to test the code. There is also another approach, test-driven development, where you write tests first and then write code that will make those tests pass. How do we know when our code is enough for the test to pass? There are three laws of test-driven development to guide you.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;You may not write production code until you have written a failing unit test.&lt;/li&gt;
&lt;li&gt;You may not write more of a unit test than is sufficient to fail, and not compiling is failing.&lt;/li&gt;
&lt;li&gt;You may not write more production code than is sufficient to pass the currently failing test.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If it is hard to understand those rules, let's go through them. The first law says that you have to write a failing test first and then write production code to make that test pass, nothing more, nothing less. By following the second law, your test code will be as short as possible, just enough to demonstrate the failure. The third law wants you to apply the second law to the production code. As soon as the code passes the test, that is it, no more to write, just refactoring. Here is a "refactored" version of three TDD laws:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Write NO production code except to pass a failing test&lt;/li&gt;
&lt;li&gt;Write only ENOUGH of a test to demonstrate a failure&lt;/li&gt;
&lt;li&gt;Write only ENOUGH production code to pass the test&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;By writing the tests, we make sure our code does what we want, and it is safe to push it to production. Following that practice, we write a lot of additional code, so we have to make sure tests are readable, easy to understand and maintain. As a function has to do ONE thing and ONE thing only, the test should demonstrate ONE case and ONE case only. For example,&lt;br&gt;
for the if clause, at least two tests have to be written for that. This way we keep our tests clean and code quality consistent. There is an acronym that can help you write clean code, and it is called F.I.R.S.T.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Fast - Tests should be run frequently, therefore we want them to execute fast.&lt;/li&gt;
&lt;li&gt;Independent - Every test should be able to run separately, no dependencies on other tests.&lt;/li&gt;
&lt;li&gt;Repeatable - Environments like localhost, QA, UAT or production, tests execute no matter which environment it is.&lt;/li&gt;
&lt;li&gt;Self-Validating - Test should ALWAYS be binary, pass or fail.&lt;/li&gt;
&lt;li&gt;Timely - Write test code just before production code, test functionality, then write production code.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Unit tests are equally important in the project as the production code, so take care of the tests you write. If you recently entered the world of software engineering, consider the unit test as a tool to check your code functionality, especially when a new feature is added, they can serve to test if everything else remains as it should. If TDD is something you're a fan of, read one more time The Three Laws of TDD, practice it and check how clean are they with the F.I.R.S.T. guidelines. Only like that, you'll make your test code maintainable and most importantly, clean.&lt;/p&gt;
&lt;h2&gt;
  
  
  Classes
&lt;/h2&gt;
&lt;h3&gt;
  
  
  TLDR
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Class organization (Make it readable as a newspaper article)&lt;/li&gt;
&lt;li&gt;Classes should be small, single responsibility principle&lt;/li&gt;
&lt;li&gt;Isolate from change, dependency inversion principle&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In the sections above, we talked about how to write good functions, but we didn't talk about the higher level of organization, where all those functions are, class files. Uncle Bob has a brilliant way to remember and check how a class should be written, it is called a stepdown rule. The stepdown rule helps the class to read like a newspaper article. That sentence will be the guiding thought for this section. Standard Java convention dictates that a class should begin with a variable list. On the top must be public static constants followed by private static variables and then private instance variables. Of course, we have to make sure our class is well encapsulated, make all variables as private as possible. What I mean by that is to start with a private access type and expose it only if necessary.&lt;/p&gt;

&lt;p&gt;Let's go back to the newspaper article, how long it usually is? It is one page long on average and yet it contains everything you need to know and nothing else, so it is straight to the point and focused. This is exactly how a class should be, short, straight to the point and focused on one topic. Uncle Bob says that the first rule of classes is that they should be small, and the second rule is that they should be smaller than that. What we prevent with that is making the class to concern about too much. Close to the top of the blog, we talked about names. In this case, with a name we define the responsibilities of a class, therefore if it is short, it will be easy to give it a name. A neat trick, right? Also, try to describe the class first, if there is "and" in the description, it is either too long or it has too many responsibilities. Same as functions should do ONE thing and ONE thing only, classes should have ONE responsibility and ONE responsibility only. That is the single responsibility principle.&lt;/p&gt;

&lt;p&gt;Except for the single responsibility principle, there is one more which we should look out for when we talk about classes and that is the Dependency Inversion Principle. As short as possible, it says that the class we write should depend upon abstractions, not on concrete details. We achieve that by minimizing coupling, because if we depend on the details, if any change is made, there is a probability that our code won't work anymore. Let's imagine we work on an application for a vehicle maintenance shop. An example of business logic:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class Maintenance {
  private final Car carToMaintain;

  public Maintenance(Car newCar) {
    this.carToMaintain = newCar;
  }
  ...
}
...
Car car = new Car();
Maintenance firstMaintenance = new Maintenance(car);
firstMaintenance.maintain();
firstMaintenance.clean();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above depends on Car class, and it can maintain and clean any car which is fine, but what when the shop we develop for expands its business and now it can maintain trucks as well. There is a problem now, we have to change the whole &lt;code&gt;Maintenance&lt;/code&gt; class and that is a red flag, that code is not written well. Let's try to fix that.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Vehicle {
  void setType(VehicleType type);
}

class Maintenance {
  private final Vehicle vehicleToMaintain;

  public Maintenance(Vehicle newVehicle) {
    this.vehicleToMaintain = newVehicle;
  }
...
}

...
Vehicle car = new Car();
car.setType(VehicleType.CAR);

Maintenance firstMaintenance = new Maintenance(car);

firstMaintenance.maintain();
firstMaintenance.clean();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The code above is a much better solution because it is flexible, it depends on abstractions, in this case on the interface &lt;code&gt;Vehicle&lt;/code&gt;. Now the shop can expand even more and maintain motorcycles, vans, anything. This type of isolation makes us safe from any new requirements and the change we have to do is minimal.&lt;/p&gt;

&lt;p&gt;Consider all this next time you create a class and even though you'll have to write more code at the beginning, in the long run, it will save a lot of time and effort to implement new features. Use a trick with describing a class before writing it, and you'll write short, readable classes with just ONE responsibility. Also, don't forget about the stepdown rule, make a class read like a newspaper article. With all that in mind, you and your colleagues will be grateful for it.&lt;/p&gt;

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

&lt;p&gt;There it is. These are all the principles about clean code which were covered in the book "Clean Code, A Handbook of Agile Software Craftsmanship" by Robert C. Martin. I hope you enjoyed it and learned something new or upgraded the existing knowledge. If you found this interesting, I recommend reading the book if you didn't already. By following these rules, we all make our passion for writing a code easier, cleaner, and of course more readable. I would like to hear your opinion on these principles so write them down in the comments. Thank you for reading this article.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>codequality</category>
      <category>softwarecraftsmanship</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>How  To Clean Code - Part I</title>
      <dc:creator>Filip Kisić</dc:creator>
      <pubDate>Fri, 14 Jan 2022 14:35:27 +0000</pubDate>
      <link>https://dev.to/biss/how-to-clean-code-part-i-250l</link>
      <guid>https://dev.to/biss/how-to-clean-code-part-i-250l</guid>
      <description>&lt;h2&gt;
  
  
  Intro
&lt;/h2&gt;

&lt;p&gt;Clean code principles... every professional software engineer should know about them and most importantly, follow them. Software engineering as a profession mentions the first time in 1963 while developing guidance and navigation systems for the Appolo missions, so it exists for a long time, almost 60 years. In that period a lot of problems were encountered and solved with various design patterns, conventions, and principles. So this blog serves as a review of those rules which can help our team and ourselves to be better software engineers. Everything which is mentioned here is inspired by the book &lt;em&gt;"Clean Code, A Handbook of Agile Software Craftsmanship"&lt;/em&gt; written by famous author Robert C. Martin aka Uncle Bob. The main thought through all coding sessions should be: "clean code should always read like well-written prose." by Grady Booch.&lt;/p&gt;




&lt;h2&gt;
  
  
  Naming
&lt;/h2&gt;

&lt;h4&gt;
  
  
  TLDR
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Use meaningful and intention revealing names in your code&lt;/li&gt;
&lt;li&gt;Short scope names should be short&lt;/li&gt;
&lt;li&gt;Large scope names can be longer but must be more descriptive&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Can you remember the days when you first started coding? Those "Hello world" and "Your name is" programs, well let's go a bit further and try to remember the first algorithm you wrote, an array sorting, or maybe find in the collection piece. Probably back then we weren't thinking much about our variable names and we were naming them like:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int a;
int xyz;
String s;
int[] a;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Sure, for short programs like those were, it could pass, but imagine using names as those in a big, complex codebase. You'll surely agree that it would be really hard to read and understand what is happening. There are cases where we can use short names like that, but we'll get to that quickly.&lt;br&gt;
Here is an example code from the early days:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public static void bubbleSort(int[] a) {
        boolean s = false;
        int t;
        while (!s) {
            s = true;
            for (int i = 0; i &amp;lt; a.length - 1; i++) {
                if (a[i] &amp;gt; a[i + 1]) {
                    t = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = t;
                    s = false;
                }
            }
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is a standard bubble sort algorithm that consumes an array and doesn't return anything. Take a look at the name of a variable, is it self-explanatory, do you know from the name what it represents?&lt;br&gt;
Now look at this code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public static void bubbleSort(int[] array) {
        boolean isSorted = false;
        int biggerValue;
        while (!isSorted) {
            isSorted = true;
            for (int i = 0; i &amp;lt; array.length - 1; i++) {
                if (array[i] &amp;gt; array[i + 1]) {
                    biggerValue = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = biggerValue;
                    isSorted = false;
                }
            }
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Much easier to understand, isn't it? Well, that is the reason why is it important to invest time in the naming. Meaningful and intention revealing names make code much easier to understand, like well-written prose. Another important rule is to name classes, objects, and variables using only nouns while functions should be verbs, like &lt;code&gt;bubbleSort()&lt;/code&gt; is a verb. Maybe you noticed the index variable in the for loop is just the letter &lt;code&gt;i&lt;/code&gt;, but that is fine because we are all used to it, and we know what &lt;code&gt;i&lt;/code&gt; stands for. Another reason why is so short name is that the scope of it is very short, only inside the loop. That brings me to another rule which says that the length of a variable name should depend on its scope. If the variable is more of local scope, its name should be short, but if it has a larger scope, a more descriptive name would be a better choice.  &lt;/p&gt;




&lt;h2&gt;
  
  
  Functions
&lt;/h2&gt;

&lt;h4&gt;
  
  
  TLDR
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Always separate functions by their level of abstraction&lt;/li&gt;
&lt;li&gt;The number of arguments shouldn't be more than 4&lt;/li&gt;
&lt;li&gt;It would be better to create functions for true and false cases instead of passing a bool as an argument&lt;/li&gt;
&lt;li&gt;If possible, functions should be around 4 lines long.&lt;/li&gt;
&lt;li&gt;The function should do ONE thing and ONE thing only&lt;/li&gt;
&lt;li&gt;The function should not have any side effects&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Again, let's remember the first days of our programming lessons. In those lessons, we were told to use functions when there is repeating code, to make it reusable. Let's google the definition and see the result, I found the following: "A function is a block of organized, reusable code that is used to perform a single, related action." So we will use that code a lot and that is why it is important to make it clean and readable. How to achieve that? Firstly, we should keep our functions short, according to Uncle Bob, 4 lines top. While that is ideal, it isn't written in the stone or compiler, so it can be a bit longer, but keep it as short as possible. What Uncle Bob wants to say with 4 lines tops functions is to extract the code from the functions to more short and simpler functions, but why? Look at the example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public RedirectView authenticateUserAndRedirectToMainPage(String username, String password) {
        Optional&amp;lt;User&amp;gt; user = Optional.empty();
        DataSource dataSource = DataSourceSingleton.getInstace();
        try (Connection connection = dataSource.getConnection();
             CallableStatement stmt = connection.prepareCall("authenticateUser")) {
            stmt.setString(1, email);
            stmt.setString(2, password);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    user = Optional.of(new User(
                            rs.getInt("ID"),
                            rs.getString("EMAIL"),
                            rs.getString("PASSWORD"),
                            rs.getBoolean("IS_ADMIN"))
                    );
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(DBUserRepository.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (user.isPresent()) {
            RedirectView redirectView = new RedirectView();
            redirectView.setUrl("http://www.stackoverflow.com");
            return redirectView;
        } else {
            throw new RuntimeException("User not found...");
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At first look, there is a lot to read, there are multiple levels of abstraction, exception management and function does more than one thing. All mentioned is red alarm...levels of abstraction, exceptions, and more just in one function. As school students, maybe we would say: "Oh, nice. All I need is in one function, staring at low a level and getting the final high-level result, amazing." Let's start refactoring the code and explain why step by step. The name of the function reveals that it does more than one thing, and it is not a good practice, function must do ONE thing and ONE thing only. After we create Optional of User, we work with the database by calling the stored procedure &lt;code&gt;"authenticateUser"&lt;/code&gt; and get the result if the user exists. We can agree that this is a low level of abstraction. One more thing to worry about is the try-catch block that surrounds the database access code. Let's solve the problem by extracting and refactoring the code. Before we start, just one note that we will focus on refactoring the &lt;code&gt;authenticateUserAndRedirectToMainPage&lt;/code&gt; function to keep it simple. Others will be ignored.&lt;/p&gt;

&lt;p&gt;The first step is to extract the try-catch block to function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    private Optional&amp;lt;User&amp;gt; authenticateUser(String username, String password) {
        DataSource dataSource = DataSourceSingleton.getInstace();
        try (Connection connection = dataSource.getConnection();
             CallableStatement stmt = connection.prepareCall("authenticateUser")) {
            stmt.setString(1, email);
            stmt.setString(2, password);
            try (ResultSet rs = stmt.executeQuery()) {
                if (rs.next()) {
                    return Optional.of(new User(
                            rs.getInt("ID"),
                            rs.getString("EMAIL"),
                            rs.getString("PASSWORD"),
                            rs.getBoolean("IS_ADMIN"))
                    );
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(DBUserRepository.class.getName()).log(Level.SEVERE, null, ex);
        }
        return Optional.empty();
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Great, first step done. A recommendation would be to extract this method to a new interface with an implementation class, for example, UserRepository. Now let's see how our code looks now.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public RedirectView authenticateUserAndRedirectToMainPage(String username, String password) {
        Optional&amp;lt;User&amp;gt; user = authenticateUser(username, password);
        if (user.isPresent()) {
            RedirectView redirectView = new RedirectView();
            redirectView.setUrl("http://www.stackoverflow.com");
            return redirectView;
        } else {
            throw new RuntimeException("User not found...");
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You will agree this is more pleasant to eyes. The next step would be to extract code inside the if clause.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    private RedirectView redirectToMainPage() {
        RedirectView redirectView = new RedirectView();
        redirectView.setUrl("http://www.stackoverflow.com");
        return redirectView;
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Nice, now our function looks like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public RedirectView authenticateUserAndRedirectToMainPage(String username, String password) {
        Optional&amp;lt;User&amp;gt; user = authenticateUser(username, password);
        if (user.isPresent()) {
            return redirectToMainPage();
        } else {
            throw new RuntimeException("User not found...");
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are getting close to the goal, two steps are done, two remaining. By now I hope we all got a little smile on our faces because of the progress. The last two steps would be to replace the if-else body with lambda since we use Optional and to rename the function. If we look at the feature we had to implement, it was logging the user into the application. Exactly that should be our final method name, &lt;code&gt;loginUser&lt;/code&gt;. If it is a bit confusing how is this good, because our function is doing two actions again, authentication and redirecting, well we have to merge them to make a feature. It is a higher level of abstraction, therefore more abstract naming and function body. The final result should look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public RedirectView loginUser(String username, String password) {
        return authenticateUser(username, password)
                .map(user -&amp;gt; redirectToMainPage())
                .orElseThrow(() -&amp;gt; new RuntimeException("User not found..."));
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We are done, let's make a short review. If you compare the first version of this function, before we did two things, now we do ONE and ONE only. Before, we mixed levels of abstraction, now we have one level of abstraction per function. Also, if you didn't notice, every function is one level of abstraction above the inner function. Before our code required concentration and time to figure out what is it doing, now we need a couple of seconds to read it and again, read it like well-written prose. Felling happy and satisfied, aren't you? It is in our nature to bring order to chaos. We haven't mentioned yet the number of arguments that are passed to function. According to Uncle Bob, as a number of lines, 4 tops. Of course, the ideal would be without arguments, but there are a lot of cases where that isn't possible. One more tip from Uncle Bob is to never send a boolean as an argument, but create two functions, one for true and one for a false case. Lastly, there is a rule that functions shouldn't have side effects. Maybe it isn't clear at first what it means, but think about it this way: Function has one purpose, we pass arguments to it if needed, function do its magic and either returns the result or void. Its magic shouldn't do anything with other parameters inside the class, just with the passed ones. If it changes anything else, it should be refactored.&lt;/p&gt;

&lt;p&gt;This section was a bit longer, but we covered a lot of important rules and what should be avoided while writing our code.&lt;/p&gt;




&lt;h2&gt;
  
  
  Comments
&lt;/h2&gt;

&lt;h3&gt;
  
  
  TLDR
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Avoid writing comments&lt;/li&gt;
&lt;li&gt;Make a code explain itself, then there is no need for comments&lt;/li&gt;
&lt;li&gt;A lot of comments is a sign of bad code&lt;/li&gt;
&lt;li&gt;Good comments: legal, todo, javadocs...&lt;/li&gt;
&lt;li&gt;Commented-out code is a sin&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The first and most important rule about comments is not to write them. Avoid them as much as possible. Think of writing a comment in the code like littering the street. Why? Let's again go back to school days, probably we would think comments are helpful because they describe what the code does and maybe keep the track of all changes made through the development. And partially, yes, we would find that helpful, to read a comment as a description of some complex algorithm, but when we write code as in the previous section, like well-written prose, comments are unnecessary. Code should be self-explanatory, do you agree? When we write functions that are concise, short, and well named, comments really are like litter on the street. So if you see lots of comments in the code, that is a badly written code. Even in the development process, avoid the comments, avoid them to log the changes, because most of the modern IDEs today have that integrated. IntelliJ for example has Git to show history, when it was edited, by whom, and much more. Also, avoid commenting out the code you don't use anymore because you think you might need it at some point, but probably you won't. Right, we talked about bad comments, but actually, there are some use cases where comments are a good practice. The first example is Javadoc comments. For instance, when we use an external library sometimes we need more details, for example, about the function we call. In IntelliJ by pressing Ctrl + left mouse click, it opens the code file where we can find Javadoc written by the author of a class. This is an example of how Javadocs look:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  /**
   * Reads single {@link CodeBook} from database specified by {@link StaticValue}
   *
   * @param staticValue value to load from database
   * @param &amp;lt;I&amp;gt;         {@link javax.persistence.Id} type
   * @param &amp;lt;T&amp;gt;         {@link javax.persistence.Entity} type
   * @return single {@link CodeBook}
   */
  &amp;lt;I extends Number, T extends CodeBook&amp;lt;I&amp;gt;&amp;gt; T load(StaticValue&amp;lt;I, T&amp;gt; staticValue);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The method above is generic, and you will agree the comment above is quite useful. The second example of a good comment is a legal comment, and it can usually be found in short form in the header. Common parts of those comments are licenses, copyrights, references to legal documents, and others. One more example we will talk about is TODO comments. It is fine to write them sometimes, as a note what should be done, and to mark it as unfinished code, so a reader can understand why is something written in the way it is and what will be written in the future. To find them, IDEs like IntelliJ have a special menu for TODO comments, so you can find them easily.&lt;/p&gt;




&lt;h2&gt;
  
  
  Formatting
&lt;/h2&gt;

&lt;h3&gt;
  
  
  TLDR
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;IDEs now do it for ourselves&lt;/li&gt;
&lt;li&gt;Its role is to make code easy to understand&lt;/li&gt;
&lt;li&gt;Each company or team have its own rules&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;This is a short topic because formatting depends on the company in which you work and your personal preferences, so there are no strict rules. Since there are no strict rules, every company has its formatting, its code style. Let's see two examples of different formatting.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    if (clause) {
        code_to_execute
    } else {
        code_to_execute
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Other style:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    if (clause) {
        code_to_execute
    } 
    else {
        code_to_execute
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Does this affect the performance? Thankfully no, but what is its role then? We are visual beings, as they say, you eat with your eyes first. The same rule applies to code. When you start to code and when you're reading the code above or in another file, the visual structure is very important. Its visual structure determines how easy the code is to read and understand. Have you ever seen minified CSS, HTML, or JS code? If you didn't google it. Imagine how hard it would be to understand what the website looks like...That is why the formatting is so important and why all IDEs today do it automatically for us. Those default IDE formatting settings are more than enough to use, even our team uses them daily as a formatting tool. And that is it, that is the role of formatting.&lt;/p&gt;




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

&lt;p&gt;All right, a lot of topics were covered above and these take practice learning and making them a habit. Try the approach in which you write the solution for the problem first and clean the code afterward. That way, you'll have the image in your head of what the solution should look like after you write it down. Remember to name your variables, constants, methods, and classes properly, make sure that your functions do ONE thing and ONE thing only and classes should have ONE responsibility and ONE responsibility only. As your code grows, so should you as a professional, therefore clean your code. We have a lot more to cover so stay tuned for the next part of this blog.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>codequality</category>
      <category>softwarecraftsmanship</category>
    </item>
  </channel>
</rss>
