Is there a difference between these two constructors for a node in a linked list?

Comparing the following two pieces of code, is there a difference between these two constructors for a node in a linked list? In particular, consider a constructor with a single object E as a parameter.

and.

public class Listnode<E> {
  //*** fields ***
    private E data;
    private Listnode<E> next;

  //*** constructors ***
    // 2 constructors
    public Listnode(E d) {
        this(d, null);
    }

    public Listnode(E d, Listnode n) {
        data = d;
        next = n;
    }
}

      

IN.

public class Listnode<E> {
  //*** fields ***
    private E data;
    private Listnode<E> next;

  //*** constructors ***
    // 2 constructors
    public Listnode(E d) {
        data = d;
        next = null;
    }

    public Listnode(E d, Listnode n) {
        data = d;
        next = n;
    }
}

      

I am just starting to teach myself Java over the internet and I thought the implementation in B was easier to read, however A came from Reliable source. On the surface, they both work fine. Is there an advantage of one over the other?

+3


source to share


1 answer


The end result is the same assignments for both constructors, however option A is better because you don't duplicate code.

Option B is more error prone because you are assigning fields in both constructors.

This can lead to possible errors if you mess up the assignment in one of the constructors or forget to assign one of the fields. Also, if you later add more fields to the class, you will have to remember to assign values ​​to them in multiple places.

Also, if you needed to do input validation, you'd have to duplicate this in multiple constructors (or at least call validation methods in multiple constructors), it's better to have all the validation in one place.



For example, let's say you need to make sure the data is not null

:

//validate that data can't be null
public Listnode(E d) {
    if(d ==null){
       throw new NullPointerException("data can't be null");
    }
    data = d;
    next = null;
}

public Listnode(E d, Listnode n) {
    if(d ==null){
       throw new NullPointerException("data can't be null");
    }
    data = d;
    next = n;
}

      

All of this violates the Do not Repeat Yourself (DRY) principle.

+3


source







All Articles