Reputation: 21154
I think this is a "best practice" category question:
I have a custom control - some kind of grid that holds some panels. One of the panels is the current active panel (the last one clicked).
TMyGrid = class (TSomeKindOfGrid)
published
property CurrentPanel: TPanel read getCurPanel write setCurPanel;
end;
My question is: if at a certain point someone asks for the CurrentPanel
and the grid is empty, should getCurPanel
return a NIL or should it raise an exception?
getCurPanel
returns NIL, then I MUST check for NIL everywhere/every-time I call CurrentPanel
. There is also a possibility that the caller forgets to check for NIL. Well, nothing "bad" will happen since it will try to access a NIL object. The program will nicely crash right there. And I get to get a stack trace. getCurPanel
, I only do the check in one place (yes, I'm lazy). Upvotes: 1
Views: 175
Reputation: 28806
If you return nil
, you give the user the opportunity to check the return value and skip anything he or she intended to do with the current panel:
panel := XYZ.currentPanel;
if Assigned(panel) and (panel.Index = 17) then
begin
The above code runs without any unnecessary interruptions.
If you immediately raise an exception, you don't give the user the opportunity to find out if there is a current panel at all. In other words, raising an exception would be premature. The same code as above will blow up.
But I admit that this is my personal preference (and probably that of many, but not all). This is a matter of opinion.
But instead of returning a nil
, you could also expose a PanelCount
property. If people have something like that to check, you can just as well raise if someone tries to access a panel if count is zero. Then it is not premature.
As you can see, there are several ways to do this.
As SilverWarrior correctly noticed in a comment, currentPanel
is a published property which will eventually appear in an Object Inspector. That can handle a property returning nil
, but not necessarily a property that throws an exception.
So: the best advice is to return nil
.
Upvotes: 5