<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jaycent Gunawan Ongris on Medium]]></title>
        <description><![CDATA[Stories by Jaycent Gunawan Ongris on Medium]]></description>
        <link>https://medium.com/@jaycentg?source=rss-3f05c5ac32c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*X0OR-bdggIABAGNKLgTTYA.jpeg</url>
            <title>Stories by Jaycent Gunawan Ongris on Medium</title>
            <link>https://medium.com/@jaycentg?source=rss-3f05c5ac32c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 17:12:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jaycentg/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SOLID for a Solid Software Product]]></title>
            <link>https://medium.com/@jaycentg/solid-for-a-solid-software-product-12d2af7a5ff8?source=rss-3f05c5ac32c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/12d2af7a5ff8</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jaycent Gunawan Ongris]]></dc:creator>
            <pubDate>Tue, 21 May 2024 07:33:07 GMT</pubDate>
            <atom:updated>2024-05-22T07:31:30.296Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*9NC16tqnBx4CX-P2.jpeg" /><figcaption>Source: <a href="https://medium.com/sarccom/is-your-code-solid-enough-part-1-fe1e2cb73894">Is your Code Solid Enough? — Part 1 | by Buyung Bahari | sarccom | Medium</a></figcaption></figure><p>In the software engineering realm, a properly-working code is simply not sufficient. Programmers have to ensure that their code is maintainable and scalable as well. As we all know, software requirements keep changing as time goes by. By making the software maintainable and scalable, it is easier for developers to adjust to the latest requirements and implement the new features, without having to alter most part of the existing source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*IcKuaWv_CjkqOlID.jpg" /><figcaption>Source: <a href="https://imgflip.com/i/7hd6d7">messed up code — Imgflip</a></figcaption></figure><p>You don’t want to add a single tiny part into your code and the entire program turns into a complete disaster, right?</p><p>To sum it up, what are the advantages of following software design principles in writing code? To create:</p><ul><li>Maintainable software</li><li>Scalable software</li><li>Reliable software</li></ul><p>There are some software principles and best practices we can follow to make our code better. However, let me start with the most important concept: Object-Oriented Design.</p><h3>Object-Oriented Design</h3><p>Object-Oriented Design or Object-Oriented Programming (OOP) is a software design paradigm centered around the concept of objects, which represent instances of classes that encapsulate both data and behavior. There are several key concepts of OOP, also known as pillars of OOP.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*sRa3ihP2nU2fv-oj.png" /><figcaption>Source: <a href="https://medium.com/swlh/the-four-pillars-of-object-oriented-programming-8ce8a26b32eb">The Four Pillars of Object Oriented Programming | by Karl Matthes | The Startup | Medium</a></figcaption></figure><h4>Inheritance</h4><p>This principle allows a new class to inherit attributes and methods from existing class. Therefore, this ensures better code readability, reusability, and establishes a natural hierarchical relationship (specifically, ‘is-a’ relationship) between classes. For example, we have a parent class Animal and a child class Dog. We can say that Dog is an Animal based on this ‘is-a’ relationship.</p><p>In the project, I implement inheritance principle by separating DaftarJadwalAdminService and DaftarJadwalUserService, and make them both inherit from one base DaftarJadwalService class, since they have the same method which only differ in implementation. A better explanation about this will be covered in Open/Closed Principle in the next section.</p><pre>class DaftarJadwalService:<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        raise NotImplementedError(&quot;Must be implemented by subclass&quot;)<br><br>class DaftarJadwalAdminService(DaftarJadwalService):<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        if date_start is None:<br>            return list(PreferensiJadwal.objects.all().values(&#39;datetime&#39;, &#39;is_available&#39;).<br>                        order_by(&#39;datetime&#39;).distinct())<br>        ...<br><br>class DaftarJadwalUserService(DaftarJadwalService):<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        if date_start is None or not isinstance(date_start, date):<br>            raise TypeError(&quot;Parameter harus berupa class Date&quot;)<br>        ...</pre><h4>Encapsulation</h4><p>This principle explains the idea of wrapping data and the methods that work on that data within one unit (in this case, class). By implementing this, we can restrict direct access to the components of the object and prevent accidental interference of the methods and data. The simplest way to implement this is by setting all attributes as private ones, as well as using setters and getters to do operations within a class. For example, in the Sesi class, we can refactor so that it looks like this.</p><pre>class Sesi:<br>    def __init__(self, waktu_mulai, waktu_selesai, pasien, konselor):<br>        self.__waktu_mulai = waktu_mulai<br>        self.__waktu_selesai = waktu_selesai<br>        self.__pasien = pasien<br>        self.__konselor = konselor<br><br>    def get_waktu_mulai(self):<br>        return self.__waktu_mulai<br><br>    def get_waktu_selesai(self):<br>        return self.__waktu_selesai<br><br>    def get_pasien(self):<br>        return self.__pasien<br><br>    def get_konselor(self):<br>        return self.__konselor<br><br>    def set_waktu_mulai(self, waktu_mulai):<br>        self.__waktu_mulai = waktu_mulai<br><br>    def set_waktu_selesai(self, waktu_selesai):<br>        self.__waktu_selesai = waktu_selesai<br><br>    def set_pasien(self, pasien):<br>        self.__pasien = pasien<br><br>    def set_konselor(self, konselor):<br>        self.__konselor = konselor<br><br>    def __str__(self):<br>        if self.__pasien is not None:<br>            return f&quot;Pasien: {self.__pasien}, Konselor: {self.__konselor}, {self.__waktu_mulai}-{self.__waktu_selesai}&quot;<br>        return f&quot;Konselor: {self.__konselor}, {self.__waktu_mulai}-{self.__waktu_selesai}&quot;<br><br>    def __eq__(self, other):<br>        if not isinstance(other, Sesi):<br>            return False<br>        return (self.__waktu_mulai == other.get_waktu_mulai() and<br>                self.__waktu_selesai == other.get_waktu_selesai() and<br>                self.__pasien == other.get_pasien() and<br>                self.__konselor == other.get_konselor())</pre><h4>Abstraction</h4><p>The core of this principle is information hiding. This principle can ‘simplify’ the code by hiding unnecessary details and showing only important features (the idea is pretty similar to facade pattern). Therefore, it will make the code way more clean and understandable. For example, there is an algorithm I created to find vacant counseling schedules based on counselors’ availability time and current client’s schedules. To hide the implementation of this algorithm, I created a class JadwalKosong where the algorithm will be implemented. To use this algorithm, we can simply instantiate the class and invoke the appropriate method.</p><pre>class JadwalKosong:<br>    def __init__(self, jadwal_konselor):<br>        # jadwal_konselor: (datetime, datetime) untuk menunjukkan<br>        # jadwal mulai dan selesai praktik konselor<br>        self.jadwal_konselor = jadwal_konselor<br>    <br>    def cari_jadwal_kosong(self, list_jadwal_terisi):<br>        # list_jadwal_terisi: (datetime, datetime)[] untuk menunjukkan<br>        # daftar jadwal yang sudah terisi/terjadwal<br>        if len(self.jadwal_konselor) == 0:<br>            raise ValueError(&quot;Tidak ada jadwal konselor&quot;)<br>        <br>        list_jadwal_kosong = []<br>        start_time = self.jadwal_konselor[0]<br>        end_time = self.jadwal_konselor[1]<br><br>        for slot in list_jadwal_terisi:<br>            slot_start = slot[0]<br>            slot_end = slot[1]<br>    ...<br><br>class KetersediaanJadwalService:<br>    def get_sesi_terjadwal_kosong(self, tanggal, konselor):<br>        ...       <br>        <br>        try:<br>            # jika tidak ada jadwal praktik akan melempar exception<br>            jadwal_kosong = JadwalKosong(jadwal_praktik).cari_jadwal_kosong(list_sesi_terjadwal)<br>            for jadwal_kosong_mulai, jadwal_kosong_selesai in jadwal_kosong:<br>                jam_mulai = jadwal_kosong_mulai.time()<br>                jam_selesai = jadwal_kosong_selesai.time()<br>                list_sesi_all.append(<br>                    Sesi(jam_mulai, jam_selesai, None, nama_konselor)<br>                )<br><br>            return sorted(list_sesi_all, key=lambda x: x.waktu_mulai)<br>        except ValueError:<br>            return []<br>        <br>        ...</pre><h4>Polymorphism</h4><p>The word “polymorphism” means “many forms”. To put it simply, this refers to methods/functions/operators with the same name that can be executed on many objects or classes. If we connect this to the concept of inheritance, this principle suggests that a child class can define its own unique behavior whilst sharing the same behavior with its parent class. The concrete example of this is the implementation of method overriding, like the one I have shown in the “Inheritance” section, as both child classes implement their own get_daftar_jadwal() method, overriding the one provided by the base class.</p><p>Another example of this would be the use of Python’s special (dunder) methods. Specifically, take a look at the previous example I have provided in the “Encapsulation” section. In that case, __eq__() method is implemented on Sesi class, which allows us to check the equality of two Sesi objects using = sign. If you wonder, where is the polymorphism? Do note that = sign can be used on so many objects, such as integers, strings, floats, booleans, lists, etc.</p><h3>SOLID Principle</h3><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*5iYzhNRt7yKyO664.png" /><figcaption>Source: <a href="https://blog.stackademic.com/solid-principles-explained-with-real-time-examples-e39d1c167ba5">SOLID Principles explained | Stackademic</a></figcaption></figure><p>I mention this in the title. Must be the important one, right?</p><p>SOLID is an acronym for the first five object-oriented design (OOD) principles by Robert C. Martin (Uncle Bob). It stands for Single Responsibility Principle (S), Open-closed Principle (O), Liskov Substitution Principle (L), Interface Segregation Principle (I), and Dependency Inversion Principle (D). We’ll take a look at these principles individually and elaborate the implementation in my project.</p><h4>Single Responsibility Principle (SRP)</h4><blockquote>A class should have one and only one reason to change, meaning that a class should have only one job.</blockquote><p>The principle is self-explaining. This principle aims to keep classes <strong>cohesive</strong>, which making them easier to understand, maintain, and reuse. For example, in the project (or MVC architecture, in general), we are dealing with a lot of view classes. To implement SRP, we have to ensure that each view class should only handle one operation. Take a look at this class below.</p><pre>class DeleteJadwalAPIView(APIView):<br>    def delete(self, request, waktu):<br>          try:<br>              obj_datetime = datetime.strptime(waktu, &quot;%Y-%m-%dT%H:%M:%SZ&quot;)<br>              service = HapusJadwalService()<br>              result = service.delete_jadwal(obj_datetime)<br>              if result[&#39;status&#39;]:<br>                  return Response({&quot;msg&quot;: result[&#39;msg&#39;]})<br>              else:<br>                  return Response({&quot;msg&quot;: result[&#39;msg&#39;]}, status=404)<br>          except ValueError:<br>              return Response({&quot;msg&quot;: &quot;Waktu yang dimasukkan invalid&quot;}, status=400)</pre><p>Notice that the class only handles one operation, i.e. DELETE. If this class changes, this means that there is a change in the requirement for DELETE operation. There are no other responsibilities handled by this class apart from DELETE. Other operations, such as using GET, POST, or PUT are handled in different classes. Hence, this one satisfies the SRP.</p><p>There are several advantages of implementing SRP, such as easier for developers to understand, debug, and modify the code, since each module has only single responsibility. The code is well-organized as well. Furthermore, it is easier for developers to create a more focused and independent tests.</p><h4>Open/Closed Principle (OCP)</h4><blockquote>Objects or entities should be open for extension but closed for modification.</blockquote><p>This principle means that a class should be extendable without having to modify the class itself. If we want to add a new feature that is pretty similar to the previous one we have before, we can just simply extend the base class without having to modify the existing code. For instance, my colleague in BKM User wants us to make an API to retrieve all available schedules for clients. I remember that I have created this kind of API before, but with a slight difference in the retrieval filtering. I decided to create a base abstract service class with a single method to be inherited by both concrete service classes.</p><pre>class DaftarJadwalService:<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        raise NotImplementedError(&quot;Must be implemented by subclass&quot;)<br><br>class DaftarJadwalAdminService(DaftarJadwalService):<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        if date_start is None:<br>            return list(PreferensiJadwal.objects.all().values(&#39;datetime&#39;, &#39;is_available&#39;).<br>                        order_by(&#39;datetime&#39;).distinct())<br>        ...<br><br>class DaftarJadwalUserService(DaftarJadwalService):<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        if date_start is None or not isinstance(date_start, date):<br>            raise TypeError(&quot;Parameter harus berupa class Date&quot;)<br>        ...</pre><p>If later there is a need to create another service that is pretty similar to DaftarJadwalService, we can just simply extend the class by inherit that class, so that the method will be inherited from the base class and add our implementation there. There is no need to modify the current implementation. Therefore, this base class is open for extension, but closed for modification. FYI, this is also an implementation of Strategy Pattern.</p><p>Similar to Single Responsibility Principle, the implementation of OCP also leads to a more well-structured and maintainable code. Besides that, it also increases flexibility in the code, since developers can easily add new features without having to modify existing code. In this project, if a new customized Daftar Jadwal Service is needed, we can simply define a new class with DaftarJadwalService as the parent class.</p><h4>Liskov Substitution Principle (LSP)</h4><blockquote>Let q(x) be a property provable about objects of x of type T. Then q(y) should be provable for objects y of type S where S is a subtype of T.</blockquote><p>Jeez, too math. Actually, this only suggests that every subclass should be substitutable for their base or parent class. The “substitutable” word means that objects of a superclass shall be replaceable with objects of its subclasses without leading to unexpected behavior.</p><p>Consider the previous code snippet in the Open/Closed Principle section above. We have DaftarJadwalService as the base class, as well as DaftarJadwalAdminService and DaftarJadwalUserService as the child classes. We can see that all classes only have one method, get_daftar_jadwal(self, date_start: date=None), with the same signatures as well. If we replace the superclass with the subclass, there are no issues should have been raised from the program, since the class is inherited from the superclass and the sole method in that class has the same signatures with the one in the superclass.</p><p>To explain the use of this principle clearly, take a look at this imaginative method which takes DaftarJadwalService as the parameter.</p><pre>def get_jadwal(service: DaftarJadwalService, date: date):<br>    return service.get_daftar_jadwal(date)</pre><p>According to LSP, we should be able to pass any subclasses of DaftarJadwalService without causing any problems. And yes, if we run the method, there are no errors, since the get_daftar_jadwal(date) method exists in all subclasses of DaftarJadwalService. Hence, LSP is satisfied as we are able to replace the superclass with the subclass.</p><p>Similar to Open/Closed Principle, implementation of LSP leads to a more flexible and extensible system with interchangeable components. It ensures that the child classes do not break the assumptions of clients in using the parent class. Therefore, it can maintain the program’s behavioral consistency. Additionally, it prevents unexpected runtime errors caused by the implementation of child classes.</p><h4>Interface Segregation Principle (ISP)</h4><blockquote>A client should never be forced to implement an interface that it doesn’t use, or clients shouldn’t be forced to depend on methods they do not use.</blockquote><p>This principle states that it is better to have smaller and focused interfaces rather than large and general-purpose ones. A class should not be forced to implement methods that it doesn’t need. For example, consider a class inherited from APIView base class below.</p><pre>class DaftarJadwalUserAPIView(APIView):<br>    def get(self, request):<br>        tanggal = request.query_params.get(&quot;date&quot;)<br>        if not tanggal:<br>            return Response({&quot;msg&quot;: &quot;Tidak ada tanggal input&quot;}, status=400)<br>        try:<br>            date = datetime.strptime(tanggal, &#39;%Y-%m-%d&#39;).date()<br>        except ValueError:<br>            return Response({&quot;msg&quot;: &quot;Tanggal input invalid&quot;}, status=400)<br>        <br>        service = DaftarJadwalUserService()<br>        result = service.get_daftar_jadwal(date)<br>        return Response(convert_to_datetime(result), status=200)</pre><p>The DaftarJadwalUserAPIView as a subclass of APIView class only implements the get() method, since it is the only method needed for this class. Therefore, the class only implements the method that it would use and thus making it a good example of code that aligns with ISP.</p><p>A bad example would incorporate all methods, i.e. get(), post(), patch(), delete(), and put() in that class, even though only the get() one that is needed. By providing all those methods, the ISP will be violated, since we force the client to implement and depend on methods they don’t use.</p><p>Just like the other principles, the implementation of ISP leads to a more well-structured code. Additionally, killing two birds with one stone, by implementing this, developers also reinforce the Single Responsibility Principle, as smaller and focused interfaces help to maintain a clear separation of concerns and responsibilities.</p><h4>Dependency Inversion Principle (DIP)</h4><blockquote>Entities must depend on abstractions, not on concretions. It states that the high-level module must not depend on the low-level module, but they should depend on abstractions.</blockquote><p>Let’s adhere the DRY principle by looking at the previous example in the Open/Closed Principle (and Liskov Substitution Principle) again. The DaftarJadwalService class is an abstract class (not a literal abstract class, but consider that as an “abstract class”), which its concrete implementations provided by DaftarJadwalAdminService and DaftarJadwalUserService. The same as well for get_jadwal() function, where it takes DaftarJadwalService as the parameter, not the concrete service class. This means that get_jadwal() function has been decoupled from the specific implementation and it depends only on DaftarJadwalService abstraction. Hence, all of them depend on the abstraction, which is the DaftarJadwalService.</p><p>Implementing DIP can lead to a loosely-coupled code, since this encourages modules to depend on abstractions rather than concrete implementations. Consequently, the code will become more modular.</p><h3>Don’t Repeat Yourself (DRY)</h3><p>The name of the principle says it all. This principle aims to minimize redundancy and improve maintainability of the code. In practice, we have to avoid code duplication in order to comply with this principle. You might have to do some refactoring actions to fix the code duplication, such as extract method, extract variable, etc. For the example, I have several test suites that rely on the same setUp method. Instead of copy-pasting the code of that method to every test suite, I define a base class which only contains setUp method and let other test suite classes that need the method to inherit the base class.</p><pre>class JadwalTestSetUp(TestCase):<br>    def setUp(self):<br>        jadwal1 = PreferensiJadwal.objects.create(<br>            datetime=datetime(2024, 4, 22, 8, 0, 0, tzinfo=timezone.utc)<br>        )<br>        jadwal2 = PreferensiJadwal.objects.create(<br>            datetime=datetime(2024, 4, 22, 12, 0, 0, tzinfo=timezone.utc) <br>        )<br>        jadwal3 = PreferensiJadwal.objects.create(<br>            datetime=datetime(2024, 4, 23, 8, 0, 0, tzinfo=timezone.utc)<br>        )<br>        ...<br><br>class DaftarJadwalTest(JadwalTestSetUp):<br>    def setUp(self):<br>        super().setUp()<br>        self.service = DaftarJadwalAdminService()<br><br>    def test_get_all(self):<br>        result = self.service.get_daftar_jadwal()<br>        self.assertEqual(result, convert_to_dict(self.all_jadwal))</pre><h3>Keep It Simple, Stupid (KISS)</h3><p>In software development, simplicity is one of the most important things. This principle promotes the importance of simplicity in software design, which leads to clean and minimalistic code. Therefore, it is easy to maintain the code. For example, take a look at the view class and its delete method below. We can say that this class satisfies KISS since the flow of the method is simple and straightforward: validate the input time, invoke the delete method from the service, and return the appropriate response. Besides that, this method (and class) only focuses on a single task without unnecessary complexity, making it easier to understand.</p><pre>class DeleteJadwalAPIView(APIView, MustAuthenticateAsAdminMixin):<br>    def delete(self, request, waktu):<br>        # format zulu/iso8601<br>        # example: 2024-04-26T12:34:56Z<br>        try:<br>            obj_datetime = datetime.strptime(waktu, &quot;%Y-%m-%dT%H:%M:%SZ&quot;)<br>            service = HapusJadwalService()<br>            result = service.delete_jadwal(obj_datetime)<br>            if result[&#39;status&#39;]:<br>                return Response({&quot;msg&quot;: result[&#39;msg&#39;]})<br>            else:<br>                return Response({&quot;msg&quot;: result[&#39;msg&#39;]}, status=404)<br>        except ValueError:<br>            return Response({&quot;msg&quot;: &quot;Waktu yang dimasukkan invalid&quot;}, status=400)</pre><h3>You Aren’t Gonna Need It (YAGNI)</h3><p>YAGNI is a principle which states that features should be added when required only. By doing this, developers can save up time from creating unimportant components that may not be necessary and can eventually hinder the development process. For example, take a look at this KomentarArtikel model, which contains updated_at field. However, there is no PBI about editing a comment. Therefore, this field is actually not necessary and can be deleted. We can’t just rely on the assumption that we will use that later :))</p><pre>class KomentarArtikel(models.Model):<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    pengomentar = models.ForeignKey(User, on_delete=models.CASCADE)<br>    konten = models.TextField()<br>    artikel = models.ForeignKey(Artikel, on_delete=models.CASCADE, related_name=&#39;komentar_artikel&#39;)<br>    created_at = models.DateTimeField(default=timezone.now)<br>    updated_at = models.DateTimeField()<br>    is_active = models.BooleanField(default=True)</pre><h3>Law of Demeter</h3><p>This principle also known as the principle of least knowledge. By implementing this, we encourage encapsulation and loose coupling by restricting the interaction between objects. To put it simply, a method in an object should only invoke the methods of itself (defined in the same class), its parameters, objects it creates, and its direct component objects. Below are some examples that comply with this principle.</p><pre># a method invokesanother method in the same class<br>class KetersediaanJadwalService:<br>    def get_sesi_terjadwal_kosong(self, tanggal, konselor):<br>        if not tanggal or not konselor:<br>            raise TypeError(&quot;Tidak bisa None&quot;)<br>        <br>        if type(tanggal) is not str or type(konselor) is not str:<br>            raise TypeError(&quot;Salah tipe input&quot;)<br><br>        sesi_terjadwal_all = SesiKonseling.objects.filter(tanggal_konseling=tanggal).filter(konselor=konselor).filter(is_dibatalkan=False)<br>        ...<br>    <br>    def get_sesi_terjadwal_kosong_all_konselor(self, tanggal):<br>        konselor_all = Konselor.objects.all()<br>        jadwal_all = []<br>        for konselor in konselor_all:<br>            # calling another method in the same class<br>            jadwal_all.extend(self.get_sesi_terjadwal_kosong(tanggal, str(konselor.id)))<br>        <br>        return sorted(jadwal_all, key=lambda x: x.waktu_mulai)</pre><pre>class DaftarJadwalAdminService(DaftarJadwalService):<br>    &quot;&quot;&quot;<br>    Service ini untuk melihat daftar jadwal yang available sesuai dengan kebutuhan admin.<br>    &quot;&quot;&quot;<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        if date_start is None:<br>            return list(PreferensiJadwal.objects.all().values(&#39;datetime&#39;, &#39;is_available&#39;).<br>                        order_by(&#39;datetime&#39;).distinct())<br>        <br>        if not isinstance(date_start, date): <br>            raise TypeError(&quot;Parameter harus berupa class Date&quot;)<br>        <br>        # calling method of the parameter date_start __add__() method<br>        date_end = date_start + timedelta(days=7)<br><br>        return list(PreferensiJadwal.objects.filter(datetime__date__range=(date_start, date_end)).<br>                    values(&#39;datetime&#39;, &#39;is_available&#39;).order_by(&#39;datetime&#39;).distinct())</pre><pre>class DaftarJadwalUserAPIView(APIView, MustAuthenticateAsUserMixin):<br>    def get(self, request):<br>        # format: YYYY-MM-DD<br>        tanggal = request.query_params.get(&quot;date&quot;)<br>        if not tanggal:<br>            return Response({&quot;msg&quot;: &quot;Tidak ada tanggal input&quot;}, status=400)<br>        try:<br>            date = datetime.strptime(tanggal, &#39;%Y-%m-%d&#39;).date()<br>        except ValueError:<br>            return Response({&quot;msg&quot;: &quot;Tanggal input invalid&quot;}, status=400)<br>        <br>        # instantiate an object<br>        service = DaftarJadwalUserService()<br>        # invoke the method<br>        result = service.get_daftar_jadwal(date)<br>        return Response(convert_to_datetime(result), status=200)</pre><pre>class DaftarJadwalService:<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        raise NotImplementedError(&quot;Must be implemented by subclass&quot;)<br><br>class DaftarJadwalAdminService(DaftarJadwalService):<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        if date_start is None:<br>            return list(PreferensiJadwal.objects.all().values(&#39;datetime&#39;, &#39;is_available&#39;).<br>                        order_by(&#39;datetime&#39;).distinct())<br>        ...<br><br>class DaftarJadwalUserService(DaftarJadwalService):<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        if date_start is None or not isinstance(date_start, date):<br>            raise TypeError(&quot;Parameter harus berupa class Date&quot;)<br>        ...<br><br>def get_jadwal(service: DaftarJadwalService, date: date):<br>    # invoking the method of direct component<br>    return service.get_daftar_jadwal(date)</pre><h3>Project Structure</h3><p>Project structure is pretty important to consider. A well-organized project structure can increase the maintainability and readability of the overall project. It is easier to navigate in a well-structured project directory. For example, since we separate typical views in Python into services and views (controllers), the best practice is by putting service files into a services folder and view files into a views folder. The same as well for tests and serializers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*1-uPfSucrlsadQCEgGIZ4g.png" /></figure><h3>PEP-8</h3><p>Naming conventions may seem trivial, but actually it plays a crucial role in maintaining the quality, readability, and consistency of a codebase. To maintain this, many tools can be used in Python, such as PyLint, flake8, or even SonarQube. Below are some examples of the implementation of PEP-8.</p><pre># class name must use CamelCase<br>class DaftarJadwalAPIView(APIView, MustAuthenticateAsAdminMixin):<br>    def get(self, request):<br>        # variables must use snake_case<br>        query = request.query_params.get(&quot;q&quot;, None)<br>        service = DaftarJadwalAdminService()<br>        if not query:<br>            # methods must use snake_case<br>            result = service.get_daftar_jadwal()<br>            return Response(PreferensiJadwalSerializer(result, many=True).data)<br>        try:<br>            date = datetime.strptime(query, &#39;%Y-%m-%d&#39;).date()<br>        except ValueError:<br>            return Response({&quot;msg&quot;: &quot;Tanggal input invalid&quot;}, status=400)<br>        <br>        result = service.get_daftar_jadwal(date)<br>        return Response(PreferensiJadwalSerializer(result, many=True).data)</pre><h3>Benefits</h3><p>After applying all those principles and best practices, there are several benefits that me and my colleagues feel:</p><h4>Reducing the number of merge conflicts</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*ztBLFUM2bLOpmpit" /><figcaption>Source: <a href="https://www.reddit.com/r/ProgrammerHumor/comments/u5pyji/incoming_flood_of_merge_conflicts/">Incoming flood of merge conflicts : r/ProgrammerHumor (reddit.com)</a></figcaption></figure><p>By doing modularization and maintaining a good project structure, it is easier to manage and isolate changes to specific parts of the codebase, which eventually minimizes overlap of work between team members. This approach helps developers to work on different parts of the project without interfering with each other’s work. Therefore, the likelihood of overlapping changes and merge conflicts is reduced.</p><h4>Easy to do code reviews</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*dUXlB0wGq0z-5Gk9" /><figcaption>Source: <a href="https://www.reddit.com/r/ProgrammerHumor/comments/mtocyp/there_is_no_naming_convention_in_hell/">There is no naming convention in hell : r/ProgrammerHumor (reddit.com)</a></figcaption></figure><p>By using a consistent naming convention, it is easier for code reviewers to understand the functionality of different parts of the code quickly. Consistent naming helps reviewers to identify the roles of variables, functions, classes, and modules without having to delve deeply into the code, thus speeding up the review process. Furthermore, this also makes debugging easier.</p><h4>Improved onboarding</h4><p>My team consists of two smaller teams, BKM Admin and BKM User. Each team has its own repository and at the end of the project, the repositories will be merged. By maintaining a good project structure and using a consistent naming convention, it is easier to adapt to other team’s codebase. This approach simplifies the process for new developers to understand and work with different parts of the project, thus facilitating a better collaboration between teams.</p><h3>References</h3><p><a href="https://www.linkedin.com/pulse/how-software-engineering-principles-help-you-build-better-stefan-elie/">(4) How Software Engineering Principles Help You Build Better Software | LinkedIn</a></p><p><a href="https://www.digitalocean.com/community/conceptual-articles/s-o-l-i-d-the-first-five-principles-of-object-oriented-design">SOLID: The First 5 Principles of Object Oriented Design | DigitalOcean</a></p><p><a href="https://www.linkedin.com/pulse/applying-solid-principles-django-real-world-examples-fa-alfard-uqhbf/">(5) Applying SOLID Principles in Django: Real-World Examples | LinkedIn</a></p><p><a href="https://github.com/hamedasgari20/Python-Django-FastAPI-advanced-topics?tab=readme-ov-file#solid-principles">hamedasgari20/Python-Django-FastAPI-advanced-topics: Python and Django advanced topics (github.com)</a></p><p><a href="https://medium.com/@ramdhas/4-interface-segregation-principle-isp-solid-principle-39e477bae2e3">4. Interface Segregation Principle (ISP): SOLID Principle | by Ramdhas | Medium</a></p><p><a href="https://www.linkedin.com/pulse/mastering-solid-principles-python-understanding-inversion-jafari">Mastering SOLID Principles in Python: Understanding Dependency Inversion Principle (linkedin.com)</a></p><p><a href="https://www.linkedin.com/advice/1/what-benefits-applying-single-responsibility-principle">How the Single Responsibility Principle Improves Your Code (linkedin.com)</a></p><p><a href="https://www.ggorantala.dev/srp-advantages-and-disadvantages/">Single Responsibility Principle: Strengths and Weaknesses (ggorantala.dev)</a></p><p><a href="https://www.linkedin.com/pulse/open-closed-principle-ocp-frontend-prithveesh-goel">Open-Closed Principle (OCP) in Frontend (linkedin.com)</a></p><p><a href="https://www.linkedin.com/pulse/liskov-substitution-principle-software-design-sanjoy-kumar-malik">Liskov Substitution Principle in Software Design (linkedin.com)</a></p><p><a href="https://www.linkedin.com/pulse/interface-segregation-principle-software-design-sanjoy-kumar-malik">Interface Segregation Principle in Software Design (linkedin.com)</a></p><p><a href="https://dev.to/tkarropoulos/the-power-of-dependency-inversion-principle-dip-in-software-development-4klk">The Power of Dependency Inversion Principle (DIP) in Software Development — DEV Community</a></p><p><a href="https://www.w3schools.com/python/python_polymorphism.asp">Python Polymorphism</a></p><p><a href="https://www.linkedin.com/pulse/embracing-simplicity-kiss-principle-django-web-development-sibin-m-s/">(16) Embracing Simplicity: The KISS Principle in Django Web Development | LinkedIn</a></p><p><a href="https://www.techtarget.com/whatis/definition/You-arent-gonna-need-it">What is YAGNI principle (You Aren’t Gonna Need It)? | Definition from TechTarget</a></p><p><a href="https://pythonislove.com/the-law-of-demeter-in-python">The Law of Demeter in Python (pythonislove.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12d2af7a5ff8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sentry: The Guardian of theCode]]></title>
            <link>https://medium.com/@jaycentg/sentry-the-guardian-of-thecode-93daae7dded8?source=rss-3f05c5ac32c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/93daae7dded8</guid>
            <category><![CDATA[error-monitoring]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[sentry]]></category>
            <category><![CDATA[monitoring-software]]></category>
            <dc:creator><![CDATA[Jaycent Gunawan Ongris]]></dc:creator>
            <pubDate>Sat, 27 Apr 2024 17:06:20 GMT</pubDate>
            <atom:updated>2024-05-22T09:39:54.474Z</atom:updated>
            <content:encoded><![CDATA[<h3>Sentry: The Guardian of the Code</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V75hR-lw_HDJkvQv.png" /><figcaption>Source: <a href="https://blog.sentry.io/sentry-releases-for-bitbucket/">Three Steps to Better Error Monitoring with Sentry Releases for Bitbucket | Product Blog • Sentry</a></figcaption></figure><p>Have you ever heard about monitoring tools before? No? Me neither. This is my first time exploring about platform and error monitoring tools. In a nutshell, a software monitoring tool is a software which we can connect to our application and it can provide lots of useful information regarding the condition of our application. Besides, these tools also provide alerting system, which means that we can be notified if something happens in our application.</p><p>Specifically, an error monitoring tool is a software which can log the errors, exceptions, and crashes that occur within our application. Meanwhile, a platform monitoring tool is a software designed to track and analyze the performance and health of an entire software platform or even infrastructure.</p><p>Thankfully, we got these two important features in a single application: Sentry.</p><h3>Sentry</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*fxWVaKlRPdyoU2vq.png" /><figcaption>Source: <a href="https://www.drupal.org/project/sentry_io">Sentry.io | Drupal.org</a></figcaption></figure><p>According to their GitHub, Sentry is a developer-first error tracking and performance monitoring platform that helps developers see what actually matters, solve quicker, and learn continuously about their applications. It provides lots of useful features, such as error monitoring, performance monitoring, session replay, and code coverage. However, we will be only focusing on error and platform performance monitoring.</p><h4>Setting up</h4><p>To begin using Sentry, visit the <a href="https://sentry.io/auth/login/">website</a> and sign in to the application. There are several methods you can use to sign in to the application. I will sign in using GitHub. You can create a new account if you want, though. After signing in, you will be given a free 14-day trial account. Use it wisely! :-D</p><p>You can begin setting up the tool by providing information regarding the project you want to monitor. In this case, I will use Django, so I will pick Django in this page below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P9lqaLBXVpV19VYGAq2xjQ.png" /><figcaption>Page after getting logged in</figcaption></figure><p>We can skip the onboarding and directly create a new project in the main dashboard After that, it will provide instructions on how to configure Sentry on Django. We have to install the sentry-sdk on Python by executing this command: pip install --upgrade &#39;sentry-sdk[django]&#39;. Next, we have to add these settings in the settings.py file (or in my case, base.py). Note that the dsn variable is not the same for each project. Hence, make sure to copy the correct one from the instruction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*UUOIypzCCN8HaQpb4TvQTg.png" /><figcaption>Sentry set up configuration in settings.py or base.py</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9IOk-s2Gdo64vxZTwoPLQ.png" /><figcaption>Sentry project set up</figcaption></figure><p>After that, Sentry is successfully being set up and it is ready to be used. The dashboard will look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gr5gHVA6GYskwP4KtyFHYw.png" /></figure><p>Sentry is currently waiting for events and ready to capture errors.</p><h4>Unhandled exceptions</h4><p>By default, Sentry will catch all unhandled exceptions and display it on the dashboard as issues. However, in our application, we have already handled all exceptions (I hope so! 😅) that we thought may be raised from the application. To demonstrate the capability of Sentry, I add this one trivial line which raises ZeroDivisionError in DeleteJadwalAPIView controller class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*cG5jlA9eAE-u2ONyWGhjnQ.png" /><figcaption>Adding 1/0 to raise an exception</figcaption></figure><p>The next thing is to hit the API and see the result in Sentry’s dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i94q04T_c3KyXTKUY4JSyA.png" /><figcaption>Using Postman to test the API</figcaption></figure><p>Below is the issue displayed on Sentry’s dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDs06Gavp2vjkIEZ5fBI6A.png" /></figure><p>To delve deep into the issue, we can click the issue and see the information provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2CN25HRvYJ1KqY9AQzsLCw.png" /></figure><p>As we can see, detailed information is provided by the platform, such as the API URL, server name, browser, runtime, the line that causes the error, the breadcrumbs (history of what being called if the API is hit). We can analyze that to learn how the error can happen.</p><p>The feature of Sentry in catching unhandled exception is very beneficial for developers to identify problems in their codebases as soon as possible and therefore, preventing these problems from happening in the near future again. Developers sometimes may not realize that there are still unhandled exceptions in their code, so this is where Sentry comes in handy :)</p><h4>Handled exceptions</h4><p>By default, handled exceptions are not displayed in the Sentry’s dashboard. However, if we want to display them, we can modify the code. Take a look at the example below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*jnU_12gfGS39CCoxm_W7Rg.png" /></figure><p>We can add sentry_sdk.capture_exception(err) in the except block. By doing this, the handled exception will be captured and it is later displayed in the dashboard. Don’t forget to import the package by providing this code import sentry_sdk before using it. The dashboard will now look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8VoekEZn7Rwo6ItRcDHg_A.png" /></figure><p>The same as unhandled exception, you can click on the error to get a detailed information regarding the error. The information is pretty similar to the unhandled ones, but this time the handled is set to true.</p><h4>Performance monitoring</h4><p>The dashboard of performance page looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jlBF32zNuxoCEaNaFSQ5Qw.png" /></figure><p>As we can see, there is a panel which contains history of API call (transaction) at the bottom of the page. Besides that, we can also see the most time-consuming queries, transaction per minute, failure rate, etc. Unfortunately, since I only inspect the dashboard for testing and demonstration purposes, we can’t find anything insightful from this dashboard. After being used for some time, it is obvious that we can draw some insights from the dashboard and utilize them to increase users’ experience in using the application.</p><p>Perhaps you are confused with the most time-consuming queries section, since it does not involve tables related to our models. Actually, Silk is the library I use for profiling purposes. So, it displays information regarding the API request details. The process of inserting the information intercepted from the request to the database apparently takes a longer time than executing the query related to the models itself 😅</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2eLswNvrrjzRyK-psjgOA.png" /></figure><p>We can see in which APIs this query is being called and the average duration of the query calls.</p><p>FYI, for query profiling, I have already covered it in another article using Silk library. Kindly check it out <a href="https://medium.com/@jaycentg/get-rid-of-slow-performance-with-this-no-clickbait-9054b51ae8f5">here</a> :-D</p><p>Meanwhile, the detail of each API transaction can be accessed by clicking the API name, such as GET /api/konseling/jadwal. You will get a detailed information regarding the duration, events, issues, failure rate, and many more. The dashboard looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y9CgugtymAjuYscRk4uAvw.png" /></figure><p>Besides that, you can also get a more in-depth breakdown on the duration if you click on the ‘Aggregate Spans’ tab in the menu bar. You can see the duration of each event, visualized on an interactive graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YlySFrm7dhxVj8h_gq8HKg.png" /></figure><p>Based on the graph above, we can see that the most time spent is on the database connection, whereas database transactions only ranged from approximately 50 to 100 ms.</p><p>We can utilize this to fix the performance of the application and give users a better experience in using it. But, obviously, I don’t want to check Sentry every time an API is being called to check its performance. How do I get informed when something related to the performance is not right? Let me introduce you to a new fella, the alerting system of Sentry.</p><h4>Alerting in Sentry</h4><p>This is simply one of the most important features we can get in Sentry. With this alerting system, we can be notified if something happens to the application. The alerting panel looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dg8Y9UzqJ_IYsGHm01f8Lw.png" /></figure><p>In the example, a notification will be sent if a new issue or error is raised. By default, the notification is sent to email, but you can customize it in the settings page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udhAtWJOYqJfvOCaL3C6QA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*irzchpiMfnRTJk0Rq0o-xw.png" /><figcaption>Notifications sent to email</figcaption></figure><p>Furthermore, if we click on the alert rule, we can see the problem that causes the alerting system to send alert notification. We can see how many alerts being triggered as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXWakbWC7Llh0aXGCJK-8Q.png" /></figure><p>We can determine certain conditions which can trigger the alert notification in the ‘Create Alert’ page. You can customize the alert based on your preferences.</p><p>Specifically, in this project, I’m focusing on the overall performance of this application. I want to create an alert if the average transaction duration is increasing by 80% from the previous day’s average transaction duration. I can set that issue as the critical condition. However, I also want to get a warning notification if the average transaction duration is increasing by 20%. The rules look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*r9sXJkunf6wdFkECEDTmvQ.png" /></figure><p>Below is the summary of the rules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*Sy27Cq48Z-2bYLNZRG7XmA.png" /></figure><p>The increasing transaction duration time may indicate there is something wrong in the application. Therefore, by identifying this quickly, we can take some actions to restore the performance back. For example, increasing load by users can also increase the transaction duration time. Hence, proper load balancing and scaling actions should be done to overcome this problem.</p><p>By implementing this alerting system, we can maintain the performance of our application better :)</p><h3>How Sentry can be useful for the project?</h3><p>Sentry’s features, like error and performance monitoring (and alerting) are really useful for keeping developers informed about the condition of the application whenever something goes wrong, like these problems below.</p><h4>Database Operational Error</h4><p>For staging and development production, we use Supabase to host our database. Unfortunately, since we are using the free tier version, there’s a limitation on the number of the client connections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*uWJ-6m7sCjIo5YCepKxUuA.png" /><figcaption>Source: <a href="https://supabase.com/docs/guides/database/connecting-to-postgres">Connecting to your database | Supabase Docs</a></figcaption></figure><p>However, we didn’t realize this limitation. Thankfully, Sentry notified us through email that the connection to the database had been terminated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHKRxegfq8hCoSVml1Se7Q.png" /></figure><p>After inspecting the issue, we realized that it was the maximum client connections error raised by Supabase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NW0Gu10xXl79p32wCLCIfg.png" /></figure><p>To fix this, we reduced the number of active connections to the instance at the same time, and thankfully, the problem was solved. If it weren’t for Sentry, our staging environment might have been down for days without anyone noticing :)</p><h4>Slow DB Query</h4><p>We definitely can’t monitor the performance of the application all the time. This is where Sentry’s alerting feature comes in handy. Sentry can notify us if there is a performance drop in our application, such as slow database query problem.</p><p>Several days ago, I received a notification via email indicating a drop in the application’s performance. Specifically, it highlighted an endpoint where the database querying time had slowed down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTg2I1ZZd_8PryKDQDwSuw.png" /></figure><p>After inspecting the details about the issue, I realized the endpoint was the GET api/artikel/get-daftar-artikel. It took approximately about 38 seconds to retrieve the data about articles💀</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ttVOgy3WFMA000JJp-TP8g.png" /></figure><p>Took quite a while until I realized that gambar_sampul attribute was the culprit. The gambar_sampul column stores base64-encoded cover images of each article. One thing that we didn’t realize was that a base64-encoded file can increase the file size by approximately 33%. Hence, the retrieval was very slow because it retrieved large amounts of data. Coupled with the limited bandwidth provided by the Supabase free tier plan, it further slowed down the retrieval time even more.</p><p>The only improvement we could make was to compress the size of the images uploaded by users in the front-end service. We set the maximum size of the raw image to 300 KB after compression.</p><pre>import imageCompression from &#39;browser-image-compression&#39;;<br><br>export const compressImage = async (file: File) =&gt; {<br>  const options = {<br>    maxSizeMB: 0.3,<br>    maxWidthOrHeight: 1920,<br>    useWebWorker: true,<br>  };<br>  try {<br>    const compressedFile = await imageCompression(file, options);<br>    return compressedFile;<br>  } catch (error) {<br>    console.error(error);<br>  }<br>};</pre><p>Hopefully, implementing this compression technique and utilizing a decent instance for the production server can improve the performance of the API in general.</p><h3>References</h3><p><a href="https://github.com/getsentry/sentry">GitHub — getsentry/sentry: Developer-first error tracking and performance monitoring</a></p><p><a href="https://bharatkalluri.com/posts/base64-size-increase-explanation">Why is a base 64 encoded file 33% larger than the original? | Bharat Kalluri</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93daae7dded8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UI/UX: The Deadly Duo of Digital Design]]></title>
            <link>https://medium.com/@jaycentg/ui-ux-the-deadly-duo-of-digital-design-d1cc6362397e?source=rss-3f05c5ac32c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1cc6362397e</guid>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[user-interface]]></category>
            <dc:creator><![CDATA[Jaycent Gunawan Ongris]]></dc:creator>
            <pubDate>Sat, 20 Apr 2024 07:35:56 GMT</pubDate>
            <atom:updated>2024-05-12T06:04:01.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*j8MAVlLuPNnH-oBP" /><figcaption>Source: <a href="https://uxplanet.org/going-all-buzzfeed-a-ux-list-of-memes-738ce7d8250c">Going all “buzzfeed”, a UX list of memes | by Luísa Quinn | UX Planet</a></figcaption></figure><p>In digital product design, UI/UX is a common thing to hear. Most people use UI and UX interchangeably, but they are different, actually. User Interface (UI) refers to the interactivity and look of the product, whereas User Experience (UX) refers to user’s overall experience in using the product. UI is just the tip of the iceberg!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*l2U8saMayfYFx-zG.jpg" /><figcaption>Source: <a href="https://openclassrooms.com/en/courses/4556206-design-the-visual-side-of-experiences-ui-design/4556213-understand-the-world-of-ux-vs-ui">Understand the world of UX vs. UI — Design the visual side of experiences (UI design) — OpenClassrooms</a></figcaption></figure><p>In order to ensure that users have a good experience in using the application, designers have to follow some sets of principles to make a user-friendly design. I will explain some important principles in UI/UX design in this article.</p><h3>Nielsen and Molich’s 10 Usability Heuristics</h3><p>Jakob Nielsen and Rolf Molich proposed 10 guidelines to help designers develop UI. It is called <em>heuristics</em> because the guidelines are general, not specific ones. Below are the guidelines and implementations in my team’s project.</p><h4>Visibility of system status</h4><p>By applying this principle, we have to keep users informed about what’s currently happening in the application. In the project, we implement this by providing a loading spinner whenever the data is still being fetched.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbFi_gjgVFwv0xohLVoR5g.png" /><figcaption>Credit: Implemented by My Friend</figcaption></figure><p>Before applying the spinner, the page only displayed the “No result” message whenever the data was still on loading. We realized that we had to remove this as it would baffle most users, since they did not know whether the internal system was still loading the data, or the data had been loaded successfully but there was no result.</p><h4>Match between system and the real world</h4><p>This principle says that the system should speak users’ language. By the way of saying this, the system has to use words, phrases, and symbols that are familiar to user. For instance, in the project, we use symbols that are familiar to user, such as a trash bin symbol for delete action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*sQrpzJDwMAVXygGhe_8OSw.png" /><figcaption>Credit: Designed by Me</figcaption></figure><h4>User control and freedom</h4><p>This principle says that the system should give users the freedom to decide and perform actions they intended to do. It has to give users that sense of control over the system. However, users sometimes perform mistakes during their actions. Thus, providing an emergency exit for users who regret their preceding actions would be very helpful. For example, in the project, we provide a “Kembali” button for users if they want to cancel their decision of adding new available schedule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*v7Hm9m6Jrw1SZrSW4w3DvA.png" /><figcaption>Credit: Designed by Me</figcaption></figure><h4>Consistency and standards</h4><p>This principle is about keeping the same language throughout the system to avoid confusing the users. Therefore, an interface must follow the system’s conventions and guidelines. By implementing this, the learnability of the system can be improved and the users’ cognitive load can be reduced by not learning new things. For example, in the project, we use the same system design: typography, colors, symbols, and many more. Additionally, we utilize the same side bar across all pages in the system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*-61VHEq-ByWOkLVpKKoijA.png" /><figcaption>Credit: Designed by All of Us</figcaption></figure><h4>Error prevention</h4><p>This principle says that a good design shall prevent errors and problems from occurring in the first place. For example, we provide a confirmation dialog for users if they want to delete a schedule, since they might do this by accident. By providing the dialog, users can rethink their action and decide whether they shall continue or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*84HsSqy1UjYfwq1BbogOOg.png" /><figcaption>Credit: Designed by Me</figcaption></figure><h4>Recognition rather than recall</h4><p>This principle says that it is better to minimize users’ memory load. The users should’ve not remembered information from one page to another, since humans have limited short-term memories. For example, when the user wants to change the status of a schedule, the confirmation dialog shows the final status after being changed, instead of telling the user to remember the status from the preceding page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*JCxph6MrcKNg37r8rM39Yw.png" /><figcaption>Credit: Designed by Me</figcaption></figure><h4>Flexibility and efficiency of use</h4><p>This principle says that the system should be easy to use by both experienced and inexperienced users. Besides, it is important to ensure efficiency is achieved when using the system, such as providing shortcuts to speed up interactions. In the project, users can perform basic keyboard shortcuts, such as copy (Ctrl + C), paste (Ctrl + V), cut (Ctrl + X), and many more to speed up actions when filling the input fields. Besides, date and time inputs also allow user to type the intended input using the keyboard instead of picking manually from the provided options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*lXmuGe6R3NWfPzFIn8Mwkw.png" /><figcaption>Credit: Implemented by My Friend</figcaption></figure><h4>Aesthetic and minimalist design</h4><p>This principle says that interfaces should not contain irrelevant information. Designers have to make sure that the design is minimalist — focusing on the essential elements only. Furthermore, ensure the visual elements of the interface support users’ primary goals, not just showing too many unimportant garnishes. For example, the page below only displays important information regarding the list of schedules and actions users can do. The design is pretty simple as well, so that users are not going to be distracted by unimportant elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*SR41DxHXFtx_i92vwPsBXg.png" /><figcaption>Credit: Designed by Me</figcaption></figure><h4>Help users recognize, diagnose, and recover from errors</h4><p>This principle says that error messages should be easy to understand, yet still precisely indicate the problems. The messages also should be presented in a way that users will notice and recognize them. For example, this error message below shows the reason behind the error and is displayed in a red toast so users will notice it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oj1zozV9a5G048x4nfh2lA.png" /><figcaption>Credit: Implemented by My Friend</figcaption></figure><h4>Help and documentation</h4><p>This principle says that it may be important to provide documentation to help users understand how to complete the tasks. For this project, this feature is yet to be implemented. However, we have made the mockup for the “Help” page, as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*Q9fyPAGFfwoOFN73lXPrjw.png" /><figcaption>Credit: Designed by My Friend</figcaption></figure><h3>Fitts’ Law</h3><blockquote>The time to acquire a target is a function of the distance to and size of the target.</blockquote><p>There is a mathematical formula to express the idea of this law, but I won’t explain that here. In conclusion, the longer the distance it takes to move a pointer to a target area and the smaller the target’s size, the longer the time it takes. Furthermore, this implies that big and near objects are easy to click, whereas small and far objects are hard to click. Below are some implementations that consider this law.</p><h4>Shorter dropdown lists</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*yk9RrPZG1MWWSuP5jwUvWA.png" /><figcaption>Credit: Implemented by My Friend</figcaption></figure><p>By using shorter dropdown lists, users can minimize the travel distance in selecting an option, which reducing time and increasing productivity.</p><h4>Spacing between buttons and larger size of buttons</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/1*QMzZb9kgkvBWwnNW0XzzBQ.png" /><figcaption>Credit: Implemented by My Friend</figcaption></figure><p>Ensuring enough spacing between buttons and increasing the size of buttons can make users more convenient in pressing those buttons without having to worry accidentally pressing other buttons, thus reducing time and increasing productivity as well.</p><h4>Proper location of buttons</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ANjmmFDr_lP3kvkIktz4rQ.png" /><figcaption>Credit: Implemented by My Friend</figcaption></figure><p>Buttons should be easy to locate by putting those in a location that users will notice easily, such as at the top of the page.</p><h3>Jakob’s Law</h3><blockquote>Users spend most of their time on other sites. This means that users prefer your site to work the same way as all the other sites they already know.</blockquote><p>This means that it is better to have a “familiar” structure or design with other well-known websites.</p><h4>Implementation of side bar</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFsitygWZ65KK9Gs8AGbaQ.png" /><figcaption>Source: <a href="https://www.youtube.com/">(52) YouTube</a></figcaption></figure><p>Most popular websites use side bar to display menu bar, such as YouTube. We implement this in the design of our project by providing a side bar for users to navigate throughout the application. Users with prior experience using YouTube or other popular sites with side bar will find it easy to use this application.</p><h4>List layout</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UWaPm4XjgAatuU3lYctU0g.png" /><figcaption>Source: Implemented by My Friend</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*es5n6P3luffgYbFJ8r3v-w.png" /><figcaption>Source: <a href="https://www.google.com/search?q=human+computer+interaction&amp;sca_esv=faf3bf626897cb5c&amp;sca_upv=1&amp;ei=eJ0jZuTuOoqgnesP77K0-A8&amp;ved=0ahUKEwjkityMz9CFAxUKUGcHHW8ZDf8Q4dUDCBA&amp;uact=5&amp;oq=human+computer+interaction&amp;gs_lp=Egxnd3Mtd2l6LXNlcnAiGmh1bWFuIGNvbXB1dGVyIGludGVyYWN0aW9uMgsQABiABBiRAhiKBTILEAAYgAQYkQIYigUyChAAGIAEGEMYigUyChAAGIAEGEMYigUyBRAAGIAEMgUQABiABDIFEAAYgAQyBRAAGIAEMgUQABiABDIFEAAYgARItlZQmARY9VNwBngBkAEBmAHnAqABtyuqAQgyLjE2LjguMrgBA8gBAPgBAZgCIaACziqoAhTCAgoQABiwAxjWBBhHwgINEAAYgAQYsAMYQxiKBcICExAAGIAEGEMYtAIYigUY6gLYAQHCAhYQABgDGLQCGOUCGOoCGIwDGI8B2AECwgIWEC4YAxi0AhjlAhjqAhiMAxiPAdgBAsICEBAAGIAEGLEDGEMYgwEYigXCAgsQABiABBixAxiDAcICCBAAGIAEGLEDwgILEAAYgAQYsQMYigXCAg4QLhiABBixAxiDARiKBcICEBAuGIAEGNEDGEMYxwEYigXCAhMQLhiABBjRAxhDGNQCGMcBGIoFwgIFEC4YgATCAg4QABiABBixAxiDARiKBcICERAuGIAEGLEDGNEDGIMBGMcBwgILEC4YgAQY0QMYxwHCAhcQLhiABBiRAhixAxjRAxiDARjHARiKBcICDhAAGIAEGJECGLEDGIoFwgIKEC4YgAQYQxiKBcICDRAuGIAEGEMY1AIYigXCAiYQLhiABBiRAhixAxjRAxiDARjHARiKBRiXBRjcBBjeBBjgBNgBA8ICDRAAGIAEGLEDGEMYigXCAggQLhiABBixA5gDFogGAZAGCroGBAgBGAe6BgYIAhABGAq6BgYIAxABGBSSBwk4LjE0LjEwLjGgB-DjAQ&amp;sclient=gws-wiz-serp">human computer interaction — Google Search</a></figcaption></figure><p>There are lots of applications that use list layout to display the results, such as Google. By having a list layout in our application, users will easily get used to the application because they are already familiar with Google’s interface layout.</p><h4>Usage of most buttons or toggles</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MF4ijA_ghQEQvVmjweqRg.png" /><figcaption>Source: <a href="https://lawsofux.com/jakobs-law/">Jakob’s Law | Laws of UX</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*o-TcmJak-3FEdkeagrMTPw.png" /></figure><p>Form toggles, buttons, radio buttons, and many input are originated from the real physical ones, so it is easy for users to get familiar with these :)</p><h3>Is there any design that violates the principles?</h3><p>Unfortunately, yes. There are some implementations that “kind of” violate the principles I have mentioned before.</p><h4>Long dropdown list</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/757/1*G68yd_L7BnhtILRHNJz0Dw.png" /><figcaption>Credit: Implemented by My Friend</figcaption></figure><p>To be honest, this is inevitable. The amount of client is keep increasing all the time. Consequently, the dropdown list is going to be looooong as well. However, we have provided an alternative design: using combobox. By using this, if the amount of client has been increased significantly, admin can still easily search the client by typing client’s name in the input box.</p><h4>Some minor inconsistencies</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r30yG1kMlDlrNDT9_DIhXA.png" /><figcaption>Credit: Implemented by My Friend</figcaption></figure><p>For time input, there are some fields that require users to type the intended time manually using the format HH:MM:SS and there are some equipped with the “real” time fields. We are planning to change this text input boxes into time fields, since it is not intuitive using text fields for time inputs.</p><h4>“Hidden” button location</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjBdMQ0vLmodPYuOVu8aZw.png" /><figcaption>Credit: Implemented by My Friend</figcaption></figure><p>You might be wondering, “Which button is hidden?”. The answer is the “Cek Ketersediaan Jadwal” button. The button is visible in that screenshot, but it will disappear when you enlarge the size of the screen like the one shown in this picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nSlOByc-uHgMjzmlwp3Qw.png" /></figure><p>It takes some effort to scroll down and find the button at the bottom of the table. Hence, it violates Fitts’ Law. The potential change that can be made is by moving the button to a location which the users will possibly notice at the first time viewing the page, i.e. beside “Jadwalkan Sesi Lanjutan” button at the top of the table.</p><h3>Alternative design?</h3><p>Based on the violations I have mentioned before, below is the alternative design I propose to fix the user interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YWayUjj5E3Jw3D2eM5jbxQ.png" /></figure><p>As you can see, the “Cek Ketersediaan Jadwal” button has been moved to the top of the table, next to “Jadwalkan Sesi Lanjutan” button. The button location is way more visible right now. Users don’t have to scroll down to find that button anymore.</p><p>Furthermore, the minor inconsistencies have been fixed as well, such as the time input field.</p><h3>Lessons learned</h3><p>By implementing these principles, the learning curve for users when using the application will be reduced, enabling them to get used to the application easily. Consequently, user engagement will be enhanced significantly, which leading to greater user satisfaction, and finally: more profit! 🤑</p><h3>References</h3><p><a href="https://www.figma.com/resource-library/difference-between-ui-and-ux/">UI vs UX: What’s the Difference between UI &amp; UX Design? | Figma</a></p><p><a href="https://aelaschool.com/en/interactiondesign/10-usability-heuristics-ui-design/">Nielsen’s Heuristics: 10 Usability Principles To Improve UI Design — Aela School</a></p><p><a href="https://bootcamp.uxdesign.cc/simplified-jakob-nielsens-10-usability-heuristics-36a860c2ac9c">Simplified: Jakob Nielsen’s 10 usability heuristics | by Meghna Basak | Bootcamp (uxdesign.cc)</a></p><p><a href="https://www.nngroup.com/articles/ten-usability-heuristics/">10 Usability Heuristics for User Interface Design (nngroup.com)</a></p><p><a href="https://www.interaction-design.org/literature/topics/fitts-law">What is Fitts’ Law? — updated 2024 | IxDF (interaction-design.org)</a></p><p><a href="https://lawsofux.com/fittss-law/">Fitts’s Law | Laws of UX</a></p><p><a href="https://lawsofux.com/jakobs-law/">Jakob’s Law | Laws of UX</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1cc6362397e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SonarQube: Turning Messy Code into Blessy Code]]></title>
            <link>https://medium.com/@jaycentg/sonarqube-turning-messy-code-into-blessy-code-2acfdacf84f9?source=rss-3f05c5ac32c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2acfdacf84f9</guid>
            <category><![CDATA[quality-assurance]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[software-qa]]></category>
            <category><![CDATA[sonarqube]]></category>
            <dc:creator><![CDATA[Jaycent Gunawan Ongris]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 13:58:02 GMT</pubDate>
            <atom:updated>2024-04-01T07:33:42.404Z</atom:updated>
            <content:encoded><![CDATA[<h3>SonarQube: Farewell Dirty Code!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Inc98CTXlmTOE7pj.jpg" /><figcaption>Source: <a href="https://ifunny.co/tags/sonarqube">Sonarqube memes. Best Collection of funny Sonarqube pictures on iFunny</a></figcaption></figure><blockquote>Any fool can write code that a computer can understand. Good programmers write code that humans can understand — Martin Fowler, “Refactoring”</blockquote><p>According to <a href="https://www.turing.com/blog/software-quality-assurance-and-its-importance/">Turing.com</a>, software quality assurance (SQA) is a methodology to ensure that the quality of the software product complies with a predetermined set of quality standards. By incorporating QA into Software Development Life Cycle (SDLC) phases, programmers can ensure that the software they build has a great quality from the start, where issues are found and resolved quickly. Therefore, the cost and time for maintenance can be significantly reduced.</p><p>There are several ways to implement SQA into the SDLC. One of the ways is by inspecting the quality of the produced code. Code quality is a very important aspect in software development, as it ensures the readability and long-term management of the code. One should not be an irresponsible programmer by writing code without considering the quality of it. A good programmer doesn’t want to make others having a hard time understanding the code. Believe me, working with a (bad) legacy code is a genuine headache! :(</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*698oRhcUXEkJyo8w.png" /><figcaption>Source: <a href="https://tsh.io/blog/testing-legacy-code/">Testing legacy code can be hard. Here’s a better way to do it (tsh.io)</a></figcaption></figure><p>Unfortunately, it is very hard to check the quality of your code manually line by line. You may miss lots of potential bugs, vulnerabilities, or even security problems. This is where static code analysis tools, such as SonarQube and Code Climate come in handy. Specifically, we will talk a lot about SonarQube.</p><h3>What is SonarQube?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/0*nk9KQ8A6jeQZVaAt.png" /><figcaption>Source: <a href="https://wiki.eclipse.org/SonarQube">SonarQube — Eclipsepedia</a></figcaption></figure><p>SonarQube is a static code analysis tool that can analyze source code and provide a detailed report regarding the code quality. Not only that, SonarQube also provides feedback for all issues detected in the source code, so that programmers can easily fix the code based on that. There are three kinds of issues that can be detected by SonarQube: bugs, vulnerabilities, and code smells. SonarQube also provides the severity level of each issue to let programmers know which issue shall be prioritized to be fixed. Furthermore, SonarQube can also display the test coverage of the source code.</p><h3>How does it look?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/973/1*taoSZ8j7nnwAhjFjhb51Og.png" /><figcaption>Source: My Project’s SonarQube Dashboard</figcaption></figure><p>You can see if there are any new bugs, code smells, vulnerabilities, or security hotspots in your newly produced code in this SonarQube dashboard. Later, SonarQube can give a grade for every aspect of your source code, such as reliability, security, security review, and maintainability, as you can see in the right side of the panel. There are also some information regarding technical debts, code coverage, and code duplications. You can later utilize this information to fix your code.</p><h3>How to implement SonarQube in your project?</h3><p>There are two ways to implement SonarQube in your project: run the check manually or implement it as one of the CI/CD stages.</p><p>For the first method, you can run the SonarQube sonar-scanner command in your local terminal. But, before that, make sure to install Sonar Scanner CLI tool in your PC. Check this <a href="https://docs.sonarsource.com/sonarqube/latest/analyzing-source-code/scanners/sonarscanner/">link</a> on how to install Sonar Scanner CLI tool. After setting up your Sonar Scanner in the PATH environment variables, you can just run the scanner directly in your terminal by using this command below, assuming SONAR_PROJECT_KEY and SONAR_TOKEN are present as one of the environment variables, as stated in .env file.</p><pre>sonar-scanner -D&quot;sonar.projectKey=${SONAR_PROJECT_KEY}&quot; -D&quot;sonar.login=${SONAR_TOKEN}&quot; -D&quot;sonar.python.coverage.reportPaths=./coverage.xml&quot;</pre><p>You may add another parameters in your command by using -D&quot;sonar.{parameter}={value}&quot;. Another option you can take if there are lots of parameters you want to specify is by specifying them in sonar-project.properties file. By putting them in that file, you don’t have to re-type the parameters every time you execute that command. Below is the example of my sonar-project.properties file.</p><pre>sonar.host.url=https://sonarqube.cs.ui.ac.id<br><br>sonar.sources=.<br>sonar.exclusions=**/migrations/**, **/static/**, **/config/**<br>sonar.inclusions=<br><br>sonar.tests=.<br>sonar.test.exclusions=<br>sonar.test.inclusions=**/tests/**, **/tests.py<br><br>sonar.sourceEncoding=UTF-8<br><br>sonar.verbose=true</pre><p>The explanations for the parameters are as follows:</p><ol><li>sonar.host.url specifies the URL to the SonarQube server, which in my case, the SonarQube Enterprise for CS UI.</li><li>sonar.sources specifies the analysis directory (scope) of the source code (non-test code) in the project, which in my case the scope is the current working directory. sonar.exclusions and sonar.inclusions are used to specify which directories or files that should be excluded or included in the analysis.</li><li>sonar.tests specifies the analysis directory (scope) of the test code in the project. The same as above, sonar.test.exclusions and sonar.test.inclusions specify which directories or files that should be excluded or included in the test analysis.</li><li>sonar.sourceEncoding specifies the encoding of the source code, which in my case is UTF-8.</li><li>sonar.verbose specifies whether the scanner should provide detailed logs while doing the analysis. I suggest you to set this to true to ease your debugging process.</li></ol><p>There are lots of other optional parameters you can specify in this file, which has been explained in a detail manner in <a href="https://docs.sonarsource.com/sonarqube/latest/analyzing-source-code/analysis-parameters/">this documentation</a>.</p><p>Nevertheless, running the analysis each time you write new code can be tedious. So, let’s just specify this command in our CI script, such that every time you push new changes to the remote repository, the analysis will be conducted automatically. Now you can understand the meme I’ve shown you earlier 😁</p><pre>SonarQube:<br>  stage: Test<br>  image: sonarsource/sonar-scanner-cli:latest<br>  needs:<br>    - job: Test<br>      artifacts: true<br>  allow_failure: true<br>  variables:<br>    SONAR_USER_HOME: &quot;${CI_PROJECT_DIR}/.sonar&quot;  # Defines the location of the analysis task cache<br>    GIT_DEPTH: &quot;0&quot;  # Tells git to fetch all the branches of the project, required by the analysis task<br>  cache:<br>    key: &quot;${CI_JOB_NAME}&quot;<br>    paths:<br>      - .sonar/cache<br>  script:<br>    - sonar-scanner -D&quot;sonar.projectKey=${SONAR_PROJECT_KEY}&quot; -D&quot;sonar.login=${SONAR_TOKEN}&quot; -D&quot;sonar.python.coverage.reportPaths=./coverage.xml&quot;<br>  dependencies:<br>    - Test</pre><p>Above is the CI stage for SonarQube analysis. You can see that the same script is defined in that job. The dependency for this job is Test job, as this produces coverage.xml artifact which provides information regarding the test coverage. We can specify the path to this file as the value of sonar.python.coverage.reportPaths parameter.</p><h3>How SonarQube can be helpful for the project?</h3><p>As I have explained before, SonarQube provides lots of detailed information regarding issues in your code. For example, below is the “Issues” panel in my SonarQube dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6T0YpJE2rAKXKDGAKuiI6Q.png" /><figcaption>Source: My Team’s SonarQube Issues Panel</figcaption></figure><p>As you can see, there are several code smells in the source code. If you click the issue, SonarQube will show you which line that causes the problem, as seen below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hjrpVUTIpCT7X-mJYOE65w.png" /><figcaption>Source: My Team’s SonarQube Issue</figcaption></figure><p>Not only that, by clicking “Why is this an issue?”, you can get a detailed information regarding the issue, including information on how to fix it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDWJf4kic491PrGxlKkqiQ.png" /><figcaption>Source: My Team’s SonarQube Issue Description</figcaption></figure><p>The same as well for “Security Hotspots” panel. We can review every security hotspot to decide whether that piece of code poses a risk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOHsDAcbZtoXu2ZwE8V0hg.png" /><figcaption>Source: My Team’s SonarQube Security Hotspots Panel</figcaption></figure><p>SonarQube also provides visualization to see the technical debt and coverage of each file. Bigger circle indicates more lines of code (LOC) in the respective file. You can see more information by hovering your cursor to the circle (file) you want to inspect.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4KHRn_4gIBPOaTIy_aO4_A.png" /><figcaption>Source: My Team’s SonarQube Visualization</figcaption></figure><p>After inspecting all those issues, we can fix the code based on that. The way you fix the code depends on which issue are you currently facing. For instance, if the issue is the commented code, then we can simply remove it. Take a look at the guide provided by SonarQube to determine which action should have been taken next.</p><h3>Code smells I fixed</h3><h4>Unused assignment</h4><p>The solution for this code smell is pretty simple, you only have to remove the assignment for the variable. In this case, we can just call authenticate() without having to assign it to variable user, because user is not going to be used later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BUsUt_MsEXf7qRACY8h4g.png" /><figcaption>Removing unused assignment</figcaption></figure><h4>Commented code</h4><p>The solution for this code smell is simple as well, you only have to simply remove the commented code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Xs5O7_wF0bWp8eehTbgNw.png" /><figcaption>Removing commented code</figcaption></figure><h4>Usage of generic exception</h4><p>This code smell should be avoided because it may lead to unexpected behavior in runtime, i.e. it might catch exceptions that programmers did not anticipate before. Furthermore, it could cause difficulty in troubleshooting because the provided information regarding the error is not specific enough. In this case, instead of catching generic Exception class, I changed the code to catch specific User.DoesNotExist class. It is way more intuitive and informative compared to catching Exception class. Besides that, I also deleted the as e because e is not going to be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vaLS6uhV6EGMURUNtqMJhQ.png" /><figcaption>Using specific exception class</figcaption></figure><h4>No positional parameter</h4><p>This code smell appears because there are instance methods that are not equipped with positional parameters, in this case self parameter. To fix this, we can simply add self as the first parameter in the instance method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*78yTb-zjZAxUilndf90mEg.png" /><figcaption>Using positional parameter in instance method</figcaption></figure><h4>Not following naming convention</h4><p>There are some parts in the code that do not comply with Python’s naming convention. For instance, the name of the variable below is using camel case. I changed it to snake case so that it follows Python’s naming convention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AV1F6FXO77CkVoMTVnqTfA.png" /></figure><h3>Aftermath</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*udd_Pii2-ZKINO5SDX_gVQ.png" /><figcaption>Source: My Team’s SonarQube Issues Panel After Refactoring</figcaption></figure><h3>Lessons learned</h3><p>You can utilize SonarQube to help you identify code smells, vulnerabilities, bug, and security hotspots in your code. It provides lots of detailed information regarding the issues, as well as the fixes. Therefore, you can maintain the quality of your code and prevent others from having a hard time understanding your code. Here’s to higher code quality! 🍻</p><h3>References</h3><p><a href="https://www.codecademy.com/resources/blog/inspirational-coding-quotes/">14 Motivational Quotes About Coding &amp; Computer Programming (codecademy.com)</a></p><p><a href="https://www.turing.com/blog/software-quality-assurance-and-its-importance/">What Is Software Quality Assurance, and Why Is It Important? | Turing</a></p><p><a href="https://www.linkedin.com/advice/0/how-do-you-add-quality-assurance-your-1f">How do you add quality assurance to your SDLC? (linkedin.com)</a></p><p><a href="https://www.simplilearn.com/software-quality-assurance-article">What Is Software Quality Assurance: Definition, Benefits, and Top Techniques Explained (simplilearn.com)</a></p><p><a href="https://aws.amazon.com/what-is/code-quality/">What is Code Quality? — Code Quality Explained — AWS (amazon.com)</a></p><p><a href="https://www.crestdatasys.com/blogs/an-introduction-on-using-sonarqube/">An introduction on using SonarQube — Crest Data Systems</a></p><p><a href="https://docs.sonarsource.com/sonarqube/9.9/user-guide/issues/">Issues (sonarsource.com)</a></p><p><a href="https://docs.sonarsource.com/sonarqube/latest/analyzing-source-code/analysis-parameters/">Analysis parameters (sonarsource.com)</a></p><p><a href="https://docs.sonarsource.com/sonarqube/latest/project-administration/analysis-scope/">Narrowing the focus with an analysis scope (sonarsource.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2acfdacf84f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Rid of Slow Performance with This!! (No Clickbait)]]></title>
            <link>https://medium.com/@jaycentg/get-rid-of-slow-performance-with-this-no-clickbait-9054b51ae8f5?source=rss-3f05c5ac32c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9054b51ae8f5</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[profiling]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jaycent Gunawan Ongris]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 09:31:23 GMT</pubDate>
            <atom:updated>2024-03-27T09:31:23.333Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*9lhWyYKDvHbyWZxJ.jpg" /><figcaption>Source: <a href="https://www.pinterest.com/pin/74661306310490921/">Profiling | Programmer jokes, Funny, Jokes (pinterest.com)</a></figcaption></figure><p>Can you guess what do I want to explain in this article? No, I am not going to buy new hardware or use hi-end VM in Google Cloud Platform to improve the performance. I don’t want to talk about improving performance <strong>externally (or physically?)</strong>, but <strong>internally</strong>. Yes, you can improve the performance internally by inspecting your code and do optimization things.</p><p>But, how do you know which part of your code has to be optimized? Let me introduce you to this technique called ✨profiling✨. Profiling is a process of analyzing a software program’s runtime behavior with the goal of identifying performance bottlenecks, memory leaks, and other inefficiencies. There are several types of profiling, but in this article, we will be focusing on performance and database profilers, especially in Django.</p><h3>Profiling in Django with Silk</h3><p>In this section, we will look on how to set up Silk in your Django project. By the way, Silk is a profiling and inspection tool for Django Web Framework. It works by intercepting and storing HTTP requests and database queries before presenting them in a user interface for further inspection. You can take a look at the documentation here: <a href="https://github.com/jazzband/django-silk">GitHub — jazzband/django-silk: Silky smooth profiling for Django</a>.</p><p>Okay, let’s start. The first thing to do is to definitely install it to your environment. Using pip package manager, you can install Silk using the command below.</p><pre>pip install django-silk</pre><p>After that, you have to put Silk as the middleware of your application by putting them in the MIDDLEWARE variable in settings.py or other equivalent files. Furthermore, Django will treat this Silk as a Django App, so don’t forget to put it into the INSTALLED_APPS as well.</p><pre>MIDDLEWARE = [<br>    ...<br>    &#39;silk.middleware.SilkyMiddleware&#39;,<br>    ...<br>]<br><br>INSTALLED_APPS = (<br>    ...<br>    &#39;silk&#39;<br>)</pre><p>Next, specify the user interface path in urls.py.</p><pre>urlpatterns += [path(&#39;silk/&#39;, include(&#39;silk.urls&#39;, namespace=&#39;silk&#39;))]</pre><p>Lastly, since this is a new “app”. You have to do migration and collectstatic in which Silk uses to put the files related to the user interface.</p><pre>python manage.py migrate<br><br>python manage.py collectstatic</pre><p>Voila, you have finished setting up Silk in your Django project. The next thing to do is to run your server and visit <a href="http://localhost:8000/silk/">http://localhost:8000/silk/</a>. You can see the dashboard which provides lots of detailed information regarding the APIs defined in your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3EQ2dqZin5q_qYPI7f-WA.png" /><figcaption>Source: My Own Documentation</figcaption></figure><p>No need to worry if the dashboard looks pretty different to mine, since I have already tested several APIs. To display the performance of the API in your dashboard, you can simply hit the API using Postman or from your browser. After that, refresh the Silk dashboard and you can see the stats of your latest API hit.</p><p>As you can see, there are several APIs that need to be optimized because of their response time and the amount of database queries. We will take a look at several example and refactor the code so that it performs better.</p><h3>Profiling: Get Daftar Pilihan Jadwal Konseling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8BW_wpLCPtMQNRf9ROwQtg.png" /><figcaption>Source: My Own Documentation</figcaption></figure><p>What a bad stats, huh? 3293ms overall and 57 queries. Well, frankly speaking, for me, this makes sense, since this API is quite complex and involves retrieving data from several tables. What did I do to improve the performance of this API?</p><h4>Change the If-Else (Conditional) Block</h4><p>I use two query parameters for filtering the result of this API, which are q and status. It is not necessary to use all the query parameters to filter the data. User may leave them empty if they want to. My first naive approach was to specify all the combinations of all possible values. In a nutshell, it used to look like this.</p><pre>if query == &quot;&quot; and stat == &quot;&quot;:<br>    pendaftaran = Pendaftaran.objects.all()<br>elif query == &quot;&quot; and stat != &quot;&quot;:<br>    pendaftaran = Pendaftaran.objects.filter(status=stat)<br># handle npm<br>elif query[0].isdigit():<br>    pendaftaran = Pendaftaran.objects.filter(pengguna__npm__startswith=query)<br>    if not stat == &quot;&quot;:<br>        pendaftaran = pendaftaran.filter(status=stat)<br># handle nama<br>else:<br>    pendaftaran = Pendaftaran.objects.filter(pengguna__fullname__startswith=query)<br>    if not stat == &quot;&quot;:<br>        pendaftaran = pendaftaran.filter(status=stat)</pre><p>I realized that using lots of conditional statements (even though lazy evaluation will be implemented for and operator) can slow down the performance a little bit. So, I just use different approach to handle this, using Django’s Q filter with a little bit of restructuring the conditional statements.</p><pre>filter_conditions = Q()<br><br>if stat:<br>    filter_conditions &amp;= Q(status=stat)<br>        <br>if query:<br>    if query.isdigit():<br>        filter_conditions &amp;= Q(pengguna__npm__startswith=query)<br>    else:<br>        filter_conditions &amp;= Q(pengguna__fullname__icontains=query)<br>        <br>list_pendaftaran = Pendaftaran.objects.filter(filter_conditions).select_related(&#39;pengguna&#39;)</pre><p>It’s way cleaner and the number of complex conditional statements has been reduced as well. Actually, the performance improvement is negligible, but hey, let’s take a look at the bright side: the code is far better than before, right? :-D</p><h4>Use Prefetch in Fetching Data</h4><p>This is actually the MVP. As you can see in the code snippet above, I use select_related method. Basically, this method not only retrieve the filtered Pendaftaran objects from the database, but the related objects specified as the foreign key as well. In this case Pengguna object in pengguna attribute will be returned. For a brief context, here is the model of Pendaftaran.</p><pre>class Pendaftaran(models.Model):<br>    &quot;&quot;&quot;<br>    Model ini merupakan pendaftaran konseling yang dilakukan oleh pengguna.<br>    Pendaftaran juga bisa dilakukan oleh admin atas saran konselor.<br>    &quot;&quot;&quot;<br>    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)<br>    pengguna = models.ForeignKey(User, on_delete=models.CASCADE)<br>    status = models.ForeignKey(KonselingStatus, on_delete=models.CASCADE)<br>    tujuan_konseling = models.TextField()<br>    mode_konseling = models.CharField(max_length=10, choices=[(&#39;ONLINE&#39;, &#39;Online&#39;), (&#39;OFFLINE&#39;, &#39;Offline&#39;)], default=&#39;OFFLINE&#39;)<br>    is_didaftarkan_oleh_konselor = models.BooleanField(default=False)<br>    skala_prioritas = models.IntegerField(default=1) # 1-10<br>    alasan_skala_prioritas = models.TextField(null=True, blank=True)<br>    created_at = models.DateTimeField(default=timezone.now, editable=False)<br>    updated_at = models.DateTimeField(auto_now=True)<br><br>    class Meta:<br>        ordering = [&#39;created_at&#39;]<br><br>    def __str__(self):<br>        return f&quot;{self.pengguna}: {self.status} - {self.created_at}&quot;</pre><p>By selecting pengguna from the start, the program does not have to query from the database again if the object is needed in the future, thus reducing the number of query calls. Below is another intuitive example on how to use select_related from Django’s documentation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvea0hLyj5FeiAiEDKQYTg.png" /><figcaption>Source: <a href="https://docs.djangoproject.com/en/5.0/ref/models/querysets/#select-related">QuerySet API reference | Django documentation | Django (djangoproject.com)</a></figcaption></figure><h4>Restructure the Loop</h4><p>Loop is one of the most crucial building blocks for a program. But, if you can’t use loops properly, it will slow down the performance of your program. In the original version, there are two loops that basically iterate over the “same” data. Take a look at the code snippet below.</p><pre>result = []<br>for entry in pendaftaran:<br>    try:<br>        sesi_konseling = SesiKonseling.objects.get(pendaftaran=entry.pk)<br>        konselor = sesi_konseling.konselor<br>    except:<br>        sesi_konseling = None<br>        konselor = None<br>            <br>    preferensi_jadwal = PreferensiJadwal.objects.filter(pendaftaran=entry.pk)<br>    if list(preferensi_jadwal) == list(PreferensiJadwal.objects.none()):<br>        preferensi_jadwal  = None<br>            <br>    pengguna = entry.pengguna<br>            <br>    result.append((entry, sesi_konseling, pengguna, konselor, preferensi_jadwal))<br><br>combined_data = {}<br>count = 0<br># Iterasi hasil dari filtering, untuk membuat output ditampilkan per entry/row berdasarkan pendaftaran<br>for row in result:<br>     pendaftaran_serialized = DaftarKonselingPendaftaranSerializer(row[0]).data<br>     sesi_konseling_serialized = DaftarKonselingSesiKonselingSerializer(row[1]).data<br>     pengguna_serialized = DaftarKonselingPenggunaSerializer(row[2]).data<br>     konselor_serialized = DaftarKonselingKonselorSerializer(row[3]).data if row[1] else {&#39;nama&#39;:None}<br>     if isinstance(row[4], Iterable):<br>         preferensi_jadwal_serialized = DaftarKonselingPreferensiJadwalSerializer(row[4], many=True).data<br>     else:<br>         preferensi_jadwal_serialized = DaftarKonselingPreferensiJadwalSerializer(row[4]).data<br>            <br>     combined_data[&quot;entry&quot; + str(count)] = {&quot;pendaftaran&quot;:pendaftaran_serialized, <br>                                            &quot;sesi_konseling&quot;:sesi_konseling_serialized,<br>                                            &quot;pengguna&quot;:pengguna_serialized,<br>                                            &quot;konselor&quot;:konselor_serialized,<br>                                            &quot;preferensi_jadwal&quot;:preferensi_jadwal_serialized} <br>     count += 1</pre><p>The complexity of the code above is O(2n), because there are two loops, each iterates over a list of n elements. However, we can reduce this to O(n), using this code below.</p><pre>result = []<br>for pendaftaran in list_pendaftaran:<br>    sesi_konseling = SesiKonseling.objects.filter(pendaftaran=pendaftaran.pk).first()            <br>    preferensi_jadwal = PreferensiJadwal.objects.filter(pendaftaran=pendaftaran.pk)<br><br>    pendaftaran_serialized = DaftarKonselingPendaftaranSerializer(pendaftaran).data<br>    sesi_konseling_serialized = DaftarKonselingSesiKonselingSerializer(sesi_konseling).data if sesi_konseling else None<br>    pengguna_serialized = DaftarKonselingPenggunaSerializer(pendaftaran.pengguna).data<br>    konselor_serialized = DaftarKonselingKonselorSerializer(sesi_konseling.konselor).data if sesi_konseling else None<br>    preferensi_jadwal_serialized = DaftarKonselingPreferensiJadwalSerializer(preferensi_jadwal, many=True).data if preferensi_jadwal else []<br><br>    result.append({<br>        &quot;pendaftaran&quot;: pendaftaran_serialized,<br>        &quot;sesi_konseling&quot;: sesi_konseling_serialized,<br>        &quot;pengguna&quot;: pengguna_serialized,<br>        &quot;konselor&quot;: konselor_serialized,<br>        &quot;preferensi_jadwal&quot;: preferensi_jadwal_serialized<br>    })</pre><p>There is only one loop, each iteration retrieve the sesi_konseling and preferensi_jadwal. The data is later serialized in the same iteration and it is appended to the result list.</p><h4>The Aftermath</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0FBAISU50utgvhnRxg8Aw.png" /><figcaption>Source: My Own Documentation</figcaption></figure><p>You can see the overall response time and the number of query calls has been decreased as the result of refactoring the program into a more efficient one :D</p><h3>Profiling: Get Sesi Potensial</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7mtadizq9sfgXVv19CnRsw.png" /><figcaption>Source: My Own Documentation</figcaption></figure><p>Not too bad, huh? But, let’s see how much we can do to improve the performance of this API.</p><h4>Use Prefectch in Fetching Data</h4><p>The same as before, I will use select_related to prefetch related data. The example can be seen below.</p><pre>preferensi_jadwal_all = PreferensiJadwal.objects.filter(datetime__date=tanggal).select_related(&#39;pendaftaran__pengguna&#39;)</pre><p>To give a context, below is the PreferensiJadwal model.</p><pre>class PreferensiJadwal(models.Model):<br>    datetime = models.DateTimeField()<br>    pendaftaran = models.ForeignKey(Pendaftaran, on_delete=models.CASCADE)</pre><p>Pendaftaran model can be seen in the previous section’s code snippet. In Pendaftaran, there is a foreign key to Pengguna object saved in pengguna attribute. To get this object, we can simply use __ operator, so it goes like this: pendaftaran__pengguna. This code is basically pre-fetching Pendaftaran and Pengguna objects with PreferensiJadwal, so the program does not need to query from Pengguna again in this call: jadwal.pendaftaran.pengguna.fullname. The number of query calls will be reduced in the end.</p><h4>Use List Comprehension Instead of For Loop</h4><p>List comprehensions are generally faster than conventional for loops. This is because list comprehensions do not require the overhead of the loop construction. Besides, there are other internal optimizations in list comprehension implementation. Hence, we will generate the SesiPotensial list using list comprehension, as you can see below.</p><pre>list_preferensi_jadwal = [<br>    SesiPotensial(<br>        nama_pasien=jadwal.pendaftaran.pengguna.fullname,<br>        is_pagi=jadwal.datetime.time() &lt; time(12, 0, 0),<br>        skala_prioritas=jadwal.pendaftaran.skala_prioritas,<br>        id_pendaftaran=jadwal.pendaftaran.id,<br>        is_terjadwal=SesiKonseling.objects.filter(pendaftaran=jadwal.pendaftaran, is_dibatalkan=False).exists(),<br>        created_at=jadwal.pendaftaran.created_at<br>    )<br>    for jadwal in preferensi_jadwal_all<br>]</pre><h4>Avoid Chaining Filters</h4><p>In this part, I refactor the code from multiple chaining filters into one filter with several parameters.</p><pre># good example<br>SesiKonseling.objects.filter(pendaftaran=jadwal.pendaftaran, is_dibatalkan=False)<br><br># bad example<br>SesiKonseling.objects.filter(pendaftaran=jadwal.pendaftaran).filter(is_dibatalkan=False)</pre><p>If several chaining filters are used, the program will generate several queries, which resulting in increased number of query calls.</p><h4>The Aftermath</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHJVM9IHn64KXMxJTtJx5Q.png" /><figcaption>Source: My Own Documentation</figcaption></figure><p>We can see that the number of query calls has been reduced and the overall response time also reduced a little bit.</p><h3>References</h3><p><a href="https://reintech.io/terms/category/profiling-software-development">Profiling in Software Development — Identify &amp; Optimize Performance | Reintech media</a></p><p><a href="https://github.com/jazzband/django-silk">GitHub — jazzband/django-silk: Silky smooth profiling for Django</a></p><p><a href="https://medium.com/globant/for-loop-vs-list-comprehension-vs-high-order-functions-a766a8b9cbe1">Choosing the Best Iteration Technique for Optimized Python Code | by Juan Alfonso | Globant | Medium</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9054b51ae8f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring: Turning Code ‘Frankenstein’ into ‘Einstein’]]></title>
            <link>https://medium.com/@jaycentg/refactoring-turning-code-frankenstein-into-einstein-4890fd01f237?source=rss-3f05c5ac32c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/4890fd01f237</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[code-quality]]></category>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Jaycent Gunawan Ongris]]></dc:creator>
            <pubDate>Sat, 16 Mar 2024 13:57:54 GMT</pubDate>
            <atom:updated>2024-05-26T08:34:21.043Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*McJWFHGlHuSuKa9q.png" /><figcaption>Source: <a href="https://www.pinterest.com/pin/refactoring--484207397435294517/">Refactoring | Programming humor, Programmer humor, Computer science humor (pinterest.com)</a></figcaption></figure><p>Have you ever writing code so much until you can’t really understand about your code? You write hundreds of lines and you can barely know 10% of those. What should you do now?</p><p>Trying to re-understand the code every time you look at it would be a really tedious thing to do, right? Well, let me introduce you to this technique called ✨refactoring✨.</p><p>What is it, actually? Long story short, for this case, it is a process to change your code to an understandable and neat one. In general, refactoring is the process of restructuring code, without changing its external functionality. So, the goal is to improve internal code by making small changes without altering the code’s external behavior. What does it mean by ‘external behavior’? If the original code receives input A and returns output B, then the refactored code would behave the same, not receiving input A and returning output ABC.</p><blockquote><em>Be brave to refactor your code when something is not right, don’t be a coward programmer who does not want to change the code if it already works xD</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*orwwBCH0PYLR1-04.png" /><figcaption>Source: <a href="https://media.tenor.com/fJAoBHWymY4AAAAe/do-not-touch-it-programmer.png">do-not-touch-it-programmer.png (640×552) (tenor.com)</a></figcaption></figure><h3>How to ensure the code’s behavior?</h3><p>One simple thing: test your code. Make sure the previous code that passed all the test suites after being refactored still behave the same. Test suites act as safety nets when refactoring code, as they provide confidence that the behavior of the code remains unchanged after making modifications.</p><p>This is actually the other advantage of implementing TDD in your project and this is why we can see ‘refactor’ as one of the phases in the TDD cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/0*DSbZRya82t14fYBj.png" /><figcaption>Source: <a href="https://harshavardhan-reddy.medium.com/tdd-test-driven-development-a592f492bb0b">TDD : Test Driven Development. Hello! Hope everyone is well and… | by HarshaVardhanReddy Bommareddy | Medium</a></figcaption></figure><h3>When to refactor?</h3><p>There’s this rule of three to specify on what conditions we should perform refactoring in our code.</p><ol><li>When adding a feature</li><li>When fixing a bug</li><li>During a code review</li></ol><p>When you have finished working on a new feature and pushing it to GitLab, this is the perfect time for you to do refactoring. If you are implementing TDD, refactoring should occur after the GREEN phase, since the original code has passed the test suites after that phase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mx4070jmV7uxyAzjbAXCxQ.png" /><figcaption>Source: My Own Documentation</figcaption></figure><p>The same applies when you are trying to fix a bug. Sometimes you can realize that your code is actually that “dirty” when you are looking for bugs, just like in real life, since they live in the darkest and dirtiest places in the code.</p><p>Lastly, you may address some issues that need to be refactored during a code review, before being merged to the staging or main branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kdsvA_TZcd4LFnb5Afs3Kw.png" /><figcaption>Source: My Own Documentation</figcaption></figure><h4>What to refactor?</h4><p>Actually, quality assurance tools, such as SonarQube have provided good static analysis of your code. Such tools give detailed explanation of code smells, bugs, and vulnerabilities in your code, with their severity levels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uR0iS8lDB5asyvwLv925Eg.png" /><figcaption>Source: My Own Documentation</figcaption></figure><p>Other thing that I really like about SonarQube is that they also provided some sample fixes and detailed explanations regarding the issues, thus we can refactor the code based on those.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TnDOVN30ZnsTnWnu_MSsnA.png" /><figcaption>Source: My Own Documentation</figcaption></figure><h3>SonarQube is good, but is it everything?</h3><p>Sadly, no. SonarQube can’t detect every section of the code that needs to be refactored. For example, it can’t detect if some class names need to be changed into more meaningful ones. Yeah, refactoring could include changing the name of the class, which is actually a very simple thing, yet very important for code readability.</p><p>FYI, this code snippet below is not detected by SonarQube. The original class name was class KetersediaanJadwalTest(TestCase), but I changed it to class KetersediaanJadwalTestSetup(TestCase) since it only includes a set-up method, so that I can reuse it in many other test suites by inheriting the method from that class. I will explain about this later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MkGkp1hT_Sxdvlhbh4yhvQ.png" /><figcaption>Source: My Own Documentation</figcaption></figure><h3>But, actually what should we avoid in writing code?</h3><p>Well, every single answer that leads to bad practice should be avoided. However, there are several common bad practices called <strong>anti-patterns</strong>, which I will explain later. If you have ever found this in your code, maybe it’s a vivid sign for you to start refactor your code. Below are some anti-patterns that I have found during writing my code.</p><h4>Spaghetti code</h4><p>Spaghetti code refers to a condition where program code is written without having a coherent structure. This condition may lead to a less readable code, thus making others having a hard time in understanding the code.</p><p>In my project, there’s this views.py file containing all these controller methods used in the application. Yep, ALL METHOD. I didn’t realize it until I was having a hard time scrolling the code, trying to fix a minor bug in my implementation. To fix this, I separated those methods into different files, based on the functionalities. Take a look at this complete chaos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QfRuyLT7Z5pkzkFGgUgERw.png" /><figcaption>Source: My Own Documentation</figcaption></figure><p>That file contains 226 lines with 5 controller classes. In order to fix this, we can do <strong>modularization</strong>, which actually is a practice of dividing the code into smaller, independent, and cohesive units that perform specific tasks or functions. To implement this, I created a views folder, which will be containing all the controller classes in separate files. Below is the result after applying some modularization magic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*b0iEHzY_j_j_B11JgFjRYg.png" /><figcaption>Source: My Own Documentation</figcaption></figure><p>Each .py file contains an independent controller class, which is actually far better (and readable) than before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xd3cQssbh2TdJ_ZwKPor7w.png" /><figcaption>Source: My Own Documentation</figcaption></figure><h4>Copy-paste programming</h4><p>Copy-paste programming is actually an anti-pattern which the programmer produces a highly repetitive code by copy-pasting the code manually without creating generic solutions. In my project, I’ve found that several test suites are actually using the same setUp method. The naive approach I took was obviously copy-pasting the method into each test class that needed it.</p><p>And then I realized that I should’ve used an object-oriented principle called <strong>inheritance </strong>to minimize the repetition. So, I defined a parent class KetersediaanJadwalTestSetup that only contained the setUp method and made other classes that needed this method to inherit from this parent class. By doing in this way, they derived the setUp method from the parent. Hence, there’s no need to specify a setUp method in each of these classes anymore.</p><p>If some modifications are needed to be applied in the setUp method for a specific child class, we could simply override the original setUp method from the parent in that child class and invoke the setUp method from the parent class using super().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*HGhLvHYqeAe-SWnTDYA3xg.png" /><figcaption>Source: My Own Documentation, Base setUp Class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*FZmgEaij8P6QccZTE7h_ig.png" /><figcaption>Source: My Own Documentation, Inherited Class</figcaption></figure><p>In the second code snippet, I want to do a modification to the setUp method for SesiTambahanViewTest, so I just define the setUp method once more in that class, invoking the parent class’ setUp method by super().setUp(), and simply define the variable that is going to be used in that specific class. Pretty simple, isn’t it?</p><h3>Next, what should we encourage in writing code?</h3><p>Absolutely, you have to keep your code clean. It is everything when it comes to code readability. But, there’s another important concept in writing code called <strong>design pattern</strong>. Design patterns are actually typical solutions to common problems in software design. There are three types of design patterns, as follows.</p><ol><li>Creational patterns, which provide object creation mechanisms. Example: singleton, builder, prototype, etc.</li><li>Structural patterns, which explain how to assemble objects and classes into larger structures. Example: adapter, bridge, decorator, facade, DTO, etc.</li><li>Behavioral patterns, which handle effective communication and the assignment of responsibilities between objects. Example: command, iterator, state, observer, etc.</li><li>Compound patterns, which consist sets of few patterns that are combined to solve a general problem. Example: MVC, MVVM, MVP, etc.</li></ol><p>In this part, we will dive into some design patterns that me and my team have applied in the code.</p><h4>Strategy</h4><p>In a nutshell, strategy pattern is a design pattern which allows us to define a family of algorithms, put each of them into separate class, and make their objects interchangeable. By implementing this pattern, we have also fulfilled the “O” in SOLID principle, which is the “Open/Closed Principle”. This is because the pattern allows a class’s behavior to be extended without modifying its source code. Instead of altering the class itself, new strategies can be created and used interchangeably, making the system open for extension but closed for modification.</p><p>For example, I was asked by a colleague in BKM User to create an API to retrieve all schedules. I recognized that his request is pretty similar to the API I had created before. The main difference was only in the filtering. To give a context, the PreferensiJadwal object has is_available attribute to indicate whether client can pick that schedule or not. In my API, I retrieved all PreferensiJadwal objects without considering the is_available attribute, whereas he wanted me to create an API to retrieve the available schedules only (the ones with is_available equal to True). Hence, I implemented this as a concrete strategy class, deriving from abstract DaftarJadwalService class, as seen below.</p><pre>class DaftarJadwalService:<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        raise NotImplementedError(&quot;Must be implemented by subclass&quot;)<br><br>class DaftarJadwalAdminService(DaftarJadwalService):<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        if date_start is None:<br>            return list(PreferensiJadwal.objects.all().values(&#39;datetime&#39;, &#39;is_available&#39;).<br>                        order_by(&#39;datetime&#39;).distinct())<br>        ...<br><br>class DaftarJadwalUserService(DaftarJadwalService):<br>    def get_daftar_jadwal(self, date_start: date=None):<br>        if date_start is None or not isinstance(date_start, date):<br>            raise TypeError(&quot;Parameter harus berupa class Date&quot;)<br>        ...</pre><h4>Singleton</h4><p>Singleton pattern is a pattern to ensure that a class has just a single instance. One of the most important implementations of singleton pattern is the definitely the database connection. We have to ensure that there is only one instance of database connection during the runtime, which can be accessed across the application.</p><p>However, in fact, we don’t implement this explicitly, since this thing has been provided by Django ORM. We can simply specify the database credentials and let the ORM does the rest. Singleton is still singleton, though.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V7VMpRRLL10xE3IIi0m0rg.png" /><figcaption>Source: Database Connection Specification</figcaption></figure><h4>DTO</h4><p>DTO stands for Data Transfer Object. DTOs are actually objects that carry data between processes in order to reduce the number of method calls in the application.</p><p>In this application, I define a DTO class called Sesi to pass data between layers of application. The object simply encapsulates the several data related to specific entity without providing any business logic. In this case, I only add __str__() method to get the string representation of the data and __eq__() method so that this object can be compared with each other.</p><pre>class Sesi:<br>    def __init__(self, waktu_mulai, waktu_selesai, pasien, konselor):<br>        self.waktu_mulai = waktu_mulai<br>        self.waktu_selesai = waktu_selesai<br>        self.pasien = pasien<br>        self.konselor = konselor<br><br>    def __str__(self):<br>        if self.pasien is not None:<br>            return f&quot;Pasien: {self.pasien}, Konselor: {self.konselor}, {self.waktu_mulai}-{self.waktu_selesai}&quot;<br>        return f&quot;Konselor: {self.konselor}, {self.waktu_mulai}-{self.waktu_selesai}&quot;<br><br>    <br>    def __eq__(self, other):<br>        if not isinstance(other, Sesi):<br>            return False<br>        return (self.waktu_mulai == other.waktu_mulai and<br>                self.waktu_selesai == other.waktu_selesai and<br>                self.pasien == other.pasien and<br>                self.konselor == other.konselor)</pre><p>Later, we will serialize the instance of this DTO class by converting it to JSON or other common formats to transfer the data to another services or applications, in this case: front-end service.</p><pre>class SesiSerializer(serializers.Serializer):<br>    waktu_mulai = serializers.TimeField()<br>    waktu_selesai = serializers.TimeField()<br>    pasien = serializers.CharField()<br>    konselor = serializers.CharField()</pre><h4>MVC (or MTV, by default in Django)</h4><p>MVC (Model-View-Controller) is a design pattern commonly used for developing user interfaces that separate the program logic into three interconnected elements, namely model, view, and controller. Model is responsible for managing data, view is responsible for handling display, and controller is responsible for routing commands to the model and view parts.</p><p>In Django, they have different terminologies. You can see the differences below.</p><ol><li>Model is called Model in Django</li><li>View is called Template in Django</li><li>Controller is called View in Django</li></ol><p>However, me and my colleagues implement this quite differently compared to standard MVT in Django. In the original implementation, people treat View in Django as a combination between controller and service. So, basically, accessing database and serializing the result into JSON are done in the same method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/789/1*LBcJux-YnDYRaInNLnGvBA.png" /><figcaption>Source: <a href="https://docs.djangoproject.com/en/5.0/topics/http/views/">Writing views | Django documentation | Django (djangoproject.com)</a></figcaption></figure><p>Nevertheless, we’ve found that these implementations do not adhere to the <strong>Single Responsibility Principle</strong>. So, we decided to separate it into different controller and service method. Service will handle the business logic and controller will handle the communication stuff, such as serializing the data into JSON, providing endpoints, etc.</p><pre>from konseling.models import Konselor, User<br><br>class PasienSelesaiService:<br>    def get_all_pasien_selesai(self):<br>        # hanya mengambil yang selesai<br>        return User.objects.filter(pendaftaran__status__state_order=3).distinct()</pre><pre>from konseling.serializers import KonselorUtilsSerializer, UserUtilsSerializer<br>from konseling.services.utils_api_service import PasienSelesaiService<br>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>import json<br><br>class PasienSelesaiGetAPIView(APIView):<br>    def get(self, request):<br>        pasien_selesai_service = PasienSelesaiService()<br>        pasien_all = pasien_selesai_service.get_all_pasien_selesai()<br>        serializer = UserUtilsSerializer(pasien_all, many=True)<br>        return Response(json.loads(json.dumps(serializer.data)), status=200)</pre><p>Much better, right? :-)</p><h3>To sum it up, how to refactor?</h3><ol><li>Be familiar with some code smells and anti-patterns that may appear. You can also identify whether you can utilize design patterns to make your code well-organized. You can read about code smells and design patterns here in <a href="https://refactoring.guru/refactoring/smells">refactoring.guru</a>. Definitely worth the time!</li><li>Check any code smells detected by SonarQube analysis after pushing your code to the remote repository. You should also check any other potential code smells that are not detected by SonarQube.</li><li>Refactor it based on the guidelines provided by SonarQube.</li><li>Run the test to ensure the newly refactored code still behaves the same like before.</li><li>Push your code to the remote repository. Don’t forget to use the [REFACTOR] tag!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/0*5AFTcFw4BEebt9O7.jpg" /><figcaption>Source: <a href="https://devrant.com/rants/2056893/when-optimizing-becomes-ur-curse">devrant — When optimizing becomes ur curse… — devRant</a></figcaption></figure><p>It may seem daunting at first, because changing your code just a little bit sometimes can make the IDE scold you by giving those errors and warnings. However, be patient, try to evaluate all errors and warnings, and eventually fix them all. In the end, your code will be waaaay better than before. Good luck and make sure to set your standard high in terms of code quality!</p><h3>References</h3><p><a href="https://www.techtarget.com/searchapparchitecture/definition/refactoring">What is Refactoring (Code Refactoring)? (techtarget.com)</a></p><p><a href="https://refactoring.guru/refactoring/when">When to refactor (refactoring.guru)</a></p><p><a href="https://bariscimen.medium.com/10-most-common-anti-patterns-every-software-engineer-must-avoid-182091438c2b">10 Most Common Anti-Patterns Every Software Engineer Must Avoid! | by Barış Çimen | Medium</a></p><p><a href="https://www.pcmag.com/encyclopedia/term/spaghetti-code">Definition of spaghetti code | PCMag</a></p><p><a href="https://www.linkedin.com/advice/3/how-do-you-follow-principles-modularity-reusability">How do you follow the principles of modularity and reusability in your code? (linkedin.com)</a></p><p><a href="https://refactoring.guru/design-patterns">Design Patterns (refactoring.guru)</a></p><p><a href="https://refactoring.guru/design-patterns/classification">Classification of patterns (refactoring.guru)</a></p><p><a href="https://www.baeldung.com/java-dto-pattern">The DTO Pattern (Data Transfer Object) | Baeldung</a></p><p><a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">Model–view–controller — Wikipedia</a></p><p><a href="https://developer.mozilla.org/en-US/docs/Glossary/MVC">MVC — MDN Web Docs Glossary: Definitions of Web-related terms | MDN (mozilla.org)</a></p><p><a href="https://refactoring.guru/design-patterns/strategy">Strategy (refactoring.guru)</a></p><p>Advanced Programming Lecture Slide: Compound Patterns, Term 2 2022/2023</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4890fd01f237" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working in a Team 101]]></title>
            <link>https://medium.com/@jaycentg/working-in-a-team-101-fa65a204028b?source=rss-3f05c5ac32c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa65a204028b</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[jira]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Jaycent Gunawan Ongris]]></dc:creator>
            <pubDate>Sat, 02 Mar 2024 10:48:05 GMT</pubDate>
            <atom:updated>2024-05-22T10:20:33.780Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*H45vt1vHFlNsZb46.png" /><figcaption>Source: <a href="https://www.pinterest.com/pin/484207397443804039/">Teamwork | Programmer humor, Programming humor, Computer science humor (pinterest.com)</a></figcaption></figure><p>Time to take a break from writing about technical programming stuff. In this blog, we are going to talk about working in a team in developing software. You can’t develop a big software on your own, or you can if you want to get scolded by the client because you deliver the working software several months after the deadline 🤔</p><p>Working alone in a software development is tough, and so does working in a team. You have to juggle between multiple responsibilities, coordinate with team members, and ensure that everyone is on the same page. There are lots of soft skills needed in doing team-based projects, such as communication, adaptability, conflict management, and many more.</p><h3>Challenges</h3><p>Managing a software development project could be immensely hard, especially when the scope of the software is huge, like the project I am currently doing. My team is assigned to create a counseling booking system website for BKM UI, student’s counseling organization in my university. Since the project scope is quite big, the team is divided into two sub-teams to handle the user side and the admin side separately. My sub-team develops the admin side website.</p><p>THAT is the tough part. Besides coordinating with my own sub-team members, I have to coordinate with another sub-team to make sure that we are on the same track. We have to coordinate a lot regarding the features separation and technical things, such as the tech stacks, API contracts, etc. Indeed, we conducted sprint planning beforehand, but there are some things that we still have to discuss throughout the sprint process. But, anyways, that is a normal thing to do in a team; I guess it is only me who hasn’t gotten accustomed to the workflow 😅</p><p>OK, let’s assume that the features have been separated and every task has been assigned to each team member. Now, how do we manage and track all the tasks effectively? <em>Nah, I ain’t gonna use Excel, mate</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/0*3YKnN5bMg0V3C7Li.jpeg" /><figcaption>Source: <a href="https://blog.transparentchoice.com/pmos-and-the-saddest-excel-joke">PMOs and the Saddest Excel Joke… (transparentchoice.com)</a></figcaption></figure><p>Obviously, we don’t want the development process hindered by ineffective task management. We have to track the progress of each task and the overall project clearly, so that there is no overlapping task being done by more than one member. Hence, without further ado, let me introduce you to project management software called Jira,̶ ̶w̶h̶i̶c̶h̶ ̶i̶s̶ ̶w̶a̶a̶a̶a̶y̶ ̶b̶e̶t̶t̶e̶r̶ ̶t̶h̶a̶n̶ ̶E̶x̶c̶e̶l̶ ̶i̶n̶ ̶d̶o̶i̶n̶g̶ ̶p̶r̶o̶j̶e̶c̶t̶ ̶m̶a̶n̶a̶g̶e̶m̶e̶n̶t̶ ̶t̶a̶s̶k̶s̶.</p><h3>Project Management Software: Jira</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*IIqVGv31UCbqkufy.jpg" /><figcaption>Even this wise Yoda knows that you have to use project management software, although he is not a PM 😆Source: <a href="https://twitter.com/workep/status/1101482695388000261?lang=zh-Hant">X (twitter.com)</a></figcaption></figure><p>Okay, what’s Jira though? In a nutshell, Jira is a project management tool developed by Atlassian. There are so many useful features provided by Jira, such as issue tracking, scrum board, dashboards, and many more.</p><p>In Jira, we can just define the sprint and its details, such as sprint goal, sprint period, and backlogs you want to complete in that sprint period.</p><h4>Jira’s Backlog Page</h4><p>For each backlog, you can specify the description of the backlog, the story point, and tasks included in the backlog. Furthermore, we can also assign a team member to a task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F1uxUbGCW9QKYx31CwZzHw.png" /><figcaption>Source: My Team’s Jira Backlog Page</figcaption></figure><p>But… where is the task tracking part? You can track the progress of each task or backlog by looking at the status and changing it if necessary.</p><blockquote><strong><em>Pro Tip</em></strong><em>: Remember to change the status every time you have finished your work, otherwise the report would be misleading :D</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*kyYefU8WSIMOAQXynwhCVQ.png" /><figcaption>Source: My Team’s Jira Backlog Page</figcaption></figure><h4>Jira’s Scrum Board</h4><p>Another important feature that Jira has is called scrum board. Scrum board is basically the summary of all backlogs you have defined, grouped by the status. By using this, you can track the progress of each backlog clearly, leading to a more efficient workflow and task management 👍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AXowmjb0WP3olBVncOLgJA.png" /><figcaption>Source: My Team’s Jira Scrum Board</figcaption></figure><h4>Jira’s Timeline Progress</h4><p>Not only that, but there is also a feature in Jira to inspect the project timeline. You can see which epics are in progress for every sprint. In the left side under the epic name, you can see the progress of the backlogs, which denoted by three colors: green means the backlog is done, blue means the backlog is still in progress, and gray means the backlog is yet to be worked on (still on TO DO).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*IJwaxhgfkXFMgVaqXSwJgw.png" /><figcaption>Source: My Team’s Jira Timeline</figcaption></figure><p>We can also zoom in to see the detail for each epic. For instance, I want to see the progress for the backlogs in Konseling (Admin) epic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*CfbnihWK7JRF05tyQ1dCgw.png" /><figcaption>Source: My Team’s Jira Timeline for Konseling Epic</figcaption></figure><p>You can see that there is only one backlog remains in progress for that epic, which is actually expected to be done in this second sprint.</p><h4>Jira’s Insights Tab</h4><p>Lastly, you can view the progress of your sprint in the ‘Insights’ tab. You can find this by going to ‘Board’ page and click ‘Insights’ button on the right side of ‘View settings’ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*xWQAfPi3CEonb_G8T0bEPg.png" /><figcaption>Captured this upon completion of Sprint 3, but anyways, this is my Sprint 3’s progress.</figcaption></figure><p>Just like its name, this feature provides so many insights about how the sprint is going, such as the overall progress, burndown chart, and epic progress.</p><p>For the overall progress, you can get the overall percentage of tasks that have been done, in progress, and not started. Meanwhile, for the epic progress, you can get the overall percentage of tasks that have been done <strong>in that specific epic</strong>. Just to recall, an epic is a large body of work that can be broken down into a number of smaller stories.</p><p>The sprint burndown chart is a visualization of the progress made during a sprint in agile project management. It tracks the completion of work over time, typically displayed in daily basis. It consists of two main components: the x-axis which represents time (usually measured in days) and the y-axis which represents amount of work (usually measured in story points). As you can see, our group finished all the targeted story points in that sprint, which was 59, although not following the ideal “linear” guideline. We can see that most of the tasks were being done in the second half of the sprint.</p><p>Besides that, most of the group members used to forget changing the status of the task upon completing it, making the burndown chart very asymmetrical. We have addressed this issue in the sprint retrospective, and we are currently trying to fix this behavior by reminding each other pretty often.</p><h4>Jira, is it complex?</h4><p>It is hard to deny that Jira is quite complex and hard to learn, especially for beginners who have never used project management tool before, just like me. There are so many new technical terms and features I have just known after using Jira. Thankfully, there are lots of tutorials out there to explain how to use Jira properly. Once you master it, I believe that you will find this tool is very helpful, not only in the software engineering field, but also in another fields that require project management.</p><h3>Using Git as Communication Platform</h3><p>I am writing this not to discourage you from using other social media, such as Slack, Discord, etc. as a media to communicate with another team member. It is OK to use them if you want to talk about something that is not directly related to the code. However, if you want to talk about code, GitLab has provided a feature for you to comment on others’ commits and merge requests. Take a look at these pictures below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*56FVoywMJZOggbsrKxMaGQ.png" /><figcaption>Source: My Chat Reviewing Others’ Code in Discord xD</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgIBbEBQnHuQRU2oUAT_mw.png" /><figcaption>Source: My Comment on Other Member’s Commit</figcaption></figure><p>Which one is better? The second one, right? Firstly, you don’t have to send a screenshot of the code snippet to the group. Instead, you can comment directly on other’s commit in GitLab, so they can understand the context of your comment better. Secondly, it serves as a ‘documentation’ for future reference. It can be valuable for both current team members and future developers who may need to understand the code. L̶a̶s̶t̶l̶y̶,̶ ̶y̶o̶u̶ ̶c̶a̶n̶ ̶g̶e̶t̶ ̶a̶ ̶h̶i̶g̶h̶ ̶s̶c̶o̶r̶e̶ ̶o̶f̶ ̶d̶e̶v̶e̶l̶o̶p̶m̶e̶n̶t̶ ̶d̶i̶s̶c̶i̶p̶l̶i̶n̶e̶ ̶c̶o̶m̶p̶e̶t̶e̶n̶c̶e̶ ̶i̶n̶ ̶t̶h̶e̶ ̶i̶n̶d̶i̶v̶i̶d̶u̶a̶l̶ ̶r̶e̶v̶i̶e̶w̶.̶</p><p>Writing comments on others’ code is important, but make sure the comment you write is helpful in identifying potential bugs, code smells, and other issues, not just throwing LGTM randomly in others’ commits or merge requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*bJ9dXhDtSKGforM8NDj6Qg.png" /><figcaption>Source: My Own Documentation🤫</figcaption></figure><p>Besides commenting on others’ commits, you can utilize commit message as a medium of communication. Ensure that your commit message is descriptive enough so that others can understand the changes you made. There are several conventions on how to write commit messages, but my team uses this <a href="https://gist.github.com/qoomon/5dfcdf8eec66a051ecd85625518cfd13">Conventional Commit Messages (github.com)</a>. Note that if you are working with TDD, you must denote your commits with [RED], [GREEN], or [REFACTOR] tags to show which phase you are in while developing the module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3RBejAi5eGsNVKmbeQUT7A.png" /><figcaption>Source: Several Commits I Made</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/0*JszZBipT02XWBDYD.jpeg" /><figcaption>Don’t be like Adam. Source: <a href="https://www.reddit.com/r/ProgrammerHumor/comments/1cxr9yl/yesitisreallygood/">yesItIsReallyGood : r/ProgrammerHumor (reddit.com)</a></figcaption></figure><h3>After Using Jira and GitLab for More Than One Month</h3><p>Jira has been really helpful for my team during the scrum process. With those versatile features, especially scrum board, have increased our flexibility and transparency in the task management. We can easily track the status of each backlog very easy since they are all displayed in an intuitive display, separated by columns. Thus, we can quickly notice if someone has been working on the same backlog for a long time and decide what action should be done to mitigate that.</p><p>From my personal experience, Jira has increased my workflow and productivity, especially when doing task that is highly correlated with others. Let’s say that I am currently working on this front-end task. If I need some clarifications regarding the API or other back-end stuff, I can just inspect who is currently working on the back-end task for that backlog and contacting them directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*goj4aKBlo1sVL6omWRmahA.png" /><figcaption>Source: My Team’s Jira Scrum Board</figcaption></figure><p>After decisions have been made, we can just update the description of that task, so that it can be reviewed later, instead of putting that on any note-taking platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*MTNFhr7cw5k34yK_fdYOyg.png" /><figcaption>Source: My Team’s Jira Task Detail</figcaption></figure><blockquote>If I need to know something important related to the project, I just go to Jira.</blockquote><p>Overall, Jira has been very helpful in increasing our team’s productivity. What about GitLab? The same as well. Commenting on merge requests and commits (and Git, overall) streamlines our communication process. We can minimize screenshotting our code and share it to the team’s Discord server. Instead, every time a commit or merge request is made, available team members can simply review the code by commenting directly on GitLab. Furthermore, we also integrate GitLab with the team’s Discord server, so that any changes made in the repository will trigger a notification in Discord, which is really useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nLH6d25HRtnRlaFR5mlKSQ.png" /><figcaption>Source: My Team’s Discord Server</figcaption></figure><h3>Lessons Learned</h3><p>There are many ways you can increase your workflow’s efficiency. For instance, you can utilize project management tools like Trello or ClickUp, not necessarily limited to Jira. Furthermore, enhancing communication through Git by commenting on others’ commits or merge requests, as well as writing descriptive commit messages, can significantly improve collaboration and understanding within your team. By implementing these practices, you can streamline your development processes and eventually achieve higher productivity.</p><h3>References</h3><p><a href="https://en.wikipedia.org/wiki/Jira_(software)">Jira (software) — Wikipedia</a></p><p><a href="https://www.atlassian.com/agile/project-management/epics#:~:text=An%20epic%20is%20a%20large,over%20a%20set%20of%20sprints">https://www.atlassian.com/agile/project-management/epics</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa65a204028b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CI/CD: Where Bugs Go to Die (or Multiply????)]]></title>
            <link>https://medium.com/@jaycentg/ci-cd-where-bugs-go-to-die-or-multiply-49a0ddff36b7?source=rss-3f05c5ac32c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/49a0ddff36b7</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[sonarqube]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Jaycent Gunawan Ongris]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 07:00:33 GMT</pubDate>
            <atom:updated>2024-05-22T05:08:29.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IC_N9P4Eu1NO1UkE.png" /><figcaption>Source: <a href="https://www.freecodecamp.org/news/automate-mern-app-deployment-with-jenkins/">MERN App Development — How to Build a CI/CD Pipeline with Jenkins (freecodecamp.org)</a></figcaption></figure><p>Uh, CI/CD. Continuous Integration and Continuous Delivery. Most programmers mention these two terms together all the time. However, how do they differ though? What is CI and what is CD, actually? Why do they important in saving programmers’ time a̶n̶d̶ ̶l̶i̶f̶e̶?</p><p>Let’s delve into CI first. CI stands for Continuous Integration, which process involves automatically integrating code changes from several developers into a shared repository by continuously building and testing it. By implementing this process, you can find bugs earlier to prevent them propagate into the codebase.</p><p>Meanwhile, CD stands for Continuous Delivery (or Continuous Deployment). This process is executed after your code is rigorously being tested in the CI process to make sure the code is ready for delivery. In a nutshell, CD as Continuous Delivery ensures that all code changes are ready for release after passing the CI process. Meanwhile, CD as Continuous Deployment — as what the name implies — is one step further than CD as Continuous Delivery, by automatically releasing changes to production after they pass the tests without explicit approval or human intervention.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*OC11hb1WJ-th-154.png" /><figcaption>Source: <a href="https://blog.openreplay.com/what-is-a-ci-cd-pipeline/">What is a CI/CD pipeline? (openreplay.com)</a></figcaption></figure><p>As you can see in the diagram above, there are several steps (or stages) in each pipeline. CI pipeline consists of build stage and test stage, whereas CD pipeline mainly consists of deploy stage. However, you may add another stages if needed.</p><p>OK, enough for the introduction, I guess. Let’s jump into the implementation. In this project, I use GitLab Enterprise (GitLab CSUI) as the repository to host the code. As I am using GitLab, stages I want to apply in the CI/CD pipeline should be defined in a .gitlab-ci.yml file. If you use GitHub, you can define the stages in a yml file inside .github/workflows directory.</p><p>Below is the content of my .gitlab-ci.yml.</p><pre>stages:<br>  - build<br>  - test<br>  - sonarqube-check<br>  - publish<br>  - deploy<br><br>build:<br>  stage: build<br>  image: python:3.10<br>  script:<br>    - pip install -r requirements.txt<br>    - python manage.py makemigrations<br>    - python manage.py migrate<br><br>sonarqube:<br>  stage: sonarqube-check<br>  image: sonarsource/sonar-scanner-cli:latest<br>  variables:<br>    SONAR_USER_HOME: &quot;${CI_PROJECT_DIR}/.sonar&quot;  # Defines the location of the analysis task cache<br>    GIT_DEPTH: &quot;0&quot;  # Tells git to fetch all the branches of the project, required by the analysis task<br>  cache:<br>    key: &quot;${CI_JOB_NAME}&quot;<br>    paths:<br>      - .sonar/cache<br>  script:<br>    - sonar-scanner -D&quot;sonar.projectKey=${SONAR_PROJECT_KEY}&quot; -D&quot;sonar.login=${SONAR_TOKEN}&quot; -D&quot;sonar.coverage.reportPaths=coverage.xml&quot;<br>  dependencies:<br>    - test<br>  allow_failure: true<br><br>test:<br>  stage: test<br>  image: python:3.10<br>  script:<br>    - pip install -r requirements.txt<br>    - coverage run manage.py test<br>    - coverage xml -i<br>    - coverage report -m<br>  artifacts:<br>    paths:<br>      - coverage.xml<br><br>publish_staging:<br>  stage: publish<br>  image: docker:latest<br>  services:<br>    - name: docker:dind<br>      alias: thedockerhost<br>  variables:<br>    DOCKER_DRIVER: overlay2<br>    DOCKER_TLS_CERTDIR: &quot;&quot;<br>  before_script:<br>    - apk add --no-cache bash<br>    - chmod +x ./setup_env.sh<br>    - bash ./setup_env.sh<br>    - echo $(ls -al)<br>    - echo &quot;$CI_REGISTRY_PASSWORD&quot; | docker login -u &quot;$CI_REGISTRY_USER&quot; --password-stdin docker.io<br>  script:<br>    - docker info<br>    - docker build --pull -t $CI_REGISTRY_USER/$CI_REGISTRY_IMAGE .<br>    - docker push $CI_REGISTRY_USER/$CI_REGISTRY_IMAGE<br>  only:<br>    - staging<br><br>deploy_staging:<br>  stage: deploy<br>  tags:<br>    - deploy-stg<br>  before_script:<br>    - chmod 400 $STG_SSH_KEY<br>    - apt-get update &amp;&amp; apt-get install -y openssh-client<br>  script:<br>    - ssh -o StrictHostKeyChecking=no -i $STG_SSH_KEY $STG_SSH_USERNAME@$STG_STATIC_IP &quot;<br>      sudo docker container rm -f $CONTAINER_NAME || true &amp;&amp;<br>      sudo docker image rm -f $CI_REGISTRY_USER/$CI_REGISTRY_IMAGE:latest || true &amp;&amp;<br>      sudo docker run --name $CONTAINER_NAME -d -p 8000:8000 $CI_REGISTRY_USER/$CI_REGISTRY_IMAGE:latest&quot;<br>  only:<br>    - staging</pre><p>Disclaimer: For now, I only prepare the pipeline for staging environment, since we are going to deploy the application to production in an on-premise faculty’s server, which documentation hasn’t been released yet — at least until the time I write this blog.</p><p>The CI pipeline consists of build, test, and sonarqube-check, whereas the CD pipeline consists of publish and deploy. Let’s break down each stage I have already defined in the script.</p><h3>The Build Stage</h3><p>This stage is pretty straight-forward. It builds the application we have pushed in the repository by installing the package requirements and conducting database migrations.</p><h3>The Test Stage</h3><p>Guess this one is pretty straight-forward, too, huh? It is actually the same as the build stage, we have to install the package requirements first, since they don’t share the same environment. Next, we have to run the test case to make sure that the program is free of bug. Do note that I am not using the classic python manage.py test to test the application here. I use coverage run manage.py test because I want to analyze the code coverage of the software, which function provided by coverage package. Lastly, I want to generate a coverage report in XML by applying coverage xml -i, as well as displaying the report on the CLI using coverage report -m.</p><h3>The SonarQube-Check Stage</h3><p>SonarQube is basically a quality assurance software to check the quality of the code you have pushed to the repository. Well, not necessarily in the “repository”, since we can run the check on our local environment, too. But, hey, this is where CI/CD comes in handy, to prevent us doing the same repetitive action again and again and again. You don’t want to type this looooooong SonarQube command all the time, right. Perhaps you can save it in a text file and copy-pasting it to the terminal every time you want SonarQube to run the check on your code, but if you can automate it, why not? :D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*IHBCTlL6EBpQDJxi.jpeg" /><figcaption>Source: <a href="https://www.kitchensoap.com/2012/09/21/a-mature-role-for-automation-part-i/">Kitchen Soap — A Mature Role for Automation: Part I</a></figcaption></figure><p>Yeah, I am using the same meme again. O̶r̶ ̶p̶e̶r̶h̶a̶p̶s̶ ̶w̶e̶ ̶c̶a̶n̶ ̶a̶u̶t̶o̶m̶a̶t̶e̶ ̶t̶h̶e̶ ̶p̶r̶o̶d̶u̶c̶t̶i̶o̶n̶ ̶o̶f̶ ̶t̶h̶i̶s̶ ̶m̶e̶m̶e̶?̶</p><p>But, anyway, let’s get back to the topic. You can put the SonarQube command in the .gitlab-ci.yml file and let GitLab does the rest to contact SonarQube to analyze your code every time you push a new change.</p><p>SonarQube can give you a detailed analysis of the quality of your code, such as bugs, vulnerabilities, security hotspots, and even code smells (WOW!). You may want to use this platform if you want to maintain the quality of your code. Super recommended if you are into SQA kinda stuff 👍</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtxiB2BH0AVbX4TWd8tHtg.png" /><figcaption>Source: My Team Project’s SonarQube Report</figcaption></figure><p>You may also need an additional file called sonar-project.properties to specify things such as the SonarQube Host URL, files to exclude and include, the encoding, etc., otherwise you have to put that in the script again. And.. yeah, don’t forget to put the SonarQube credentials in the environment variables 🤓</p><h3>The Publish Stage</h3><p>Here comes the CD (read: hard) part. Basically, we will utilize Docker in the CD part. Yep, that enormous blue whale with containers above it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*3Bs4IN-S1a83DoRj" /><figcaption>Source: <a href="https://www.networkworld.com/article/940638/docker-the-container-company-with-a-whale-of-a-logo-adopted-a-real-whale.html">Docker, the container company with a whale of a logo, “adopted” a real whale | Network World</a></figcaption></figure><p>Docker is a very important tool to deliver software in an isolated environment called container. Referring to Docker’s website, a container is a standard unit of software that packages up code and all its dependencies so the application runs quickly and reliably from one computing environment to another. Long story short, container technology is made because of this reason:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/0*hYDV_AEZOTZBRVrr.png" /><figcaption>Source: <a href="https://medium.com/nerd-for-tech/docker-in-a-nutshell-but-it-works-on-my-machine-well-then-lets-ship-your-machine-81c6df27ade5">Docker — “But it works on my machine…” Then we’ll ship your machine! | by Aditya Singh | Nerd For Tech | Medium</a></figcaption></figure><p>So, Docker is basically shipping containers which are actually entire computers, included with the operating system, the codebase, and its dependencies. Seems interesting, right?</p><p>Now, how do we create a container? Before get into it, we have to understand the concept of ✨image✨. Image is basically a static blueprint for an application which defines the required environment and dependencies. On the other side, container is an isolated, dynamic, and runnable instance of that image. Struggling in grasping this concept? Remember about the concept of objects and classes in OOP. Classes are associated with images, whereas objects are associated with containers :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/0*4iOn1DUti_xIq6Xk.png" /><figcaption>Source: <a href="https://dhathriblog.medium.com/difference-between-docker-image-and-container-85354526c914">Difference between Docker Image and Container. | by Dhathri Vupparapalli | Medium</a></figcaption></figure><p>To put it simply, containers are basically <strong>activated</strong> images.</p><p>In this step, we are going to create an image and push it into the container registry. Container registry is a place to store container images. Docker build the image based on what you have specified in the Dockerfile. Mine look like this.</p><pre># base image  <br>FROM python:3.10<br><br>ENV PYTHONUNBUFFERED=1<br><br># working at default directory <br>WORKDIR .<br><br># copy whole project to your docker home directory. <br>COPY . .<br><br># create virtual environment<br>CMD [&quot;/bin/bash -c source venv/bin/activate&quot;]<br><br># install dependencies  <br>RUN pip install --upgrade pip  <br><br># run this command to install all dependencies  <br>RUN pip install -r requirements.txt <br><br># port where the Django app runs  <br>EXPOSE 8000<br><br># start server  <br>CMD [&quot;python&quot;, &quot;manage.py&quot;, &quot;runserver&quot;, &quot;0.0.0.0:8000&quot;]</pre><p>You can see the description in the comment lines which start with #. This file contains a set of instructions for building a Docker image using docker build command. After that, we can push the created image to the container registry using docker push command.</p><h3>The Deploy Stage</h3><p>Yeay, we have come to the last part of the script. In this project, we are going to deploy the application on Google Cloud Platform (big thanks to the lecturers who have given us $50 GCP credit 😁).</p><p>In a nutshell, this stage is just running the container we have made in the GCP virtual machine. So, before doing that, we have to log in to the VM using SSH by specifying the SSH key, username, and VM’s external IP address. After that, we can clean the environment by remove the existing container and image with the same name by applying docker container -rm and docker image -rm if they exist. Finally, run the Docker container by pulling the latest specified image in the container registry and exposing port 8000 on the host and mapping it also to port 8000 in the container.</p><p>You can access the deployed application by visiting this URL: http://&lt;VM_EXTERNAL_IP&gt;:8000.</p><h3>The HEALTHCHECK Command</h3><p>Besides normal configuration as explained before, we can also perform HEALTHCHECK command. This HEALTHCHECK command lets us to assess and report the health of a running container based on the application it hosts. Using HEALTHCHECK, we can specify a command which can indicate the “healthiness” of the container and this command will be executed at regular intervals. If this user-defined command executed successfully, the container is considered healthy, otherwise it will be flagged as unhealthy.</p><p>In this project, I will use curl <a href="http://localhost:8000/docs/">http://localhost:8000/docs/</a> to check the condition of the container. This curl command is just basically try to retrieve the page of the API docs (doing HTTP GET). If the API docs is retrieved successfully, this means the container is running and we can access the application hosted in it.</p><p>We can just simply add the curl command in the HEALTHCHECK part along with other parameters you may want to specify. This HEALTHCHECK command is put in the Dockerfile, after exposing the port of the application. The command would look like this.</p><pre>HEALTHCHECK --interval=3m --timeout=30s --start-period=5s --retries=3 \<br>    CMD curl --fail http://localhost:8000/docs/ || exit 1</pre><p>There are several parameters I use in this command.</p><ul><li>--interval specifies the time between healthcheck executions. This means that healthcheck is executed every 3 minutes.</li><li>--timeout specifies the maximum time Docker should wait for a healthcheck to complete. In this case, I set this to 30 seconds. If the healthcheck execution takes a longer time than this, it is considered as a failed condition.</li><li>--start-period specifies the amount of time to wait before performing healthcheck. This means that Docker will wait 5 seconds after the container is started before executing healthcheck.</li><li>--retries specifies the number of consecutive failures needed to flag a container as unhealthy. If it can’t curl the docs for 3 times consecutively, Docker will flag the container as unhealthy.</li></ul><p>We can specify the specific command we want to use to inspect the container after CMD tag, in this case the curl command.</p><p>After that, we can check the status of the container by running docker ps in the VM. As you can see, the container with jaycentg/bkm-staging:staging image condition is healthy, as specified in the STATUS column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-bzFQCA88ljiF2REw4hmWA.png" /></figure><h3>Lessons Learned</h3><p>Applying this CI/CD pipeline will definitely ease programmer’s job, as everything will be conducted automatically after pushing the code into the repository. Indeed, it takes a lot of time in writing the suitable configuration for the application, but believe me, it is worth it in the end :)))</p><h3>References</h3><p><a href="https://www.linkedin.com/pulse/point-3-continuous-integration-ci-context-reducing-bugs-jovovic/">(5) Point 3. Continuous Integration (CI) — In the context of reducing bugs in production | LinkedIn</a></p><p><a href="https://www.atlassian.com/continuous-delivery/principles/continuous-integration-vs-delivery-vs-deployment">Continuous integration vs. delivery vs. deployment (atlassian.com)</a></p><p><a href="https://aws.amazon.com/devops/continuous-delivery/">What is Continuous Delivery? — Amazon Web Services</a></p><p><a href="https://katalon.com/resources-center/blog/continuous-delivery-vs-continuous-deployment">Continuous Delivery vs. Continuous Deployment: A Comparison (katalon.com)</a></p><p><a href="https://lumigo.io/container-monitoring/docker-health-check-a-practical-guide/">Docker Health Check: A Practical Guide — Lumigo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49a0ddff36b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test-Driven Development: A Decent Approach to Bugless Code]]></title>
            <link>https://medium.com/@jaycentg/test-driven-development-a-decent-approach-to-bugless-code-7463965069c3?source=rss-3f05c5ac32c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7463965069c3</guid>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Jaycent Gunawan Ongris]]></dc:creator>
            <pubDate>Tue, 27 Feb 2024 07:56:39 GMT</pubDate>
            <atom:updated>2024-05-15T08:59:35.586Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/575/0*pqyTheZytgn3JfgS" /><figcaption>Source: <a href="https://www.linkedin.com/pulse/test-driven-development-tdd-why-you-should-care-lance-harvie">LinkedIn</a></figcaption></figure><p><strong>Have you ever tried writing tests before coding? </strong>If the answer is no, then we are actually the same — at least before I decided to jump into ✨Test-Driven Development✨ in this Software Engineering Project course. Perhaps for some programmers who don’t know about TDD before, this behavior is just bizarre. Why focus on tests when creating a working software is more important? Well, you are <em>partially</em> right. At the end of the day, people will only inspect your work based on the working software. However, the working software is worthless if the output is not what we expected. This is actually the importance of testing: to ensure that the software is not just working, but also working <strong>correctly</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*eZa3z_Secb07HNtZ.jpeg" /><figcaption>Source: <a href="https://mailtrap.io/blog/qa-testing-memes/">QA Testing Memes | Mailtrap Blog</a></figcaption></figure><p>Yup, tests are everywhere when we are talking about test-driven development. Test-driven development is basically a software engineering practice that emphasizes on unit test creation before developing the code. It is an iterative approach consisting of creating unit tests, coding, and refactoring. There are three phases: Red, Green, and Refactor, as seen on the diagram below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/0*eOFgUXy3XpDPIKg0.png" /><figcaption>Source: <a href="https://www.spiceworks.com/tech/devops/articles/what-is-tdd/">What is TDD (Test Driven Development)? (spiceworks.com)</a></figcaption></figure><p>Well, I guess enough for the introduction. Let’s just jump into the implementation of test-driven development itself.</p><h3>Implementation</h3><p>In the following example, I create a function to validate a counseling session schedule, to prevent conflicting schedule with the counselor’s availability. To give some context, my team is assigned to create a counseling session booking system. One of my tasks in this sprint is to develop a function I have stated before. Oh, I am using Django (Python), by the way.</p><pre>class ValidasiJadwal:<br>    def __init__(self, jadwal_start, jadwal_end):<br>        self.jadwal_start = jadwal_start<br>        self.jadwal_end = jadwal_end<br>    <br>    def is_jadwal_konselor_sesuai(self, konselor_day, konselor_start, konselor_end):<br>        pass</pre><p>Above is the function and its signatures. The function receives three parameters (excluding self, since I put this function in a class for the sake of fulfilling the SOLID principle): konselor_day: int, konselor_start: time, and konselor_end: time to specify the weekly availability of the counselor. Do note that konselor_day is an integer representing days in a week, such as Monday is represented by 0, Tuesday is represented by 1, and so on. On the other side, jadwal_start: datetimeand jadwal_end: datetime specify the to-be-checked schedule.</p><p>The next thing is to create unit test to test the code. Yup, this is the way. You have to test the empty method. Eventually, the test will fail, and it will force you to write the implementation of the method. You can commit this code with [RED] tag to denote that the test is still failed. This is how I write the test.</p><pre>class ValidasiJadwalTest(TestCase):    <br>    def test_is_jadwal_konselor_sesuai(self):<br>        day_konselor = 0 # monday<br>        start_konselor = time(8, 0, 0)<br>        end_konselor = time(16, 0, 0)<br><br>        start_1, end_1 = datetime.fromisoformat(&#39;2024-02-26T11:00:00&#39;), datetime.fromisoformat(&#39;2024-02-26T12:00:00&#39;)<br>        self.assertEqual(ValidasiJadwal(start_1, end_1).is_jadwal_konselor_sesuai(day_konselor, <br>                                                                            start_konselor, end_konselor), True)<br>        <br>        start_2, end_2 = datetime.fromisoformat(&#39;2024-02-26T07:00:00&#39;), datetime.fromisoformat(&#39;2024-02-26T08:00:00&#39;)<br>        self.assertEqual(ValidasiJadwal(start_2, end_2).is_jadwal_konselor_sesuai(day_konselor,<br>                                                                            start_konselor, end_konselor), False)<br>        <br>        start_3, end_3 = datetime.fromisoformat(&#39;2024-02-24T11:00:00&#39;), datetime.fromisoformat(&#39;2024-02-24T12:00:00&#39;)<br>        self.assertEqual(ValidasiJadwal(start_3, end_3).is_jadwal_konselor_sesuai(day_konselor,<br>                                                                            start_konselor, end_konselor), False)<br>        <br>        start_4, end_4 = datetime.fromisoformat(&#39;2024-02-26T15:00:00&#39;), datetime.fromisoformat(&#39;2024-02-26T17:00:00&#39;)<br>        self.assertEqual(ValidasiJadwal(start_4, end_4).is_jadwal_konselor_sesuai(day_konselor,<br>                                                                            start_konselor, end_konselor), False)<br>        <br>        start_5, end_5 = datetime.fromisoformat(&#39;2024-02-26T08:00:00&#39;), datetime.fromisoformat(&#39;2024-02-26T16:00:00&#39;)<br>        self.assertEqual(ValidasiJadwal(start_5, end_5).is_jadwal_konselor_sesuai(day_konselor,<br>                                                                            start_konselor, end_konselor), True)<br>        <br>        start_6, end_6 = datetime.fromisoformat(&#39;2024-02-26T16:00:00&#39;), datetime.fromisoformat(&#39;2024-02-26T17:00:00&#39;)<br>        self.assertEqual(ValidasiJadwal(start_6, end_6).is_jadwal_konselor_sesuai(day_konselor,<br>                                                                            start_konselor, end_konselor), False)<br>        <br>        start_7, end_7 = datetime.fromisoformat(&#39;2024-02-26T07:00:00&#39;), datetime.fromisoformat(&#39;2024-02-26T07:30:00&#39;)<br>        self.assertEqual(ValidasiJadwal(start_7, end_7).is_jadwal_konselor_sesuai(day_konselor,<br>                                                                            start_konselor, end_konselor), False)<br>        <br>        start_8, end_8 = datetime.fromisoformat(&#39;2024-02-26T16:10:00&#39;), datetime.fromisoformat(&#39;2024-02-26T16:30:00&#39;)<br>        self.assertEqual(ValidasiJadwal(start_8, end_8).is_jadwal_konselor_sesuai(day_konselor,<br>                                                                            start_konselor, end_konselor), False)<br>        <br>        start_9, end_9 = datetime.fromisoformat(&#39;2024-02-26T07:00:00&#39;), datetime.fromisoformat(&#39;2024-02-26T09:00:00&#39;)<br>        self.assertEqual(ValidasiJadwal(start_9, end_9).is_jadwal_konselor_sesuai(day_konselor,<br>                                                                            start_konselor, end_konselor), False)<br>        <br>        start_10, end_10 = datetime.fromisoformat(&#39;2024-02-26T08:00:00&#39;), datetime.fromisoformat(&#39;2024-02-26T09:00:00&#39;)<br>        self.assertEqual(ValidasiJadwal(start_10, end_10).is_jadwal_konselor_sesuai(day_konselor,<br>                                                                            start_konselor, end_konselor), True)<br>        <br>        start_11, end_11 = datetime.fromisoformat(&#39;2024-02-26T15:00:00&#39;), datetime.fromisoformat(&#39;2024-02-26T16:00:00&#39;)<br>        self.assertEqual(ValidasiJadwal(start_11, end_11).is_jadwal_konselor_sesuai(day_konselor,<br>                                                                            start_konselor, end_konselor), True)</pre><p>In the code, I write 11 test cases to test the expected outputs of the algorithm. Below is the explanation for each test case.</p><p>P.S.: You can skip the explanation below if you want to, there is a diagram I will introduce later to help you understand the test cases :)</p><ol><li>Test case 1: The schedule is within the counselor’s availability time.</li><li>Test case 2: The schedule starts before the counselor’s availability time but ends exactly in the start of the counselor’s availability time.</li><li>Test case 3: The schedule is in different day.</li><li>Test case 4: The schedule starts in the counselor’s availability time but ends after the counselor’s availability time.</li><li>Test case 5: The schedule exactly matches the counselor’s availability time.</li><li>Test case 6: The schedule starts exactly in the end of the counselor’s availability time and ends after the counselor’s availability time.</li><li>Test case 7: The schedule starts and ends before the counselor’s availability time.</li><li>Test case 8: The schedule starts and ends after the counselor’s availability time.</li><li>Test case 9: The schedule starts before the counselor’s availability time but ends within the counselor’s availability time.</li><li>Test case 10: The schedule starts exactly the same as the start of the counselor’s availability time and ends within the counselor’s availability time.</li><li>Test case 11: The schedule starts within the counselor’s availability time and ends exactly the same as the end of the counselor’s availability time.</li></ol><p>Feeling dizzy reading all those things? Me too. However, no worries. I have a different approach to visualize these things (and obviously it helps you to uncover all possible test cases in an easy and visual manner). Take a look at the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Frtl3N8kQqZK8-Gzy9-HDA.png" /><figcaption>Source: My own drawing :D</figcaption></figure><p>Do note that the red boxes indicate <strong>invalid schedules (negative/edge cases)</strong>, whereas the green boxes indicate <strong>valid schedules (positive cases)</strong>.</p><p>You can use the diagram above when dealing with ranged input like this. With this diagram, you can inspect all possible cases, ensuring the algorithm is bug-free. It has been helping me writing test cases without having to worry whether there are some cases that I haven’t covered in my test suite.</p><p>Guess we’ve talked about the test suite pretty detailed. Now let’s move to the implementation. Below is the implementation.</p><pre>class ValidasiJadwal:<br>    def __init__(self, jadwal_start, jadwal_end):<br>        self.jadwal_start = jadwal_start<br>        self.jadwal_end = jadwal_end<br>    <br>    def is_jadwal_konselor_sesuai(self, konselor_day, konselor_start, konselor_end):<br>        weekday = self.jadwal_start.weekday()<br>        if weekday != konselor_day:<br>            return False<br>        <br>        jadwal_start = self.jadwal_start.time()<br>        jadwal_end = self.jadwal_end.time()<br>        if (jadwal_start &gt;= konselor_start and jadwal_end &lt;= konselor_end):<br>            return True<br>        return False</pre><p>The algorithm simply checks the validity of the date first. After that, it checks whether jadwal_start and jadwal_end are within the counselor’s availability time using simple comparison.</p><p>Let’s check whether the algorithm is already correct or not by running python manage.py test or coverage run manage.py test if you use coverage package to measure the code coverage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/669/1*8zL6WNgWQQEmTVF2nFeEcA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/787/1*oCC-fkBN07TLhUTvdocj3w.png" /><figcaption>Yeay! The coverage is 100%</figcaption></figure><p>After ensuring you have covered all lines and all possible cases, you can commit with [GREEN] tag to denote that the test has passed. Later, if you want to refactor the code, you can commit with [REFACTOR] tag.</p><h3>Is there any standards to ensure that your test is “good” enough?</h3><p>Well, surely if you write some tests, make sure that the coverage is 100%. It covers all important functions, classes, and all other components. However, covering all lines of code does not ensure that your test is good enough. There are several characteristics of a good test, which we can call F.I.R.S.T principle (yes, that is an acronym).</p><h4>Fast</h4><p>Ensure that your test is quick to run, otherwise it will act as a bottleneck in the development process. With faster tests, faster feedback loop will be achieved, thus enhancing developer’s productivity. There is no absolute rule to determine whether the testing process is already fast or not. However, you can approximate it, though. If it takes up to several minutes to test several methods, maybe that is a sign for you to change your test.</p><p>In my project, there are 64 test suites, where each test suite consists of several test cases. Those tests run in approximately 1.741 s. Pretty good, right? :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*mAhFUPuzyRImWfAEU0PCqA.png" /><figcaption>Source: My Own Documentation</figcaption></figure><h4>Independent</h4><p>A test being independent means that the test is isolated from each other and it is not relying on other test’s output or state. The simplest thing you can implement this is by ensuring that each test does not call other test on its implementation. You can see the example below, each test is independent to each other, right?</p><pre>class SesiTest(TestCase):<br>    def setUp(self):<br>        self.sesi1 = Sesi(time(8, 0, 0), time(9, 0, 0), None, &quot;John Doe&quot;)<br>        self.sesi1_dup = Sesi(time(8, 0, 0), time(9, 0, 0), None, &quot;John Doe&quot;)<br>        self.sesi2 = Sesi(time(9, 0, 0), time(10, 0, 0), &quot;Doe John&quot;, &quot;John Doe&quot;)<br><br>    def test_str_representation_sesi(self):<br>        self.assertEqual(str(self.sesi1), &quot;Konselor: John Doe, 08:00:00-09:00:00&quot;)<br>        self.assertEqual(str(self.sesi1_dup), &quot;Konselor: John Doe, 08:00:00-09:00:00&quot;)<br>        self.assertEqual(str(self.sesi2), &quot;Pasien: Doe John, Konselor: John Doe, 09:00:00-10:00:00&quot;)<br>    <br>    def test_equality_berhasil(self):<br>        self.assertEqual(self.sesi1 == self.sesi1_dup, True)<br>    <br>    def test_equality_gagal(self):<br>        # sama datatype<br>        self.assertEqual(self.sesi1 == self.sesi2, False)<br>        self.assertEqual(self.sesi1_dup == self.sesi2, False)<br><br>        # beda datatype<br>        self.assertEqual(self.sesi1 == 5, False)<br>        self.assertEqual(self.sesi2 == &quot;test&quot;, False)</pre><h4>Repeatable</h4><p>This means that tests should be able to be run multiple times and still produce the same results. Maybe you think this principle is silly; if you run the same test multiple times, it is impossible to get different result if you don’t change the code. However, let’s take a look a simple example on a case where this principle might be violated.</p><pre>def generate_random_number(minimum, maximum):<br>    return random.randint(minimum, maximum)<br><br>def test_generate_random_number():<br>    minimum = 0<br>    maximum = 100<br>    random_number = generate_random_number(minimum, maximum)<br>    assert 50 &lt;= random_number &lt;= 100</pre><p>Yep, the test is non-repeatable for the case above. The generated number is non-deterministic; we can’t control which number is going to be generated. If the generated number is 0 &lt;= number &lt; 50, the test will fail. Otherwise, if the generated number is 50 &lt;= number &lt;= 100, the test will success.</p><h4>Self-Validating</h4><p>This principle refers to the ability of a test to verify its results without manual intervention. Actually, by using assert, this principle has been fulfilled. If the actual result and expected result are different, assert will throw an error and provide detailed information regarding which test has failed. Hence, we don’t need to check the result manually; all inspections will be done automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5nPsMXkViR_WIOkhwxUMw.png" /><figcaption>Example of failed test description</figcaption></figure><h4>Thorough</h4><p>This principle highlights that tests should be comprehensive and cover all relevant areas of the tested system. However, getting a 100% code coverage does not imply the test has fulfilled this principle. Programmers have to ensure that the test has covered all possible cases, including edge and negative cases. There are several ways to ensure this, for instance, I have mentioned an example previously on how to test a method with ranged input. You may scroll up to the diagram I have provided above :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*WdPsPCXWQiejCvXUWfE4Hw.jpeg" /><figcaption>Source: <a href="https://renatosugimoto.com/2023/01/29/the-pitfalls-of-high-code-coverage-and-how-TDD-can-mitigate-them.html">https://renatosugimoto.com/2023/01/29/the-pitfalls-of-high-code-coverage-and-how-TDD-can-mitigate-them.html</a></figcaption></figure><h3>Monitoring tool: SonarQube</h3><p>SonarQube can provide a detailed information regarding the code coverage. For example, take a look at this dashboard below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UPUKRuXumlVQJVRIEhEudQ.png" /></figure><p>If you click on the folder name, you can see the detailed coverage for each file, as well as lines that are not covered by tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvxkoclKxXBK7M-uwNJqTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ZSrVk0kUS9vrMIPgH18zw.png" /></figure><p>The lines with green indicators indicate that they have already been covered by tests. We can implement this in CI/CD of our application. In order to display this in SonarQube dashboard, we have to specify the path of the artifact generated by Test stage, which is coverage.xml in Cobertura format. Below is the example CI script for Test and SonarQube stages.</p><pre>Test:<br>  image: python:3.10<br>  stage: Test<br>  cache:<br>    paths:<br>      - .cache/pip<br>  before_script:<br>    - pip install -r requirements.txt<br>  script:<br>    - coverage run manage.py test<br>    - coverage xml -i<br>    - coverage report -m --precision=2<br>  artifacts:<br>    paths:<br>      - coverage.xml<br>    reports:<br>      coverage_report:<br>        coverage_format: cobertura<br>        path: coverage.xml<br>  coverage: &#39;/TOTAL.*? (100(?:\.0+)?\%|[1-9]?\d(?:\.\d+)?\%)$/&#39;<br>  interruptible: true<br><br>SonarQube:<br>  stage: Test<br>  image: sonarsource/sonar-scanner-cli:latest<br>  needs:<br>    - job: Test<br>      artifacts: true<br>  allow_failure: true<br>  variables:<br>    SONAR_USER_HOME: &quot;${CI_PROJECT_DIR}/.sonar&quot;  # Defines the location of the analysis task cache<br>    GIT_DEPTH: &quot;0&quot;  # Tells git to fetch all the branches of the project, required by the analysis task<br>  cache:<br>    key: &quot;${CI_JOB_NAME}&quot;<br>    paths:<br>      - .sonar/cache<br>  script:<br>    - sonar-scanner -D&quot;sonar.projectKey=${SONAR_PROJECT_KEY}&quot; -D&quot;sonar.login=${SONAR_TOKEN}&quot; -D&quot;sonar.python.coverage.reportPaths=./coverage.xml&quot;<br>  dependencies:<br>    - Test<br>  interruptible: true</pre><p>The main actor of this script is the sonar-scanner part. This is the command that run SonarQube analysis.</p><p>The analysis of details can be used to improve the coverage of the code.</p><h3>Incorporating TDD in all features and services</h3><p>You may ask: is it different in applying TDD for different features? Well, actually yes. In fact, you have to tailor your test depending on which feature or service you are going to test. For example, you have to take different approach in testing service and controller. Services mainly focus on business logic, so the tests have to ensure that they perform intended operations correctly. Meanwhile, controllers mainly focus on handling incoming requests, interacting with services, and finally returning appropriate responses. Hence, to test controllers, you have to ensure that if they receive certain requests, the correct services or methods will be invoked, and lastly they will return the expected responses. So, the scopes and intentions are quite different, right? :)</p><p>However, the similarity is that all of them are using the same principle: test before code. No matter what kind of features are you currently working on, you have to do the testing process before start coding. This ensures that all features have fulfilled the accepting criteria by passing all the tests.</p><p>To sum it up, you have to tailor the test based on the feature you are testing because each of them has different functionalities and responsibilities, which you should take into account when creating a test. Nevertheless, always follow the principle of TDD when developing all features, i.e. to test before coding.</p><h3>Benefits</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*N95HFyisWNmajDrK" /><figcaption>Source: <a href="https://medium.com/free-code-camp/test-driven-development-i-hated-it-now-i-cant-live-without-it-4a10b7ce7ed6">How and why I decided test driven development was worth my time | by Deasy Kiana Natalia | We’ve moved to freeCodeCamp.org/news | Medium</a></figcaption></figure><p>Well, in my opinion, there are many advantages of using TDD in your development. One of the advantages of implementing TDD is that it can help you to debug your code easily. Since you are writing unit tests every time you develop a new method, you can identify bugs earlier. And by doing this, you can prevent the inception of major bugs that probably would affect the entire program. Furthermore, it can save your precious time from doing unnecessary debugging, which leads to increased productivity and faster development. At the end, your code will become way more maintainable, and your workflow will become more productive.</p><h3>Final Words</h3><p>Perhaps many programmers have to shift their paradigms in doing programming to get used to this TDD cycle, but believe me, it is worth it. By creating tests before starting to code, you can identify bugs earlier and later you can save lots of time from debugging the code. Therefore, it will increase your productivity.</p><p><strong>TL;DR</strong></p><p>Implement TDD, it will help you to code better!</p><h3>References</h3><p><a href="https://www.browserstack.com/guide/what-is-test-driven-development">What is Test Driven Development (TDD) ? | BrowserStack</a></p><p><a href="https://www.geeksforgeeks.org/weekday-function-of-datetime-date-class-in-python/">weekday() Function Of Datetime.date Class In Python — GeeksforGeeks</a></p><p><a href="https://www.conformiq.com/resources/blog-the-six-benefits-of-test-driven-development-05-16-2023">Six Benefits of TDD in Software Testing | Conformiq</a></p><p><a href="https://medium.com/@tasdikrahman/f-i-r-s-t-principles-of-testing-1a497acda8d6">F.I.R.S.T principles of testing</a></p><p><a href="https://fueled.com/the-cache/posts/frontend/a-guide-to-first-principle/">https://fueled.com/the-cache/posts/frontend/a-guide-to-first-principle/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7463965069c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>