<?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: BISS d.o.o.</title>
    <description>The latest articles on DEV Community by BISS d.o.o. (@biss).</description>
    <link>https://dev.to/biss</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%2Forganization%2Fprofile_image%2F5192%2F9e89acbb-f80c-445f-b766-42d00a6e1b9b.png</url>
      <title>DEV Community: BISS d.o.o.</title>
      <link>https://dev.to/biss</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/biss"/>
    <language>en</language>
    <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>
