Skip to content

Freeongoo/java-merge-object

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

19 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Merge Object

Problem

Often there is the task of sum the numeric fields of two objects of the same class.

As a rule, this problem is solved as follows:

Cat catTo = new Cat(2);
Cat catFrom = new Cat(3);

catTo.setAge(catTo.getAge() + catFrom.getAge());

System.out.println(catTo.getAge()); // 5

class Cat {
    private Integer age;

    public Cat(Integer age) {
        this.age = age;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

But this approach is very inconvenient. When increasing the number of fields - increases duplication of the code. Also, if one of the fields contains null, then an exception will be thrown.

Solution

To solve this problem and get rid of code duplication, use our class MergeObject:

MergeObject mergeObject = new MergeObjectImpl();
Set<String> fields = new HashSet<>(Arrays.asList("age"));
mergeObject.sumNumberFields(catTo, catFrom, fields);

System.out.println(catTo.getAge()); // 5

About

A simple way to summarize the fields of objects

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages