JuliaLozova / messenger

0 stars 0 forks source link

Decomposing into functions #2

Open AdamDorwart opened 7 years ago

AdamDorwart commented 7 years ago

Okay so my question -- Is it possible to make this section of code a function (from the elif on)? -- And if so data and item would be their parameters?

https://github.com/JuliaLozova/messenger/blob/master/MessengerWithSelect.py#L84-L106

and isntead of an elif, its an if in the other function.

i try it and it breaks. I feel like there is a better way of going about it. I've made two functions one for the writable and the other the exceptional... but I'm kind of stuck. The inputs are funnier with this one. and is it even worth it to write this one as afunction?

also not sure if I should impliment a class... or just not worry about that yet

AdamDorwart commented 7 years ago

First of all notice that data is only referenced in that block so that would remain entirely local to the function. item however is defined outside of the block so that would be a parameter.

But that's not it. Don't the two sections of code use different input/output buffers and message_queues as well?

Furthermore you obviously couldn't just do:

def my_func(...):
  elif item is not sys.stdin:
      data = item.recv(1024)
      if data:
          # A readable client socket has data
          print('Friend:{!r}'.format(data, item.getpeername()))
      else:
          # Interpret empty result as closed connection
          print('closing', addr)
          inputs.remove(item)
          item.close()
          #Remove message queue  
          del message_queues[item]

  else:
      #inp = sys.stdin.write('[Me]:')
      #sys.stdout.write('[Me]') + inp 
      inp = sys.stdin.readline()
      socket_list = message_queues.keys()
      for sock in socket_list:
          message_queues[sock].put(inp)
          if sock not in outputs:
              outputs.append(sock)

Because what is an elif without an if first? And however you resolve that could also have interesting implications for the else (Need to make sure the refactor is logically equivalent)