best coding practice with functions/methods


Let’s say for instance u have a method DisplayPic ( p as picture) that displays the picture on screen.
With respect to checking the “quality” of the parameter p what is the best coding practice:

  1. checking p before feeding it to the method like
if p <>nil then displaypic (p)


  1. checking the paramenter from within inside the method:

[code]Sub displaypic(p as picture)

if p<>nil then
'good pic : code here
'bad pic
end if

End sub[/code]

  1. Or maybe it’s completely irrelevant ??

thanks rgds

Depends. Sometimes just doing nothing can be the best pick and a NilObjectException will rise right from the start of the function avoiding a worst error failing in silence. Then in a upper level you can catch those condition in a Try-Except-End block. So, each case needs a proper design decision.

Let’s pick your example. At design time, you could decide that you need a function to display something, and “that something” can be acceptable as a Nil, signifying a “do nothing”, then you could just check at the start of the function and just return. If in your design decision it’s not acceptable, and you MUST receive a proper value and not accept a nil, then force (raise) an exception to avoid it doing some bad behavior not detected. (Later you can use a Try-Catch to avoid it or inspecting the parameters beforehand to guarantee its quality [never nil])

Functions/Methods (in my opinion) should be self-contained where ever possible. That is they should deal with any value (including NIL) or circumstance that may occur.

UNLESS… you purposely need to conditionally call the function with various condition throughtout your program

You want to separate error detection from error reporting. Error detection should be pushed as far down as possible, in order to provide maximum flexibility in the calling routines. Eg., you may have an intermediate class/method that can act on several different types of input mechanisms and you want to treat them all the same. This routine is not the right place to test the validity of the mechanism (file is open; socket is connected; etc.) It just needs to pass the “handle” on to lower level routines that deal with the specifics. Hide the details.

But error reporting should be at a higher level, so you don’t lock yourself in to one particular method of reporting the error: sometimes it is appropriate to display a message on screen, other times you may not have a screen and need to log to a file or send an message across a socket. Reporting the error too deep in the calling hierarchy reduces your flexibilty.

It’s a delicate balance, for sure.