1

I am writing a simple IRC chatbot in Python and, in an effort to get more into OOP, made a basic "connection" class that manages all the backing-and-forthing involved. But IRC protocol is rather annoying to work with, so I wrote a function that takes the raw message from the server and translates it into a form that's much easier to work with. (It separates out the user/channel the message came from, the message it contained, etc.)

In my first iteration of this function, I used a tuple to return this information, but this was extremely difficult to work with as I had to remember which item in the tuple corresponded with what information. Then I changed it to return a dictionary, with the indices being "channel," "user," and "msg." (Not all are used for every message/event, of course.) But as I'm looking back at my code written for that system, it too seems a bit unwieldy. So what's the best* way to go about doing this? Was my string-indexed list a good way to go? Or should I continue with the tuples, but unpack it into separate variables? Thanks in advance.

  • I'm going for readability, maintainability, and Pythonicness (if that's a word)
  • Hard to see what you're experiencing from this description. You seem to be blaming messy code on data structure choices. In python I believe the string-indexed data structure is called a dictionary not a list. If you've somehow hacked a list to work like a dictionary it's no wonder your code is messy. – candied_orange May 14 '16 at 12:12
  • My apologies - as it turns out I was using dictionaries. – Hactar May 14 '16 at 13:38
  • Reading this again I've understood that your 'chatbot' is an IRC client that connects to an IRCd server over the normal protocol but you are trying to abstract away the details of the protocol by using a data structure to store messages and other events. You have some procedures in mind that you would like to act on this data. Have I got that right? – candied_orange May 14 '16 at 16:30
  • @CandiedOrange Yes, that is correct. – Hactar May 15 '16 at 12:04
0

Consider object oriented programming.

If you have procedures that need to act on this data, a class groups them together nicely. Your function, that takes the raw messages, could be used to construct these objects.

For maintainability try a tell, don't ask approach.

You should endeavor to tell objects what you want them to do; do not ask them questions about their state, make a decision, and then tell them what to do.

You could tell such an object: display to your channel, open a private msg window with this user, raise any of these events called for once they parse this msg.

This gets you away from procedural programming. It's a bit different but it scales really well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.