Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects Harnessing the Power of Objects Method Overloading

Why does the "dispense" method have to be a boolean?

In the following code, why must dispense be a "boolean" method rather than a public void method like "fill?"

public boolean dispense() { boolean wasDispensed = false; if (!isEmpty()) { pezCount--; wasDispensed = true; } return wasDispensed;

Couldn't we just omit the "boolean wasDispensed = false;" and "wasDispensed = true;" and instead just decrement the pezCount with an if statement? I am at a loss also as to why we must "return wasDispensed". Please help! Thank you!!!

2 Answers

Brendon Butler
Brendon Butler
4,254 Points

We do this so that in the class that accesses the "dispense" method, we can immediately see whether or not the item was dispensed.

// SOME CLASS
if (obj.dispense()) sout("Object was dispensed!");
else sout("Object was not dispensed!");

Yes, you could do this in the dispense() method, but this allows the dispenser to work more like an API, so that outside classes can do what they want with the output. You could make the dispense method void, but it limits the functionality, and may lead to issues like if there was nothing to dispense. That would leave you with an unhappy customer since the machine thinks it actually dispensed something.

You could even have it return an item, blank item, null, or optional, really whatever you feel. This is more a proof of concept really.

note: this is pseudo-code

The words out of my mouth after reading this were, "I think I like this answer.". Well thought out and it makes a lot of sense to me. So thank you.

RafaΕ‚ Sobczyk
RafaΕ‚ Sobczyk
3,274 Points

It really doesn't, and it's not a good practice to write code like that - it should've been a void method. However, until we get to exceptions, there is no other way to indicate whether the dispense operation succeeded.

Brendon Butler
Brendon Butler
4,254 Points

Actually, it's not good practice to throw exceptions every chance we get. Abusing exceptions is a bad practice, returning a boolean is perfectly valid, especially in a simple program like this.

Returning an optional would be an even better practice as they allow you to avoid nulls and they have some extended usability.