How to Avoid Constructor Code Redundancy in Java

How to avoid constructor code redundancy in Java?

As a rule, constructors with fewer arguments should call those with more.

public Pair() {}
public Pair(String car) { this(car, null); }
public Pair(Integer cdr) { this(null, cdr); }
public Pair(String car, Integer cdr) { this.car = car; this.cdr = cdr; }

How to avoid code redundancy with JAVA generics

You're pretty close with this, the way you've declared your type parameters is incorrect though. It should be more like:

protected <T extends Request, S extends Service, R extends Response> 
Response callService(T request, S service, R response) {
...
service.api1(rpcClientController, request, future::complete);
}

By convention in Java type parameters are a single uppercase letter. To get them to behave as you expect you need to bound the types; hence the extends.

How to avoid redundant code for static methods

Static methods in Java can't be overridden in subclasses.

If you define a static method in a subclass with the same signature as the static method in the parent class, the method is not overriding the parent method is hiding it. The methods in the parent and the child class has no relation to each other.

In your example, if method static void makeNoise() exists in Animal and any subclass define the method as well, the subclass is just hiding the makeNoise method in Animal.

In your example, the best you can do with static methods is:

public static void makeNoise(String noise) {
System.out.println(noise);
}

And invoke the method this way:

Animal.makeNoise(Cat.NOISE); // A constant NOISE is defined in each subclass

If the method makeNoise is non-static, inheritance could be used to use a different noise in each subclass:

public abstract class Animal {
protected String noise;

protected Animal(String noise) {
this.noise = noise;
}

public void makeNoise() {
System.out.println(noise);
}

}

public class Cat extends Animal{
public static final String NOISE = "meow";

public Cat() {
super(NOISE);
}
}

Java - Constructor and Method Redundancy

Nope. What happens if the temperature changes? You can't create a new Temperature class because that would mean you're creating a completely new object. setFarenheit() allows you to change the temperature in that specific class.

Here's another better example: Say you have a class called Person and you pass the person's age in the constructor. You should have a setAge() method in the class because the Person is eventually going to get older and it would be rather inefficient if you create a copy of the person just to change his/her age.



Related Topics



Leave a reply



Submit