yronium Level: Moderator

 Registered: 14-04-2002 Posts: 907
|
Re: Which one better?
Hello.
It doesn't matter Sub or Function relating on how many times you have to call it. In fact, if you have to do some actions once only you shouldn't have the need to enclose these action into an external routine to call, but in normal developping we enclose in external routines all those code blocks that we think they may be executed again later, even if at the moment we have the need to execute the block only once.
E.g. if I create a code that reads INI files, even if I need to do it only once at startup, I enclose the instruction into an external routine, named ReadINI(). If later I'd have the need to execute the code again, I have the routine ready to call.
What routine type? Well, subs and functions have a significant difference to consider:
- subs do some actions
- functions return a value (and can do some actions, as well)
You should choose one or another only cosidering if you need a return value or not. Period. No matter how many times you have to execute it.
Consider the above example: I have to read the contents of an INI file, but would be great to know what I have read, isn't it? So I should create a function, Public Function ReadINI() As String, returning the text I retrieved from the file. Later, when I call it, I can directly assign the return value to a variable, as following Dim INIText As String
INIText = ReadINI ' returns the text it has read in the file | Instead, when I need to write the INI file, I have only to execute some actions, and I don't need any return value. So I can create a sub, Public Sub WriteINI(), and just call it in the code by the Call keyword.
Now, I can add a feature to subs: a return value if all the actions are gone right, like it happens in the API functions. Please take note of the difference: this return value is an "artificial" value, is not strictly related with the values involved in the actions we executed, and the logic of the actions have no need to return any value. It's just a help for the programmer. An example could be as followingPublic Function WriteINI() As Long
On Error GoTo ErrRoutine
' ....
' ... actions to execute
' ....
' if the code comes to this point without any error,
' the value of the function is 0
Exit Function
ErrRoutine:
WriteINI = Err.Number
End Function | In this case I can call the function checking the execution at the same time: If WriteINI() = 0 Then ' everything is gone ok
' ... do some stuff ....
Else ' some error occurred
' ... do other stuff ....
End If |
Hope it is clear. There's no better or worse: just the appropriate one.
[Edited by yronium on 11-11-2005 at 10:58 PM GMT]
____________________________
Real Programmer can count up to 1024 on his fingers
|