简体   繁体   中英

better maintainable way to combine strings from multiple options

I have a scenario where the user can pass in multiple options. For each option passed in, I will get the text and then finally merge the text from multiple options and return a single string. Here is how I'm doing it for three options that I accept today. The code already looks unmaintainable and as I add more options, the logic will get worse:

if (len(self.options.passedin.split(",")) > 0): #multiple options were passed in
  ops = self.options.passedin.split(",")
  for op in ops:
     if (op == "option1"):
         op1_text = get_text_for_option1()
     elif (op == "option2"):
         op2_text = get_text_for_option2()
     elif (op == "option3"):
         op3_text = get_text_for_option3()

   #all three were passed in
   if ("option1" in ops and "option2" in ops and "option3" in ops):
      op1_op2 = op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op2_text.split())
      op3_op1_op2 = op1_op2 + " " + ' '.join(w for w in op1_op2.split() if w not in op3_text.split())
      return op3_op1_op2
   #option1 and option2 were passed in
   elif ("option1" in ops and "option2" in ops and "option3" not in ops):
      return op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op2_text.split())
   #option1 and option3 were passed in
   elif ("option1" in ops and "option3" in ops and "option2" not in ops):
      return op1_text + " " + ' '.join(w for w in op1_text.split() if w not in op3_text.split())
   #option2 and option3 were passed in
   elif ("option2" in ops and "option3" in ops and "option1" not in ops):
      return op2_text + " " + ' '.join(w for w in op2_text.split() if w not in op3_text.split())

The methods get_text_for_option1 get_text_for_option2 get_text_for_option3 can't be combined.

Use a dict to map your option names to the appropriate function which returns the option text, join those together, then take the unique words, eg:

from collections import OrderedDict

options = {
    'option1': get_text_for_option1,
    'option2': get_text_for_option2,
    'option3': get_text_for_option3
}

input_text = 'option3,option1,option2'

all_text = ' '.join(options[opt]() for opt in input_text.split(','))
unique = ' '.join(OrderedDict.fromkeys(all_text.split()))
if (len(self.options.passedin.split(",")) > 0): #multiple options were passed in
    ops = self.options.passedin.split(",")
    opts = {
        'op1': get_text_for_option1() if 'option1' in ops else ' '
        'op2': get_text_for_option2() if 'option2' in ops else ' '
        'op3': get_text_for_option3() if 'option3' in ops else ' '
    }
    return (opts['op1'] + opts['op2'] + opts['op3']).strip()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM