Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
One exit per procedure/function/codeblock to what purpos
Message
From
08/10/2003 18:41:59
 
 
To
08/10/2003 18:08:56
General information
Forum:
Visual FoxPro
Category:
Other
Miscellaneous
Thread ID:
00835552
Message ID:
00836561
Views:
32
Ok, here's my refactoring fetish again...

Something like this is a perfect example of what I mean. If you have multiple chunks of code in one method that might have fatal errors for the process - i.e., return .F., or some other ungood error - then they should be encapsulated into their own methods.
e.g.
** o.CreateInvoice()
LParameters tnCustId

** make sure customer exists
Select custid ;
  From customer ;
  where custid=tnCustId ;
  Into Cursor cutmp
If RecCount()=0
  MessageBox("Customer Id not found.", 16, _Screen.Caption)
  Do CleanUp()
  Return .F.
EndIf

** make sure they have no outstanding money owed
Select Sum(money_owed) as money_owed ;
  From invoices ;
  Where custid=tnCustId ;
  Into Cursor cutmp
If RecCount()>0
  MessageBox("Customer owes " + Transform($1*cutmp.money_owed), 16, _Screen.Caption)
  Do CleanUp()
  Return .F.
EndIf

** several other such processes go here **

** actual meat of the code goes here **
This I would refactor into different methods, each of which handle cleanup and error messaging pertinent to themselves only - and therefore may be reused by other processes. And by doing this, you can also get around all the IF !llRetVal checks with a case statement.
e.g.
** o.CreateInvoice()
LParameters tnCustId
Local llRetVal
Do Case
  Case !this.CustomerExists(tnCustId)
  Case !this.CustomerOwesMoney(tnCustId)
  Case !this.CustomerOverLimit(tnCustId)
  ** etc.
  Otherwise
     ** this ~Ex() method now contains the meat of the code,
     ** also refactored if necessary
     llRetVal=this.CreateInvoiceEx(tnCustId)
EndCase
Return llRetVal

Of course, this is a far less complex example that would be found in real life, but just imagine a big hairy method with this kind of original code, even if it works, refactored into multiple encapsulated and probably reusable methods...

>Hi Evan,
>
>The thing I don't 'get' is... why would it be considered 'bad' to code
...
>do Cleanup
>Return .F.
>ENDIF
>
>I personally wouldn't care if that sequence was coded 50 times in a program. What I *would* care about is having
...
>llReturn = .F.
>ENDIF
followed by EXTRA code that has to check llReturn every time something new was to be done.
>
>Admittedly, all personal taste.
>cheers
>
Insanity: Doing the same thing over and over and expecting different results.
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform