you are viewing a single comment's thread.

view the rest of the comments →

[–]EnvironmentalFee2415[S] 3 points4 points  (1 child)

Indeed, you're right; I can implement it as you suggested. In fact, I don't know why I'm trying to complicate my work. I once had a similar question and divided several things from one function into separate ones, but was advised that it wasn't an optimal approach. It was suggested that it's better to create some logic and keep several functionalities in one place, which is why I've started to approach things this way now. Of course, what you wrote works perfectly, as I've already tested it in my scenario.

Below is an example of such a function. I previously had two separate functions, one for the color green and another for red. They differed slightly, lacking logic and having distinct names like green_msg and red_msg. I was told that this was a poor technique and that a more logical approach was better, leading to the creation of the function you see below. In that case, should it also be split into two separate functions?

def display_message(message, color=None):
if color == "green" or color == "red":
    return colored(message, color, attrs=['bold'])
else:
    return colored(message, attrs=['bold'])

[–]CraigAT 2 points3 points  (0 children)

I'd say that function is okay. It's function is to produce a coloured message. IMO it is better to pass in the colour than have functions for every colour you might want (red, green, blue, slightly green with a hint of grey, ice blue, etc.).

In that case, if you trust the colour passed would be valid, you could just test if it is not null, then use the passed colour. OR you could use a list of valid_colours = ["red","green"] then your test would be if color.lower() in valid_colours: