HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

DoublyLinkedList Implementation Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
doublylinkedlistimplementationjava

Problem

I thought I'd ask for a review to make sure I am headed in the right direction. Would really appreciate pointers to what I can fix/change or think of to help me improve my coding standards and be a better programmer.

```
/**
* Doubly Linked List data structure implemented as generic to fit multiple types.
* TODO: Implement all implemented methods.
*
* @author Oskar
* @version 0.00.00
* @name DoublyLinkedList.java
*/
public class DoublyLinkedList implements List{
private int size; // Number of elements in the list.
private Node first = null; // First item in the list.
private Node last = null; // Last item in the list.

/**
* Adds a new node entry to the front of the list.
*
* @param data - data to populate the Node object with.
*/
public void addFirst(T data) {
Node newEntry = new Node(data);

if (isEmpty()) {
newEntry.next = null; //no need since its null by default
newEntry.prev = null; //no need since its null by default
first = newEntry;
last = newEntry;
} else {
first.prev = newEntry;
newEntry.next = first;
newEntry.prev = null; //no need since its null by default
first = newEntry;
}
this.size++;
}

/**
* Adds a new history entry to the end of the list.
*
* @param data - data to populate the Node object with.
*/
@Override
public boolean add(T data) {
Node newEntry = new Node(data);

if (isEmpty()) {
newEntry.next = null;
newEntry.prev = null;
first = newEntry;
last = newEntry;
} else {
last.next = newEntry;
newEntry.prev = last;
newEntry.next = null;
last = newEntry;
}
this.size++;
return true;
}

/**
* Removes the current first element of the list.
*
* @return The searchTerm within the removed History object.
*/
public T removeFirst() {
if (isEmpty()) {
//Throw exception
}

if (!isEmpty()) {
Node oldFirst = fi

Solution

One thing I see is a lot of this pattern:

public T method() {
    if (isEmpty()) {
        //Throw exception
    }

    if (!isEmpty()) {
        //Do stuff
    }
    return null;
}


The first if checks isEmpty and throws an exception, which leaves the method. The second if check is completely unnecessary.

Code Snippets

public T method() {
    if (isEmpty()) {
        //Throw exception
    }

    if (!isEmpty()) {
        //Do stuff
    }
    return null;
}

Context

StackExchange Code Review Q#147213, answer score: 3

Revisions (0)

No revisions yet.