Let us try to answer why we need Genetics in Java?


tl;dr: Generics helps to avoid runtime exceptions such as ClassCastException and making your code more type-safe.

In the typical project life cycle, around 20% of the total duration is devoted to the development phase and the initial release, with the remaining 80% being the maintenance phase. It's essential to recognize that if the product lacks a robust architecture, there is an increased likelihood that the code will become more error-prone as new features are introduced over time. Regardless of the circumstances, one universal truth remains: bugs are an integral part of the product life cycle.



Typical Product Life Cycle


Much time, effort, and resources are involved to ensure the code to production has the least amount of bugs.



StageWhoEfforts
DevelopmentDevelopersUnit tests, code reviews, best practices.
TestingQA TestersFunctional, integration, and regression testing.
Quality AssuranceQA TeamsTest plans, automated testing tools.
Project ManagementProject ManagersBug monitoring, critical issue prioritization.
DevOpsDevOps EngineersContinuous Integration and Continuous Delivery (CI/CD) implementation.
SRE (Site Reliability Engineering)SRE TeamsEnsuring system reliability and performance.
Information SecuritySecurity TeamsSecurity audits, vulnerability assessments.


IT Team Working on a Project


Still there are some bugs that creep into the production unnoticed by all, and one such category of bugs is called "Runtime Exceptions".

Runtime exceptions are literally called human errors! Something that is the responsibility of the developer to take care of while designing and writing code.

Let's take a simple real-world example.

public class Calculator {

    public static void main(String[] args) {

        Calculator calculator = new Calculator();

        double result1 = calculator.addNumbers(10, 11.2);
        System.out.println("Result: " + result1);

        double result2 = calculator.addNumbers("10", 11.2);
        System.out.println("Result: " + result2);

    }

    public double addNumbers(Object num1, Object num2) {
        
        double no1 = (double) num1;
        double no2 = (double) num2;
        
        return no1 + no2;
    }
}

Exception in thread "main" java.lang.ClassCastException:

class java.lang.Integer cannot be cast to class java.lang.Double

(java.lang.Integer and java.lang.Double are in module java.base of loader 'bootstrap')
at Calculator.addNumbers(Calculator.java:17)
at Calculator.main(Calculator.java:7)

The above Java code illustrates the concept of runtime exceptions. The Calculator class. The method addNumbers(Object num1, Object num2) is designed to work with all kinds of data types.

result1 attempts to add the numbers 10 and 11.2, which is a valid operation. However, result2 tries to add the string "10" and the number 11.2. This action leads to a ClassCastException, a runtime exception.

The issue arises when the code tries to cast the string to a double, which is not allowed, resulting in a runtime error.

This code demonstrates the significance of handling data types correctly in software development to avoid runtime exceptions. Even with thorough testing and development practices, errors like this can occur if data types are not carefully managed.

It is important to make sure that project codes are robust enough to mitigate Runtime exceptions.

Some bugs are easy to spot because they cause issues during compilation. We call them 'compile-time bugs or errors.' When you write Java code using tools like Eclipse, IntelliJ, or others, these IDEs highlight problems for you. You'll see red flags in your Java files, signaling compilation errors that need fixing before your code can be built successfully.

We can see this when we make the addNumbers method signature as addNumbers(Number num1, Number num2)

Java Compliation Error in IDE


How to make our code safe from ClassCastException?

    Generics enhance code reliability by ensuring type safety and preventing ClassCastException errors. When implementing Generics in your project framework, developers are compelled to work with specific object types. Non-compliance results in compilation errors, making it quite challenging to introduce runtime exceptions.

    Now let's re-write the above code with generics.

    Compliation Error due to Generics

    As you can see, we get two errors in the IDE when you change the code with Generic type argument T and type parameter as Double. Thus, bugs are detected during compilation and do not end up in production.


Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap