If I have a method say getNextWidget() that returns a widget, what is the proper design for such a method if I need to check the size of say, the factory that makes the widget and only return a widget if there are widgets in the factory? Is there a way to throw an exception for a method that is not void?
If I have a method say getNextWidget() that returns a widget, what is the
Share
A common pattern is to return
nullwhen there is no more widget to be had. This works very well if the method otherwise never returnsnull.Another common pattern is to throw an Exception. But then you should have a
hasMoreWidgets()method, too. In the normal flow of operation (for example retrieving all widgets until none are left), the program should not trigger exceptions.Either way, if there may be more widgets, but there was some problem accessing the factory, so that you cannot be sure, you should throw an Exception (because this would be a real error condition).