<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Dibyojyoti Sanyal</title>
    <description>The latest articles on DEV Community by Dibyojyoti Sanyal (@dibyojyoti).</description>
    <link>https://dev.to/dibyojyoti</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F678124%2F0dc75406-0b24-4b10-b5f1-8150e9f11eda.jpeg</url>
      <title>DEV Community: Dibyojyoti Sanyal</title>
      <link>https://dev.to/dibyojyoti</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/dibyojyoti"/>
    <language>en</language>
    <item>
      <title>How to avoid God Class in OO Programming ?</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Sun, 05 Sep 2021 10:16:35 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/how-to-avoid-god-class-in-oo-programming-1ia9</link>
      <guid>https://dev.to/dibyojyoti/how-to-avoid-god-class-in-oo-programming-1ia9</guid>
      <description>&lt;p&gt;When we learn programming we tend to put all the code in the same function or even in the same file. Especially in the functional programming paradigm, for example in C,  where the program logic is  driven by sequence of method calls and execution logic rather than communication between objects. Object oriented programming supports communication driven program execution among representations of real world objects. In functional programming as the starting point is the main method we tend to write the whole program in the same method. Sometimes we factor out the logic in separate methods which are called sequentially from the main method. At best we create separate files that contain few methods, this file can be reused. In Object oriented programming everything revolves around a few objects where one of the classes contains the main method and acts as the entry point. Object Oriented design principles suggest that there should not be one single God class. Today we will discuss what that exactly means and how to avoid creating God class. &lt;/p&gt;

&lt;h4&gt;
  
  
  What is a God Class or a God Object?
&lt;/h4&gt;

&lt;p&gt;A God class is a class that tends to have every solution possible logic. Rather than provisioning a solution to a specific problem a God Glass tends to have different kinds of code logic that solve different problems.  When we can call different methods on the same object to perform different tasks we can say the object is doing too much and it's a God object. Wikipedia has a good explanation on the God object. &lt;/p&gt;

&lt;h4&gt;
  
  
  Why do we need to avoid God Class and God Object ?
&lt;/h4&gt;

&lt;p&gt;There are many problems that are associated with God classes and God objects. Few of them I have mentioned here:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The size of code with a class increases and makes it unnecessarily complex. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;God Class and God objects creates tight coupling between unrelated code which becomes difficult to enhance and maintain in future.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The single responsibility principle in object oriented design principles says one class should only do one thing. This principle is not followed in God classes and God objects.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;As these classes and objects do many tasks they lack modularization concept which hinders code reusability.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Different independent code logics are intertwined in God classes and God objects. For this reason, testing of each functionality separately becomes difficult.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  How to detect God Class ?
&lt;/h4&gt;

&lt;p&gt;I have listed a few tips that will help you detect God Class and God Object.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Like the main method in C which is the entry point and central component that manages the whole working and dataflow, when you find similar classes or methods you can smell God Class.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Generally Gog Classes have a large  number of code lines.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A class that performs several tasks to solve different not related or less related problems are candidates for God Class. Generally these classes offer a lot of functionality which are not related.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;When a class has many unrelated properties and exposes methods to manipulate or fetch those properties, this class becomes a God Class.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  How to refactor a God class ?
&lt;/h4&gt;

&lt;p&gt;A systematic approach will let you identify, plan and get rid of the God classes and God objects.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;The first step is to identify the God classes and objects in each package and module. &lt;/li&gt;
&lt;li&gt;Next, we need to identify the clients of the God classes and objects who use these classes and objects. It will help us to assess the impact of the change we are going to perform.&lt;/li&gt;
&lt;li&gt;Then we need to come up with a new low level design to remove God classes and objects. In the design we need to take care of these below points.

&lt;ul&gt;
&lt;li&gt;For the static methods a separate utility class needs to be created because an object is not needed to invoke the static methods. &lt;/li&gt;
&lt;li&gt;Similarly the static and final variables can be separated out.&lt;/li&gt;
&lt;li&gt;Group common methods and properties following single responsibility principle. Create separate classes for each group.&lt;/li&gt;
&lt;li&gt;Use inheritance, association and aggregation to establish a clear relationship among the classes.&lt;/li&gt;
&lt;li&gt;Use &lt;a href="https://www.cloudnativemaster.com/post/cohesion-coupling"&gt;high cohesion and low coupling&lt;/a&gt; principles.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;
&lt;li&gt;Factor out the less frequently used part first and then work on refactoring other parts.&lt;/li&gt;
&lt;li&gt;Create unit tests to test the new code thoroughly.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  How to avoid creating a God class ?
&lt;/h4&gt;

&lt;p&gt;There should not be one single class that does all. Instead there should be a bunch of classes which are needed to perform some tasks in a certain sequence, and will be used at different points of time in the sequence. In certain scenarios it makes sense that, once the work of a class is completed it can be garbage destroyed or collected. To avoid one class performing more than one task, before creating a class create an interface and define the methods the interface will contain. Carefully, look at the interface methods to judge whether the methods solve only one task and the contract as a whole provides one functionality. Once you are sure, implement the interface in a class.&lt;/p&gt;

&lt;p&gt;You can refer to my &lt;a href="https://www.cloudnativemaster.com/post/avoid-god-class-in-oo-programming"&gt;blog post&lt;/a&gt; for example of God classes and solution of how we can avoid creating God classes.&lt;/p&gt;

</description>
      <category>java</category>
      <category>design</category>
      <category>architecture</category>
      <category>oop</category>
    </item>
    <item>
      <title>What design &amp; build incrementally means in OO design Principle ?</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Sun, 05 Sep 2021 09:50:22 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/what-design-build-increment-means-in-oo-design-principle-2l9i</link>
      <guid>https://dev.to/dibyojyoti/what-design-build-increment-means-in-oo-design-principle-2l9i</guid>
      <description>&lt;p&gt;This is one of the Object Oriented Design Principles that helps developers keep the code readable and understandable.&lt;/p&gt;

&lt;p&gt;When you try to make the whole design and start implementation that will not work because either you will find your previous assumptions were incorrect or the requirement changed. Therefore, it is better to design in a way that the design can be extended and the same basic design building blocks can be reused in other parts of the code. While designing we also need to adhere to homogeneity, which means similar things should be designed and implemented in a similar way and orientation of similar parts of code should look like the same.  This is how we can design and build incrementally, once small pieces at a time.&lt;/p&gt;

&lt;p&gt;Example, when you need to implement an HTTP connection and a JDBC connection to a database. The actual code will be very different but you should design it in a way that the same design patterns can be used in both places, the high level method names and the class hierarchy and relation between objects should be similar in both implementations. Though implementation details and the objects itself will be different but the interaction and responsibilities divided in different classes and methods in high level should look similar. It makes the code easy to understand also, as human nature is such that it recognizes the known patterns easily.&lt;/p&gt;

&lt;p&gt;You can refer to my &lt;a href="https://www.cloudnativemaster.com/post/what-design-build-increment-means-in-oo-design-pattern-how-to-apply-it-in-code"&gt;blog post&lt;/a&gt; for a concreate example.&lt;/p&gt;

</description>
      <category>java</category>
      <category>design</category>
      <category>architecture</category>
    </item>
    <item>
      <title>How to apply transparency in OO programming ?</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Tue, 31 Aug 2021 18:40:06 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/how-to-apply-transparency-in-oo-programming-2ffo</link>
      <guid>https://dev.to/dibyojyoti/how-to-apply-transparency-in-oo-programming-2ffo</guid>
      <description>&lt;p&gt;Transparency is one of the Object Oriented Design Principles that helps developers keep the code readable and understandable.&lt;/p&gt;

&lt;p&gt;When you look at the class or methods it should be very obvious immediately what it does, within the next 1 minute it should be obvious how it does what it does. You as a programmer should be able to understand the piece of code that you have written after several months even years when you look at it. Moreover, others too, should take the same amount of time that you took after 6 years to understand the code that you have written.  For Example, when anyone looks at the name of a class and its member variables and methods they should understand what they do and how, without any effort. &lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The name of the class should explain what it does or what it stands for.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The name of the variable should say what it is used for.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The name of a method should explain the action that is performed when the method is called. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;A method name should have a verb to make that happen. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The same goes for the name of the objects, they should say what they are used for and in which context. &lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Normally a class is named as a noun example Employee class. &lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;As an example, an Employee class can have variables, to maintain the state of an employee object. When the task of the Employee class is to keep age, salary, name, department details of an employee then the variable names should be like  age, salary, name, department. We should use the easiest name that identifies what the variables are for.  &lt;/p&gt;

&lt;p&gt;Here is another example for the methods. When a method increments the salary of an employee then name it like incrementSalary(). You can increment salary by providing an increment percentage or an adding a float amount to the existing salary. Then name them differently like&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;incrementSalaryByPercentage(double percentage)
incrementSalaryByAmount(long additionalAmount)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now assume a department consists of 5 employees. and one of them is an IT manager, another is an accountant, another human resource manager and two programmers. You will create 5 objects of the same Employee class in the Department class. but name the name of each Employee object should explain their role like ITManager etc.&lt;/p&gt;

&lt;p&gt;When you start creating classes, start from top to bottom. That means write the user interfaces first to provide transparency. Things like services, databases etc. should be at the bottom of the structure and written later. It should be done this way so that, even if there are changes in the technical layer like how to access the database it should not affect the upper layer.&lt;/p&gt;

&lt;p&gt;This way just by following a good naming convention we can make our code easy to understand and transparent.&lt;/p&gt;

&lt;p&gt;For the original post please refer to &lt;a href="https://www.cloudnativemaster.com/post/what-transparency-means-in-oo-design-pattern-how-to-apply-it-in-code"&gt;my blog&lt;/a&gt;&lt;br&gt;
You can see similar posts in Object Oriented Design &lt;a href="https://www.cloudnativemaster.com/object-oriented-design"&gt;here&lt;/a&gt;  &lt;/p&gt;

</description>
      <category>oop</category>
      <category>java</category>
      <category>design</category>
    </item>
    <item>
      <title>What simplicity means in OO design principles ?</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Mon, 30 Aug 2021 19:46:15 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/what-simplicity-means-in-oo-design-principles-2ofc</link>
      <guid>https://dev.to/dibyojyoti/what-simplicity-means-in-oo-design-principles-2ofc</guid>
      <description>&lt;p&gt;Simplicity is one of the Object Oriented Design Principles that helps developers keep the complexity low in an object oriented program.&lt;/p&gt;

&lt;h4&gt;
  
  
  Do not code for future
&lt;/h4&gt;

&lt;p&gt;It says, a class and its method should be as simple as possible, the code should do exactly what it should do, nothing more. We should  refrain from anticipating some functionality for future and implement it for completeness. It's better to code what is known as of now and code in a way that it can be easily extended when new functionality is needed. &lt;/p&gt;

&lt;h4&gt;
  
  
  Do not provide many arguments
&lt;/h4&gt;

&lt;p&gt;Sometimes programmers add more arguments to methods to make it more generic so that it can handle a lot of cases. But in reality all parts of the code may not be executed because all the possible scenarios the programmer thought of, is not happening now. just write what is known to be happening and don't make your method a generic one. &lt;/p&gt;

&lt;h4&gt;
  
  
  Detect reusable logic and refactor
&lt;/h4&gt;

&lt;p&gt;If you anticipate you are writing a logic  part of which can be used later in some other cases, break that method into parts, white the reusable logic in separate method(s). Call the reusable method from another method. &lt;br&gt;
An easy way to detect this is, when during development you need to refactor a certain part once that means it might have to be modified later too. So better to put an extra effort to refactor it so that later a refactoring is not needed, otherwise just leave as it is. You can use design patterns to refactor the code and write a more general solution but design patterns do come with more code and complexity. So if the situation demands it then only apply it.&lt;/p&gt;

&lt;p&gt;To read the main blog post with a concrete example please refer this &lt;a href="https://www.cloudnativemaster.com/post/what-simplicity-means-in-oo-design-pattern-how-to-apply-it-in-code"&gt;link&lt;/a&gt;&lt;br&gt;
To read all my posts related to Object Oriented Design please refer this &lt;a href="https://www.cloudnativemaster.com/object-oriented-design"&gt;link&lt;/a&gt;    &lt;/p&gt;

</description>
      <category>oop</category>
      <category>java</category>
      <category>deisgn</category>
    </item>
    <item>
      <title>What are the characteristics of Object Oriented Design Principles ?</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Sun, 29 Aug 2021 08:09:01 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/what-are-the-characteristics-of-object-oriented-design-principles-4cie</link>
      <guid>https://dev.to/dibyojyoti/what-are-the-characteristics-of-object-oriented-design-principles-4cie</guid>
      <description>&lt;h4&gt;
  
  
  Object Oriented Design principles
&lt;/h4&gt;

