Article N6KH CodeSOD: The Coercive Types

CodeSOD: The Coercive Types

by
Remy Porter
from The Daily WTF on (#N6KH)

Loosely typed languages may offer certain advantages in terms of ease of use and flexibility, but they bring another challenge: it's difficult to know what it is you're looking at. With no compiler type checking, it's hard to compare two things, and that becomes extremely problematic when you're working with languages like, say, JavaScript.

Ruby, in its quest to "make programmers happy", took a simplistic approach to the Truthy vs. Falsy problem. False is false. Nil is false. Everything else is True. Ruby is often used by web developers, who may be more comfortable in languages like JavaScript and PHP.

That is presumably why Lisa found this debacle in her code base, placed there by a co-worker who preferred other web languages:

 def equivalent_values(old_value, new_value) if (old_value == false && new_value == "0") || (old_value == "0" && new_value == false) || (old_value == "1" && new_value == true) || (old_value == true && new_value == "1") return true end if (old_value.is_a?(Array) && old_value[0].to_s == new_value.to_s && old_value.size == 1) || (new_value.is_a?(Array) && new_value[0].to_s == old_value.to_s && new_value.size == 1) return true end false end

Yes, this also does some type coercion, after a fashion, so it's a little broader that mere "Truthiness", so my initial description may have been incomplete or misleading. For this block of code, that wouldn't be the first time. For reasons no one can explain, this method was part of a module called TimestampHelper.

scout%2050x50.png[Advertisement] Scout is the best way to monitor your critical server infrastructure. With over 90 open source plugins, robust alerting, beautiful dashboards and a 5 minute install - Scout saves youvaluable engineering time. Try the server monitoring you'll today.Your first 30 days are free on us. Learn more at Scout. TheDailyWtf?d=yIl2AUoC8zAt8-JTI_Y7GE
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments