Earlier quoted context omitted.
Except where writing negative conditionals are clearer. For example turning: if(a) { if(b) { if (c) { // Do something. } } } Into: if(!a) { } elseif(!b) { } elseif(!c) { } else { // Do something. }
Or if (a && b && c) { // Do something. }
Clearer Conditionals using De Morgan's Laws
21–30 of 82 posts
Re: Clearer Conditionals using De Morgan's Laws
#22Sorry, but I just don't see what was unclear about the original conditional. Anyone with a basic grasp of logic could parse it instantly. As for the refactoring, that might be a good choice (I myself prefer positive boolean methods) but it's not a logic lesson.
Re: Clearer Conditionals using De Morgan's Laws
#23If you want to get good at clarifying conditionals, take an electronics class and revel in the Karnaugh maps.
There are very few requisites too. Some high schools and trade schools teach the material to 16-18 year-olds in a year or two. I suspect this is partially why it's so often omitted in CS curriculum. It's too easy.
Re: Clearer Conditionals using De Morgan's Laws
#24Re: Clearer Conditionals using De Morgan's Laws
#25Sorry, but I just don't see what was unclear about the original conditional. Anyone with a basic grasp of logic could parse it instantly. As for the refactoring, that might be a good choice (I myself prefer positive boolean methods) but it's not a logic lesson.
Re: Clearer Conditionals using De Morgan's Laws
#26Re: Clearer Conditionals using De Morgan's Laws
#27The refactored version reads like:
Allow access to the site if the user is signed in or has a trusted IP.
The original (DeMorgan's applied):
Allow access to the site if the user isn't signed out or doesn't have an untrusted IP.
It does help to have a good understanding of propositional logic and Boolean algebra, though.
Re: Clearer Conditionals using De Morgan's Laws
#28Re: Clearer Conditionals using De Morgan's Laws
#29Re: Clearer Conditionals using De Morgan's Laws
#30Good naming conventions are pretty key here. My guess is the original writer of that code had used those in something else entirely, then reused those methods in a new method so he wouldn't have to rewrite. I always feel like it's better to positively name Boolean values, personally, but I know everyone is different.
def signed_out?
# Code
end
def signed_in?
!signed_out?
end
Which can easily start to become its own problem. On the other hand, with Ruby, it might be worthwhile to define something like Class#invert such that you have this: def signed_out?
# Code
end
method_invert :signed_out?, :signed_in?
Dunno. I haven't ever found myself in a position where it mattered.