&lt;p&gt;Object Oriented Design principles help users to write high quality code. Today we will see what are the characteristics or what the design principles give when they are followed. To understand OO design principles you should know at least one OO programming. Here I have chosen to use JAVA. There are several principles and several names of the same principles. Here I will  list the most popular basic ones which are well received and well known. I will list here what the characteristics are.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Transparency &lt;/li&gt;
&lt;li&gt;Simplicity&lt;/li&gt;
&lt;li&gt;Incremental development approach&lt;/li&gt;
&lt;li&gt;Cohesion or Coherence and Coupling&lt;/li&gt;
&lt;li&gt;Orthogonality&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;To read an explanation on each of the above five points you can refer to my &lt;a href="https://www.cloudnativemaster.com/post/what-are-the-characteristics-of-object-oriented-design-principles"&gt;blog post&lt;/a&gt;    &lt;/p&gt;

</description>
      <category>java</category>
      <category>design</category>
      <category>oop</category>
    </item>
    <item>
      <title>What is Object Oriented Design(OOD)? Why use Object Oriented Design(OOD) Principles ?</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Sun, 29 Aug 2021 07:55:37 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/what-is-object-oriented-design-ood-why-use-object-oriented-design-ood-principles-2pio</link>
      <guid>https://dev.to/dibyojyoti/what-is-object-oriented-design-ood-why-use-object-oriented-design-ood-principles-2pio</guid>
      <description>&lt;h4&gt;
  
  
  What is Object Oriented Design(OOD)?
&lt;/h4&gt;

&lt;p&gt;Object Oriented Design teaches us some basic design principles to write high quality Object Oriented programs. The principles are learned from the common mistakes done by developers. The principles are the guidelines for the developers to avoid the same common mistakes.&lt;/p&gt;

&lt;h4&gt;
  
  
  Object Oriented Design(OOD) Patterns vs Principles
&lt;/h4&gt;

&lt;p&gt;People might have heard about Design patterns and think we are going to talk about design patterns here.   Design patterns provide few well known best practices to be used for some well known circumstances/scenarios and tells about how different classes can be written and used together in each scenario.  &lt;/p&gt;

&lt;p&gt;Object Oriented Design is more about basic principles, building blocks which programmers should keep in mind when they write programs. The Object Oriented Design principles can be applied in each design pattern, and in turn design patterns obeys the OO Design principles. That means they both are complementary and work together to handle different scenarios. &lt;/p&gt;

&lt;h4&gt;
  
  
  Why use Object Oriented Design Principles?
&lt;/h4&gt;

&lt;p&gt;Any developers who write programs using any object oriented programming language should keep in mind the design principles and examine the code after writing whether the code is aligned with the design principles. The reasons why we should do this is because the code base becomes:  &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Easy to maintain(maintainability) &lt;/li&gt;
&lt;li&gt;Easy to extend(extendibility) &lt;/li&gt;
&lt;li&gt;Easy to understand(understandability)&lt;/li&gt;
&lt;li&gt;Easy to test(testability)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Please read &lt;a href="https://www.cloudnativemaster.com/post/what-is-object-oriented-design-why-use-object-oriented-design-principles"&gt;my blog post&lt;/a&gt; to for detail on above four points&lt;/p&gt;

</description>
      <category>java</category>
      <category>oop</category>
      <category>design</category>
    </item>
    <item>
      <title>Error Handling with HTTP Error Response Generation in node.js Application</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Sat, 28 Aug 2021 11:48:28 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/error-handling-with-http-error-response-generation-in-node-js-application-2ahd</link>
      <guid>https://dev.to/dibyojyoti/error-handling-with-http-error-response-generation-in-node-js-application-2ahd</guid>
      <description>&lt;p&gt;In one of my blog posts &lt;a href="https://www.cloudnativemaster.com/post/separate-routing-from-business-logic-in-node-js-central-response-generation-in-node-js"&gt;Separate routing from business logic in node.js | Central response generation in node.js&lt;/a&gt; we have seen how we can perform central HTTP response generation from the responses generated by the business logic module. In application different error conditions can occur. We would like to code for those error conditions using a try-catch, and throw constructs provided by the programming language. But that is not good when it comes to HTTP error responses. In cloud native application development we need to convert those errors to HTTP error responses. It would be necessary to handle the throws exceptions from code and convert them to HTTP error responses centrally. &lt;br&gt;
We can create a &lt;em&gt;errorHandler.js&lt;/em&gt; file where we write the code to convert the errors to HTTP responses.&lt;br&gt;
The errorHandler will look like this&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function errorHandler() {
  return (err, req, res, next) =&amp;gt; {
    if (err instanceof TypeError) {
      return res.status(400).json(err.name + ": " + err.message);
    }
    if (err &amp;amp;&amp;amp; err.statusCode) {
      return res.status(err.statusCode).json(err.body);
    }
    return next(err);
  }
}

module.exports = errorHandler;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we need to import this errorHandler to the application server and apply it as &lt;code&gt;app.use(errorHandler)&lt;/code&gt;. In this way we don't have to convert error to HTTP response in every place, we just do it in one place. Of course, in all those files where error can occur we need to use try-catch-throw construct to throw errors. All those thrown errors will be caught by this block of code centrally. &lt;/p&gt;

&lt;p&gt;For an complete example please refer to &lt;a href="https://www.cloudnativemaster.com/post/error-handling-with-http-error-response-generation-in-node-js-application"&gt;my blog post&lt;/a&gt;. &lt;/p&gt;

</description>
      <category>node</category>
      <category>webdev</category>
      <category>errorhandelling</category>
    </item>
    <item>
      <title>Separate routing from business logic in node.js | Central response generation in node.js</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Fri, 27 Aug 2021 15:42:09 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/separate-routing-from-business-logic-in-node-js-central-response-generation-in-node-js-2h1i</link>
      <guid>https://dev.to/dibyojyoti/separate-routing-from-business-logic-in-node-js-central-response-generation-in-node-js-2h1i</guid>
      <description>&lt;p&gt;Its important to keep the code that executes the business logic separate from the  request routing. The separation helps code modularity and enhances separation of concerns. In my post &lt;a href="https://www.cloudnativemaster.com/post/routes-in-node-js-writing-modularized-codes-using-routes"&gt;What are routes in node.js ? How routes help writing modularized code ?&lt;/a&gt; I explained how we can use routers to handle multiple APIs, each API family can be separated using a separate router. You can easily imagine when the actual business logic is implemented the inline-function in the routers that handles the request will be much bigger and complicated. &lt;/p&gt;

&lt;p&gt;First, as the number of APIs increase, keeping the routing logic and the business logic to process the requests in the same file is not going to scale and becomes cumbersome. We would like to separate the business logic from the routing logic. The router layer just should contain the routing logic and the business layer contains the business logic, the routing layer should use the business layer functions. For example, when we do user management (e.g create, update, view user) and order management (create, update, view order) we write all logic related to user management in a separate .js file and logic related to order management in another .js file. Here we write the business logic that is needed for user and order management. We can also write a separate function for each operation (e.g create user, view user, update user) in each of the files. Then we create a router for each routing family, for example a router for user management that starts with /user, a route for order management that starts with /order and so on. And finally we associate the particular REST call in the router with the particular operation in the business logic. For this we just have to import the .js file that has the business logic to the .js router file. You can see an example in my &lt;a href="https://www.cloudnativemaster.com/post/separate-routing-from-business-logic-in-node-js-central-response-generation-in-node-js#viewer-711l8"&gt;blog here&lt;/a&gt;  &lt;/p&gt;

&lt;p&gt;Second, in each function when we perform HTTP response generation we are repeating some of the logic necessary for response formulation. We should have a central method for request processing, used by all functions for all routers. I have also shown this in the same blog that I have linked above. &lt;/p&gt;

</description>
      <category>node</category>
      <category>webdev</category>
      <category>routing</category>
      <category>modularity</category>
    </item>
    <item>
      <title>Manage Node applications using PM2</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Tue, 24 Aug 2021 19:01:20 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/manage-node-applications-using-pm2-548o</link>
      <guid>https://dev.to/dibyojyoti/manage-node-applications-using-pm2-548o</guid>
      <description>&lt;h4&gt;
  
  
  What is PM2?
&lt;/h4&gt;

&lt;p&gt;PM2 is a daemon process manager that helps micro service developers in node manage and keep applications online. Using PM2 is straightforward, it offers a simple and intuitive CLI. it is installable via NPM.&lt;/p&gt;

&lt;h4&gt;
  
  
  What it can do for us?
&lt;/h4&gt;

