Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it always the best idea to write a function for anything that needs to repeat twice?

Myself, I can't wait to write a function when I need to do something more than twice. But when it comes to things that only appear twice, it's a bit more tricky.

For code that needs more than two lines, I'll write a function. But when facing things like:

print ("Hi, Tom")
print ("Hi, Mary")

I'm hesitant to write:

def greeting(name):
    print ("Hi, " + name)

greeting('Tom')
greeting('Mary')

The second one seems too much, doesn't it?


But what if we have:
for name in vip_list:
    print (name)
for name in guest_list:
    print (name)

And here is the alternative:

def print_name(name_list):
    for name in name_list:
        print (name)

print_name(vip_list)
print_name(guest_list)

Things become tricky, no? It's hard to decide now.

What's your opinion about this?


1 Answers

I think you are right to be hesitant to define functions in these cases, because really what you want is to abstract the repetition, not the thing being repeated.

For your first example,

for name in "Tom", "Mary":
    print("Hi, %s" % (name,))

For your second,

for lst in vip_list, guest_list:
    for name in lst:
        print(name)

or, depending on the context, something like this might be more expressive:

for name in itertools.chain(vip_list, guest_list):
    print(name)
like image 172
chepner Avatar answered Nov 18 '25 20:11

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!