Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for "get" functions

I am new to Python.

Assume I have a dictionary which holds power supply admin state. (OK = Turned on. FAIL = Turned off).

There are several way to write the "get" function:

1st way

is_power_supply_off(dictionary)
  gets the admin state from dictionary.
  returns true if turned off.
  returns false if turned on.

is_power_supply_on(dictionary)
  gets the admin state from dictionary.
  returns true if turned on.
  returns false if turned off.

2nd way

is_power_supply_on_or_off(dictionary, on_or_off)
  gets the admin state from dictionary.
  returns true/false based on the received argument

3rd way

get_power_supply_admin_state(dictionary)
  gets the admin state from dictionary.
  return value.

Then, I can ask in the function which calls the get function

if get_power_supply_admin_state() == turned_on/turned_off...

My questions are:

Which of the above is considered best practice?

If all three ways are OK, and it`s just a matter of style, please let me know.

Is 1st way considered as "code duplication"? I am asking this because I can combine the two functions to be just one (by adding an argument, as I did in the 2nd way. Still, IMO, 1st way is more readable than 2nd way.

I will appreciate if you can share your thoughts on EACH of the ways I specified.

Thanks in advance!

like image 679
Qwerty Avatar asked Sep 01 '26 10:09

Qwerty


1 Answers

I would say that the best approach would be to have only a is_power_supply_on function. Then, to test if it is off, you can do not is_power_supply_on(dictionary).

This could even be a lambda (assuming state is the key of the admin state)::

is_power_supply_on = lambda mydict: mydict['state'].lower() == 'ok'

The problem with the first approach is that, as you say, it wastes codes.

The problem with the second approach is that, at best, you save two characters compared to not (if you use 0 or 1 for on_or_off), and if you use a more idiomatic approach (like on=True or on_or_off="off") you end up using more characters. Further, it results in slower and more complicated code since you need to do anif` test.

The problem with the third approach is in most cases you will also likely be wasting characters compared to just getting the dict value by key manually.

like image 178
TheBlackCat Avatar answered Sep 03 '26 22:09

TheBlackCat



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!