&lt;p&gt;Using PM2 we can start, restart, stop, delete an node application. That means we can manage the application lifecycle of node applications using PM2. Feel free to read &lt;a href="https://www.cloudnativemaster.com/post/pm2-and-its-uses-in-node-js-application"&gt;my blog&lt;/a&gt; for details with example.&lt;/p&gt;

</description>
      <category>node</category>
      <category>webdev</category>
      <category>pm2</category>
    </item>
    <item>
      <title>How to add multiple routers in a node application without using app.use() for each router ?</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Mon, 23 Aug 2021 16:55:17 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/how-to-add-multiple-routers-in-a-node-application-without-using-app-use-for-each-router-3gf3</link>
      <guid>https://dev.to/dibyojyoti/how-to-add-multiple-routers-in-a-node-application-without-using-app-use-for-each-router-3gf3</guid>
      <description>&lt;p&gt;In node.js, when we have multiple &lt;em&gt;Express.Router&lt;/em&gt; written in a separate file to enhance modularization we need to import each route file into the application server file and add lots of &lt;em&gt;app.use()&lt;/em&gt; statements.  Now, if we add a new router we need to remember to add that too in the file where the application server is written.&lt;/p&gt;

&lt;p&gt;Let's assume there is a routes folder where the routes are defined for &lt;em&gt;user&lt;/em&gt; and &lt;em&gt;order&lt;/em&gt; handling separately in separate files. in application server file we need to use &lt;em&gt;app.use&lt;/em&gt; two times. imagine if our routers increase the solution will not be very good. &lt;/p&gt;

&lt;p&gt;we can add a small code snippet in our application server JS file that will automatically import and add all of the routes in the application.&lt;br&gt;
In &lt;a href="https://www.cloudnativemaster.com/post/how-to-add-multiple-routers-in-a-node-application-without-using-app-use-for-each-router"&gt;this blog&lt;/a&gt; I gave an example of the initial approach and also showed how that code snippet looks like.&lt;/p&gt;

</description>
      <category>node</category>
      <category>webdev</category>
      <category>approuter</category>
    </item>
    <item>
      <title>Generate human readable REST API document in NodeJs using an apidoc node module</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Sun, 22 Aug 2021 09:27:06 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/generate-human-readable-rest-api-document-in-nodejs-using-an-apidoc-node-module-3dma</link>
      <guid>https://dev.to/dibyojyoti/generate-human-readable-rest-api-document-in-nodejs-using-an-apidoc-node-module-3dma</guid>
      <description>&lt;p&gt;Node.js is one of the top preferences of programming languages In cloud native application development. Many micro services provide functionality by exposing REST APIs. It's important for developers of consuming applications as well as the provider application to be able to read the definition and capabilities of each and every REST endpoint. The apidoc node module comes handy, this module helps application developers define and document the REST APIs with very less effort. &lt;/p&gt;

&lt;h4&gt;
  
  
  What is apidoc?
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://www.npmjs.com/package/apidoc" rel="noopener noreferrer"&gt;apidoc&lt;/a&gt; is a node plugin that can be installed in the node application. This plugin helps to write and generate REST API documents for node.js applications.&lt;/p&gt;

&lt;h4&gt;
  
  
  How to generate API documents using apidoc ?
&lt;/h4&gt;

&lt;p&gt;First we need to install apidoc in the node.js project. Then we can use the &lt;em&gt;@ parameters&lt;/em&gt; and formats as comments in the node.js files. After that we need to run a command to create the documentation. Apidoc scans all .js files in the path. It creates a nice human readable HTML static file  from the comments in the .js files. The comments can be added in-place on top of each node route that provides the REST functionality.&lt;/p&gt;

&lt;p&gt;A better approach though, is to separate the comments for documentation separate from code. We also can write all comments for all APIs in a separate .js file. Also, we can write a code snippet that will generate the documents automatically.  Let’s see an example to understand it better. &lt;/p&gt;

