Use of Action (Function programming) for better code health continued

Please read Part 1 of this post here.

But with the following code I can just do away with making change only to one place.

Class HandelException {
 function HandleError(Action success,
Action <Exception> fail, Action final){
 catch(Exception e){
 //Do some funky stuff here;


Class A {
 int i;
 int j;

 function Add(int arg1, int arg2)
 () => {return arg1 + arg1;}, //success
 (e) => {RaiseException(
  "Addition Failed in Add()"); }, //fail
 () => {/* clean up code */} //final


 function Sub(int arg1, int arg2)
 () => {return arg1 - arg1;}, //success
 (e) => {RaiseException(
"Addition Failed in Sub()"); }, //fail
 () => {/*clean up code*/} //final

See the magic here… we are not passing any parameters to the handler class.

  • We just provide the function parameters that we might want to use in the consuming (Class A) class.
  • We might want to use the exception (here -> e parameter for fail action)  for propagating user friendly message to higher layers)
  •  Now Class A concentrates more on its given responsibility (do some Math work) than the other clattery codes. It’s easy to spot logic errors there.
  •  Let say if we want to audit log all the calls to methods. Just add a logger statement before and after  sucess()  in HandelException.HandleError -> Try Block that will do the trick.

Hope this serves the purpose of explaining the use of <actions>. There are more things to it will cover it some other time.


1 comment

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: