DEV Community

Discussion on: Code Smell 251 - Collections Empty

Collapse
 
moopet profile image
Ben Sinclair
    public T pop() {
        if (isEmpty()) {
            throw new EmptyStackException();
        }

        T item = stack.pop();
        if (stack.isEmpty()) {
            isEmpty = true;             
        }
        return item;
    }

    public boolean isEmpty() {
        return isEmpty;
        // This has O(1) constant time
    }
Enter fullscreen mode Exit fullscreen mode

If you pop an item, it'll call the isEmpty() method, which returns the class variable isEmpty. If that's true, then it'll set the class variable to true. Isn't that tautological?

It feels like the isEmpty() method should wrap the size or count you're trying to avoid, else this won't work.

Collapse
 
mcsee profile image
Maxi Contieri

Thank you very much

The main challenge is about readabality and not performance.
I'm not an expert in Java and I didn't know this facts so they are good points