Does monocle use a bad example for event driven programming?
https://github.com/saucelabs/monocle
The following code is given as an example of standard event driv开发者_Go百科en programming:
def get_cmd(conn): conn.read_until("\n", callback=handle_cmd) def handle_cmd(conn, cmd): if cmd.type == "get-address": # keep track of the conn so we can write the response back! def callback(result): handle_user_query_result(conn, result) db.query(cmd.username, callback) else: conn.write("unknown command") def handle_user_query_result(conn, user): conn.write(user.address)
Though I don't understand why a closure was needed. "keep track of the conn" contradicts how the first function "get_cmd" worked. Also, don't event driven frameworks usually let you pass parameters around?
I'm guessing this would have been a more legitimate example:
def get_cmd(conn): conn.read_until("\n", callback=handle_cmd) def handle_cmd(conn, cmd): if cmd.type == "get-address": db.query(cmd.username, callback=handle_user_query_result, params=conn) else: conn.write("unknown command") def handle_user_query_result(result, params): user = result conn = params conn.write(user.address)
Am I wrong?
I'd say it's a poor example because it doesn't show just how bad callback-based event programming can be. The closure isn't necessary, but it (presumably) is used to keep things logically organized, making the code easier to read/reason about. It's quite common to write your callback as a closure. The whole point of the example is to illustrate how avoiding callbacks can make code more concise, arguably easier to read/write/reason about. Personally I'm not a fan of callback based programming, having used twisted and node.js a fair bit recently. Go write an application with either and then you'll appreciate monocle's approach (or not, some people prefer the callback-based approach).
精彩评论