通用回调机制重载成功处理程序作为流程控制的手段 - 代码味道?
我对一个项目相当陌生,对于我们对数据库进行的一些异步调用(更改了变量和函数名称),遇到了一个有趣的设计范例:
private void OnLogin(object selectedInitialState,
AsyncEventCompletedCallback<EmptyAsyncEventArgs> userCallback,
object userState)
示例用法:
OnLogin(
null,
args =>
{
if (args.IsSuccess)
DetermineNextStep(); //When done, continue to this step
else
//NOTE: This probably means we couldn't connect to the DB
// Handle this case
},
null);
OnLogin(
newInitialState,
args =>
{
ReLoginUser(); //Was logged in; re-logging in user with different initial state
},
null);
示例用法显示了两种不同情况下对此函数的两种不同调用 -初始登录和重新登录(技术上不是重新登录,而是以不同的初始状态为当前登录的用户重新启动应用程序)。
令我困扰的是,这两种情况下的回调函数是不同的。我习惯于看到函数接受回调以允许函数的用户在被调用的函数的权限内提供自定义实现。
但在上述情况下,回调函数会更改控制流。根据提供的回调函数的不同,异步调用返回后后续的调用函数也不同。这是代码味道还是只是回调的创造性用途?
I'm fairly new on a project and ran across an interesting design paradigm for some asynchronous calls we make to the database (variables and function name altered):
private void OnLogin(object selectedInitialState,
AsyncEventCompletedCallback<EmptyAsyncEventArgs> userCallback,
object userState)
Example usages:
OnLogin(
null,
args =>
{
if (args.IsSuccess)
DetermineNextStep(); //When done, continue to this step
else
//NOTE: This probably means we couldn't connect to the DB
// Handle this case
},
null);
OnLogin(
newInitialState,
args =>
{
ReLoginUser(); //Was logged in; re-logging in user with different initial state
},
null);
The example usages show two different calls to this function for two different cases - an initial login and a re-login (not technically a re-login, but a restart of the application for the currently logged in user with a different initial state).
What bothers me is that the callback function in these two cases is different. I'm used to seeing a function take a callback to allow users of the function to provide custom implementations within the purview of the function being called.
In the above case, though, the callback function changes the control flow. Depending on which callback function is provided, the subsequent calling functions after the async call returns are different. Is this a code smell or just an inventive use for callbacks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将 OnLogin 函数解释为启动一个操作,该操作将在完成后调用一次回调。
在这种情况下,代码实际上是很正常的。在异步编写程序时,这种情况并不罕见。考虑到替代方案是在回调函数中使用(小)状态机保持“状态”,我认为不同的回调实际上是更优雅的解决方案。它隐式而不是显式地处理异步“状态”。
I'm interpreting the
OnLogin
function as starting an operation that will invoke the callback exactly once upon completion.In this case, the code is actually quite normal. This is not uncommon when writing a program asynchronously. Considering that the alternative is keeping a "state" with a (small) state machine in the callback function, I think different callbacks is actually the more elegant solution. It handles the asynchronous "state" implicitly instead of explicitly.