I am currently reading some really annoying code. It's basically some weird asynchronous functions with nested lambda/callbacks, and there are some retry pattern involved too. Although I can understand the code after I spent a lot of time debugging it, reading them was really a pain in the neck.
One thing I would like to do is change these lambdas into callback functions, and another thing is to make these retry pattern more generic. For now I don't have any good idea, so any suggestion would be much appreciated!
There are some code snip sample, quite typical in my original project...
public delegate void ActionResult_1(bool ok, Object obj, string msg);
public delegate void ActionResult_2(Object obj);
public delegate void ActionResult_3(bool ok, string errorcode);
class Foo
{
public void Func_1(int value, ActionResult_1 cb_1 = null)
{
Func_2((bool ok, Object obj, string msg) =>
{
if (ok && msg == "success")
{
cb_1(ok, obj, msg + value);
}
else
{
return;
}
});
}
public void Func_2(ActionResult_1 cb_2 = null)
{
Func_3((bool ok, Object obj, string msg) =>
{
if (ok)
{
Func_4(
(ok1, obj1, msg1) =>
{
cb_2(ok1, obj1, msg1);
},
(obj1) =>
{
//do something else with the obj
});
}
else
{
cb_2(ok, obj, msg);
}
});
}
public void Func_3(ActionResult_1 cb_3 = null, int Retris = 5)
{
Func_5((bool ok, string errorcode) =>
{
if (ok)
{
if (errorcode == "unknown")
{
cb_3(ok, null, errorcode);
Func_3(cb_3, Retris - 1);
}
else if (errorcode == "service down")
{
cb_3(ok, null, errorcode);
return;
}
else if (errorcode == "connect fail")
{
cb_3(ok, null, errorcode);
Func_3(cb_3, Retris - 1);
}
else if (errorcode == "access denied")
{
cb_3(ok, null, errorcode);
return;
}
else
{
Object obj = new Object();
cb_3(ok, obj, errorcode);
}
}
});
}
public void Func_4(ActionResult_1 cb_4_a = null, ActionResult_2 cb_4_b = null, int Retris = 5)
{
Func_5((bool ok, string errorcode) =>
{
if (ok)
{
if (errorcode == "unknown")
{
cb_4_a(ok, null, errorcode);
Func_4(cb_4_a,cb_4_b, Retris - 1);
}
else if (errorcode == "service down")
{
cb_4_a(ok, null, errorcode);
return;
}
else if (errorcode == "connect fail")
{
cb_4_a(ok, null, errorcode);
Func_4(cb_4_a,cb_4_b, Retris - 1);
}
else if (errorcode == "access denied")
{
cb_4_a(ok, null, errorcode);
return;
}
else
{
Object obj = new Object();
cb_4_a(ok, obj, errorcode);
cb_4_b(obj);
}
}
});
}
public void Func_5(ActionResult_3 cb_5, int Retries = 5)
{
//Some async service calls
}
};