Say I have a method getBook() within the class Bookshelf. The method should only return a Book object if the Bookshelf isn’t empty. However, Java requires the method to return a Book object under all circumstances. I could have a method isShelfEmpty() which is called first, but it seems awkward to have to reveal the implementation of the Bookshelf to the caller. What’s the cleanest way to do this?
An Iterator would make this simpler, but this is for a class project, and we haven’t covered iterators in class yet.
Edit:
I have thought about returning null, but this seems sort of ugly to me for some reason. Is this the best option, or is there another?
You could return
nullif there is no book available. Then you have to check fornullevery time you ask for a book, of course.I would implement a method
isBookAvailable()and throw an exception if the methodgetBook()is called when there is no book available.