Skip to content

Instantly share code, notes, and snippets.

@andremedeiros
Created December 16, 2014 17:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andremedeiros/bbf423220d63de017721 to your computer and use it in GitHub Desktop.
Save andremedeiros/bbf423220d63de017721 to your computer and use it in GitHub Desktop.
Style poll
# Option 1
info = if publication
"Title: #{ publication.title } (ID: #{ publication.id })"
else
'N/A'
end
# Option 2
info = case publication
when Publication then puts "Title: #{ publication.title } (ID: #{ publication.id })"
when nil then puts 'N/A'
end
@PericlesTheo
Copy link

as it is, first one.

@andremedeiros
Copy link
Author

Can I ask why?

@PericlesTheo
Copy link

the indentation looks a bit better which makes it more readable.

@PericlesTheo
Copy link

what do you prefer?

@andremedeiros
Copy link
Author

Actually I prefer 2. Ideally I'd love Ruby to have something like this:
https://github.com/xavier/elixir-exercises/blob/master/fizzbuzz.exs

@PericlesTheo
Copy link

That is nice!

@medeirosT
Copy link

I prefer #2. Looks more pleasing to the eye. Though a "case" when there's only two outcomes is kinda weird, but I'm not familiar with the language, so there might be another outcome of this.

@rudiservo
Copy link

depends on how many "cases you have", for one either is fine but if you have too many maybe the second one is more readable for faster debuging.

@thelazycamel
Copy link

how about a third option...

info = publication ? "Title: #{ publication.title } (ID: #{ publication.id })" : "N/A"

@felixhageloh
Copy link

one funky style i've seen:

info = pubication 
     ?  "Title: #{ publication.title } (ID: #{ publication.id })"
     : "N/A"

I kinda like how the operators align it but it takes a while to parse in your head if you are not used it. Also I think ruby syntax won't let you do it.

@felixhageloh
Copy link

for option 2 I also find the indentation a bit weird. Maybe if the when statements where indented or even aligned with the case.

@kpolitowicz
Copy link

def publication_caption(publication)
  return 'N/A' if publication.nil?
  "Title: #{ publication.title } (ID: #{ publication.id })"
end

info = pubication_caption(publication)

Actually long term in such cases I would use the null object pattern (see https://github.com/avdi/naught) and define #to_s on both NullPublication and Publication.

From your options however, the first one seems a lot more readable, if the only case you need to address is NIlClass.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment