TIL #2 | IntelliJ Copy Constructor Refactoring


I wanted to learn what I wanted to know, but they wanted me to learn for the exam — Albert Einstein

Today, I spent most of my day in meetings, thinking, and preparing backlog so I couldn’t do much code.

Learning 1: IntelliJ Copy Constructor

Today, I was reviewing a piece of code where we had to create an object with 30 fields. The code had a constructor with 30 fields and then in the calling code we were passing those 30 fields. How error prone and tiring is this? A simple example is shown below.

public MyClass(String field1, String field2, String field3, String field4, String field5){
    this.field1 = field1;
    this.field2 = field2;
    this.field3 = field3;
    this.field4 = field4;
    this.field5 = field5;
}

// Calling code

MyClass instance = new MyClass("1","2","3","4","5");

I googled around and found that there is an IntelliJ Copy Constructor plugin that can generate a constructor for you using the passed object. Using the constructor, we can change this to.

public MyClass(MyClass other){
    this.field1 = other.field1;
    this.field2 = other.field2;
    this.field3 = other.field3;
    this.field4 = other.field4;
    this.field5 = other.field5;
}

// Calling code

MyClass instance = new MyClass(other);

Not only this makes code look clean but maintainable as well.

I hope you enjoy this tip and found it useful.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: