Completely agree with the previously posted, additionally, code that is explained inside the actual code (comments) becomes code that is easier to mantain, easy for new team-members to learn both its structure and workings.
A shameless plug but it works to exemplify this issure:
Code:
def on_message(client, raw_message):
"""Handles messages sent by clients."""
message = MessageServer.coder.decode(raw_message)
# If client isn't registered
if client not in MessageServer.directory.values():
if message.target != "NickBot": # and isn't trying to do so
MessageServer.close(client) # we close his connection
else: # If he is, NickBot handles it
NickBot.ProcessMessage(message, client)
else:
# If client is registered we check who he addresses
# This Bot > Group > Client heriarchy adds some protection against
# clients wanting to use names used by functions (bots or groups)
# Bots are checked first since they extend functionality
if message.target in MessageServer.bots:
bot = message.target
MessageServer.bots[bot].ProcessMessage(message, client)
# We then check if it's a group
elif message.target in MessageServer.groups:
group = MessageServer.groups[message.target]
forward_message = {"From" : message.target,
"Message" : message.text}
json = MessageServer.coder.encode(forward_message)
for member in group:
MessageServer.directory[member].write_message(json)
# Next we check if he addresses a client
elif message.target in MessageServer.directory:
# If he does we create a new message for the target
# and we send it to them with reference to the sender
username = MessageServer.directory.key_for(client)
forward_message = {"From" : username, "Message" : message.text}
json = MessageServer.coder.encode(forward_message)
MessageServer.directory[message.target].write_message(json)
else:
pass # We don't care
From a dummy chat server I did for school:
https://github.com/ChrisCTX/Tornado-IM
Sure, you may not know Python, or have any idea of the rest of the program, but you will understand at least what is happening in this function.