Created
August 21, 2014 10:33
-
-
Save phuibonhoa/4a3da3649d0671f0164e to your computer and use it in GitHub Desktop.
Use named args for boolean parameters.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Boolean paramters easily lose their context/meaning. Ex. car.drive(true) # what is true? | |
# | |
# (1) If you have booleans, use named args. | |
# (2) If you dont have named args, use an options hash with fetch. | |
# (3) At the very worse, have the method take a meaningful string/symbol and determing truthiness from the passed value. | |
# BAD. Hard to tell what the boolean means when calling the method. | |
# | |
# load_video('kitty-yawn.mp4', true) | |
# load_video('kitty-yawn.mp4', false) | |
def load_video(url, autoplay=true) | |
video = open(url) | |
video.play if autoplay | |
end | |
# 1) Named Args (Best) | |
# | |
# load_video('kitty-yawn.mp4', autoplay: true) | |
# load_video('kitty-yawn.mp4', autoplay: false) | |
def load_video(url:, autoplay: true) | |
# ... | |
end | |
# 2) Options Hash | |
# | |
# load_video('kitty-yawn.mp4', autoplay: true) | |
# load_video('kitty-yawn.mp4', autoplay: false) | |
def load_video(url:, options={}) | |
autoplay = options.fetch(:autoplay) { true } | |
# ... | |
end | |
# 3) Meaningful value translated to bool by method. | |
# | |
# load_video('kitty-yawn.mp4', :autplay) | |
# load_video('kitty-yawn.mp4', :manual) | |
def load_video(url:, mode) | |
autoplay = mode == :autoplay ? true : false | |
# ... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment