Causes for code duplication
- Multiple programmers working on different parts of the same program at the same time
- Specific parts of code look different but actually perform the same job. This kind of duplication can be hard to find and fix.
- Rushing to meet deadlines and the existing code is “almost right” for the job. Novice programmers may not be able to resist the temptation of copying and pasting the relevant code
Drawbacks of code duplication
- Any modification has to be repeated wherever the code is duplicated.
- This increases the chances of introducing bugs because of lack of understanding of all the places where the code is duplicated
- It makes code maintenance harder and tedious.
Creating generic components to avoid code duplication.
- In an attempt to make your code generic, do not make it too complicated.
- Make sure you separate out business logic and generic functionality.
- Code given in the blog is indicative and not complete
Let us write generic angular code which can display 2 different types of objects, Order and Payment. In the figure below, you will see the list of orders and payments. A single generic list component handles both the objects.
Let us assume that there is a server api which returns the list of objects in the following format.
“pagination_info”: gives the page information for the list
“object_list”: list of objects (orders/payments)
Consumes the list sent by the server and displays the list using a generic list component.
- Create a constants service - constants.service.ts
- Create Generic List Component
- Create Order List Component
- Create Payment List Component
This file has mappings for order and payment objects returned by the server. It does the following
- Define the title for a given key
- Define the display order for the data
- Apply specific css by specifying the css class
- Define if the data has to be displayed adjacent to any other key
The Generic List component will have the code to display the List UI. This is a simple List with card View. You can have your own design as per the requirement.
generic-list.component.html will look like the following. We have used Ionic framework along with angular.
generic-list.component.ts file will look like following
generic-list.component.scss will look like the following
3. Order List
Now, your Order List component will look like the following. If you notice, Here we do not write any UI code. We just pass the data to the generic list component
order-list.page.ts code will look like the following.
Now, your Payment List component will look like the following. If you notice, Here we do not write any UI code. We just pass the data to the generic list component
payment-list.page.ts code will look like the following.