&lt;h4&gt;
  
  
  The package.json file
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "Test-App",
  "version": "1.0.0",
  "devDependencies": {
    "apidoc": "^0.25.0"
  },
  "apidoc": {
    "title": "Test-App API Documentation",
    "order": [
      "Users",
      "User"
    ]
  },
  "engines": {
    "node": "^12.18.0",
    "npm": "^6.14.4"
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In package.json we have mentioned the apidoc version under devDependencies. Note the app name and version, it will be used in the apidoc generated document. This file also has an apidoc element, here the title of the generated apidoc HTML file can be defined. The groups names and their order can also be defined here. Read along to know what groups are groups. &lt;/p&gt;

&lt;h4&gt;
  
  
  The .js file with apidoc comments
&lt;/h4&gt;

&lt;p&gt;Here is a users.js file that contains all the comments. The file assumes creating a document for REST APIs for user management. It contains listing all users, creating and updating a user.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * @api {get} /users Get all users
 * @apiDescription Returns All user names.
 * @apiPermission None
 * @apiName GetUsers
 * @apiGroup Users
 *
 * @apiSuccess {Object[]} response Services metadata.
 * @apiSuccess {String} response.name user name.
 *
 * @apiSuccessExample {json} successful response(200 OK):
[
    {
        "name": "user name"
    }
]
 *
 * @apiError (Error 4XX) 404 Not Found.
 * @apiError (Error 5XX) 500 Internal Server Error.
 */

/**
 * @apiDefine ErrorCodes
 * @apiError (Error 4XX) 400 Bad Request.
 * @apiError (Error 4XX) 401 Unauthorized.
 * @apiError (Error 4XX) 403 Forbidden.
 * @apiError (Error 4XX) 404 Not Found.
 * @apiError (Error 5XX) 500 Internal Server Error.
 */

/**
 * @apiDefine UserRequestBody
 * @apiParam (Body/Json Parameter) {String} email Email of user.
 * @apiParam (Body/Json Parameter) {Number} age Age of user.
 * @apiParam (Body/Json Parameter) {String} name Name of user.
 * @apiParam (Body/Json Parameter) {String} [expdate] Optional membership expiry date.
 *
 * @apiParamExample {json} example request body:
 * {
 * "email":"name@gmail.com",
 * "age":"1",
 * "name": "name",
 * }
 *
 * @apiSuccess {String} msg operation successful.
*/

/**
 * @api {post} /users Create user
 * @apiDescription create an user
 * @apiPermission Admin
 * @apiName CreateUser
 * @apiGroup User
 * @apiUse UserRequestBody
 * @apiSuccessExample {json} successful response(200 OK):
 * {"Msg":"Successfully created user with email: ***** "}
 * @apiUse ErrorCodes
 */

/**
 * @api {put} /users Update User
 * @apiDescription Update an user
 * @apiPermission Admin
 * @apiName UpdateUser
 * @apiGroup User
 * @apiUse UserRequestBody
 * @apiSuccessExample {json} Success-Response(200 OK):
 * {"Msg":"Successfully updated user with id: ***** "}
 * @apiUse ErrorCodes
 * @apiError (Error 4XX, 5XX) 400 Bad request.
 */
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To read on the explanation of the tags read my blog &lt;a href="https://www.cloudnativemaster.com/post/generate-human-readable-rest-api-document-in-nodejs-using-an-apidoc-node-module" rel="noopener noreferrer"&gt;generate human readable rest api document in nodejs using an apidoc node module&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, I have written a code that can generate the documents automatically. The file name is genAPiDoc.js and its content is given below.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const apidoc = require('apidoc');
apidoc.createDoc({
  dest: "./webapp/apidoc",
  src: ["./apidoc_source"]
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The source means the documents in commented form will be read from the apidoc_source folder and the docs will be generated under the webapp/apidoc folder. &lt;/p&gt;

&lt;p&gt;The folder structure of our small project to generate api documentation I have depicted here&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;apidoc_source
  /users.js
node_modules
webapp
  /apidoc
genAPiDoc.js
package.json
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At this point we have everything to generate the HTML document. To install all NPM modules we have to run the &lt;em&gt;npm install&lt;/em&gt; command.  Then we run the &lt;em&gt;node genAPiDoc.js&lt;/em&gt; command to generate the human readable document. You will see lots of files and folders generated under the &lt;em&gt;webapp/apidoc&lt;/em&gt; folder. Among them you will find the index.html. This is the file where we have the output of the document in a nice human readable format.&lt;/p&gt;

&lt;p&gt;The screen shot of the html files generated are here&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3ex0ygoi56s4n7hqszxq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F3ex0ygoi56s4n7hqszxq.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;For the full view of the html page see &lt;a href="https://www.cloudnativemaster.com/post/generate-human-readable-rest-api-document-in-nodejs-using-an-apidoc-node-module" rel="noopener noreferrer"&gt;my blog post&lt;/a&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>webdev</category>
      <category>microservices</category>
      <category>apidoc</category>
    </item>
    <item>
      <title>How would you access form data without using bodyParser ?</title>
      <dc:creator>Dibyojyoti Sanyal</dc:creator>
      <pubDate>Sun, 22 Aug 2021 08:13:33 +0000</pubDate>
      <link>https://dev.to/dibyojyoti/how-would-you-access-form-data-without-using-bodyparser-1p0c</link>
      <guid>https://dev.to/dibyojyoti/how-would-you-access-form-data-without-using-bodyparser-1p0c</guid>
      <description>&lt;p&gt;Generally we use the &lt;strong&gt;body-parser&lt;/strong&gt; node module to parse request bodies. When for some reason we don't want to use express or want to know how the body-parser probably works, this post explains how developers in vanilla node.js can extract request bodies from an HTTP(S) POST, PUT and PATCH request. The request object in express works with few stream events. One of the events is &lt;em&gt;data&lt;/em&gt; and another is &lt;em&gt;end&lt;/em&gt;. Using these two stream events we can do our job. &lt;/p&gt;

&lt;h4&gt;
  
  
  What are streams in node.js ?
&lt;/h4&gt;

&lt;p&gt;Streams are one of the fundamental concepts in node.js used for data- handling.  Using streams we can read data from an input and write data to an output in a sequence. Streams can be used in any kind of information exchange. For example, to read data from files and write data to files. Streams can be used for network communications also. In streams data is not read from input at once and then written to output. Instead data is read and written at the same time as a sequence of chunks. This makes streams powerful when dealing with large amounts of data. We can write memory and time efficient code using streams. Streams uses an asynchronous programming model and provides few events to listen to.  That is a brief on streams which we need to understand for this post.&lt;/p&gt;

&lt;h4&gt;
  
  
  What are &lt;em&gt;data&lt;/em&gt; and &lt;em&gt;end&lt;/em&gt; events?
&lt;/h4&gt;

&lt;p&gt;A data event is triggered when the stream receives a chunk of data. When the data ends the stream end event is called.&lt;/p&gt;

&lt;h4&gt;
  
  
  How to use stream events to read and parse data from a request object in node.js ?
&lt;/h4&gt;

&lt;p&gt;We need to implement logic on the &lt;em&gt;data&lt;/em&gt; and the &lt;em&gt;end&lt;/em&gt; stream event. We have to listen to the data event and capture the chunk from there. Then we collect it in a variable. We also need to listen to the end event. When the end event is generated we are sure that we have received all data chunks sent as a request body. We need to consolidate the data we collected and process the data as a whole. Here in this example, we are verifying whether the data starts with a curly brace, if it is then we assume the data is in JSON format. So we convert it to a JSON data structure. After that by calling the &lt;em&gt;next()&lt;/em&gt; method we finish the data processing on the hook that we have written on the end event and pass the control to other event listeners that may exist.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use(function(request, response, next) {
  let whole_data = '';
  request.on('data', function(data_chunk) {
 console.log('on data: ', data_chunk);
 whole_data += data_chunk;
  });
  request.on('end', function() {
 req.rawBody = whole_data;
 console.log('on end: ', whole_data);
 if (whole_data &amp;amp;&amp;amp; whole_data.indexOf('{') &amp;gt; -1 ) {
  req.body = JSON.parse(whole_data);
 }
 next();
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The above code is just an example of what we might like to do when we get the whole data at the end. We can write any logic we want here. For example, if we just want to print the whole data, the code will be as follows.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.use(function(request, response, next) {
  let whole_data = '';
  request.on('data', function(data_chunk) {
 whole_data += data_chunk;
  });
  request.on('end', function() {
 console.log(whole_data);
 response.end();
  });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can read it in details &lt;a href="https://www.cloudnativemaster.com/post/how-would-you-access-form-data-without-using-bodyparser"&gt;here&lt;/a&gt;&lt;br&gt;
To read more about similar posts see my &lt;a href="https://www.cloudnativemaster.com/nodejs"&gt;blog&lt;/a&gt;  &lt;/p&gt;

</description>
      <category>node</category>
      <category>webdev</category>
      <category>formdata</category>
      <category>microservices</category>
    </item>
  </channel>
</rss>
