Stringly Typed Booleans

I’m getting rather hacked off seeing boolean properties typed as strings. Stringly typed is a phrase I learnt off a post from the excellent Coding Horror blog and it describes a phenomena whereby properties that are of a specific type, e.g. Boolean, Date, int, are stored needlessly as strings.

I’m working on a website that communicates with a money laundering service to check whether an individual is “bad” or not. Individuals can pass the test, but importantly it is possible to pass the test with some warning flags raised. If any of the warning flags are raised then an email should be sent off to compliance for them to do…whatever it is they do. Fair enough right?

The warning flags are obviously booleans. There was either a warning raised or there wasn’t – there are no two ways about it (no pun intended). In the serialized response, the warning flags are encoded as “Yes” or “No”…which is understandable. Now, upon receiving the response, it is parsed and turned into an internal representation. This is where things get really weird. The programmer that coded the object that stores the response from the service has decided to encode the warnings as strings, initialised to “”. Which is totally fucking bonkers.

Why?

Well, now our boolean warnings aren’t really booleans – they have WAY more than two possible values and the meaning of these values is subjective. One may consider “”, null, “No” as false, but could conceivably also consider “false” or “0″. We get the same sort of problem with true – “Yes”, “1″, “true” and then we get a whole load of unknown values which is every other possible string in the world. Which might be considered to be true.

So how the hell can any number of programmers work on this piece of code without introducing errors because of differing definitions of truthy and falsey values? Well, they can’t. To illustrate the problem further, even loosely typed languages differ in their boolean coercion, for example JavaScript and PHP:

<script>
if("0") alert('Opposite day!');
</script>

<?php
if("0") echo 'Opposite day!';
?>

JavaScript considers “0″ true but PHP considers it false. Personally I think JavaScript is “right” here, but as I said before, it is totally subjective.

The icing on the cake is of course the extra code you have to write to check the truthy or falsey string values. Something along the lines of “if x is not null and not empty and not the word No then it is probably true…probably”, which would otherwise have been coded as “if x then true” if x was a boolean – which is orders of magnitude shorter.

Of course, there are some bat shit crazy strongly typed languages that allow you to assign null to a Boolean, but that is a different story altogether.

23,143 thoughts on “Stringly Typed Booleans

  1. Thanks , I have just been searching for information approximately this topic for
    ages and yours is the greatest I’ve found out till now.
    But, what concerning the bottom line? Are you certain about the source?

  2. 汽水音乐是一款深受用户喜爱的音乐娱乐平台,为用户提供丰富多样的音乐资源与便捷的听歌体验。通过汽水音乐下载,用户可以轻松获取喜欢的歌曲内容,随时随地享受高品质音乐服务。无论是在手机端还是使用汽水音乐电脑版,都能满足不同用户的音乐播放需求。

    汽水音乐拥有丰富的歌曲库,涵盖多种音乐类型,用户可以根据个人喜好搜索热门歌曲、发现新音乐,并创建专属音乐体验。汽水音乐下载操作简单快捷,让用户能够快速进入音乐世界,享受流畅稳定的播放效果。

    对于喜欢在电脑上使用音乐软件的用户,汽水音乐电脑版提供更加舒适的操作方式,大屏界面、便捷管理以及稳定播放体验,让工作、学习和休闲时光更加精彩。通过汽水音乐电脑版,用户可以更加方便地收藏歌曲、管理音乐列表,并体验更好的音乐服务。

    选择汽水音乐,开启更加轻松、智能、高品质的音乐生活。无论是汽水音乐下载还是汽水音乐电脑版,都为用户提供更加便捷的音乐享受,让每一次聆听都充满乐趣。

  3. game apps to win real money canada, australia casino where and top online pokies and casinos canadian league, or casino
    united statesn poker 2

    My page :: gambling place, Mathias,

  4. Москва всем привет Брат снова сорвался Соседи стучат в стену Таблетки не помогают Короче единственный кто реально помог — нарколог на дом анонимно круглосуточно с опытом Осмотрел и поставил капельницу В общем не потеряйте контакты — вывод из запоя на дому москва круглосуточно https://czena.narkolog-na-dom-moskva-rty.ru Не ждите пока станет хуже Перешлите тем кто в такой же ситуации

  5. Hey there! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing a few months of
    hard work due to no backup. Do you have any methods to stop hackers?

  6. Соблюдаем конфиденциальность бережно общаемся с пациентом и его близкими на каждом этапе. Узнать больше – вывод из запоя цена геленджик

  7. Thanks for some other informative website.
    Where else could I am getting that kind of information written in such a perfect way?
    I have a venture that I’m just now working on, and I have been on the
    glance out for such information.

  8. Обеспечение своевременной наркологической помощи с выездом на дом в Каменске-Уральском — важный аспект комплексного лечения алкогольной и наркотической зависимости. Услуга вызова нарколога на дом позволяет получить квалифицированную медицинскую помощь в комфортных условиях что снижает стресс и способствует более быстрому восстановлению. Узнать больше – нарколог на дом в каменске-уральском

  9. Алкогольный запой представляет собой тяжелое состояние вызванное длительным бесконтрольным употреблением спиртных напитков. Без медицинского вмешательства вывести организм из запоя может быть сложно и даже опасно. Срочная помощь нарколога требуется при следующих признаках: Выяснить больше – капельница от запоя на дому нижегородская область

  10. Люди подскажите Ситуация критическая Родственники не знают что делать В больницу тащить страшно Короче только это реально спасло — наркологическая помощь на дому круглосуточно качественно Дал рекомендации и успокоил семью В общем жмите чтобы сохранить — нарколог на дом вывод https://czena.narkolog-na-dom-moskva-rty.ru Не ждите пока станет хуже Перешлите тем кто в такой же ситуации

  11. Здорова народ Близкий человек уже несколько дней в запое Родственники не знают что делать В больницу тащить страшно Короче врач приехал и поставил систему — наркологическая помощь на дому эффективно Дал рекомендации и успокоил семью В общем не потеряйте контакты — выезд нарколога круглосуточно https://stoimost.narkolog-na-dom-moskva-pcr.ru Нарколог на дом — это реальный выход Перешлите тем кто в такой же ситуации

  12. Привет народ Задолбался я уже искать нормальные карнизы То механизм клинит Короче нашел нормальный рейтинг — какой карниз лучше выбрать по дизайну Выбор огромный В общем вся инфа вот здесь — какой карниз для штор лучше какой карниз для штор лучше Не покупайте наугад Перешлите тому кто ищет карнизы

  13. An outstanding share! I’ve just forwarded this onto a co-worker who has been conducting a little research on this.
    And he in fact ordered me breakfast due to the fact that I discovered it for him…
    lol. So let me reword this…. Thanks for the meal!!
    But yeah, thanks for spending time to discuss this subject here on your web page.

  14. online gambling legal in united states, united states record win online casino (Audrea) casino real
    money and free poker no deposit uk, or new casino slot sites
    usa

  15. Hmm is anyone else having problems with the images on this
    blog loading? I’m trying to find out if its a problem on my end or if
    it’s the blog. Any feedback would be greatly appreciated.

  16. College diploma fake certificates match the exact paper, embossing, and seal of your chosen university for an impressive addition to your wall. 9568

  17. I truly love your website.. Excellent colors & theme.
    Did you create this web site yourself? Please
    reply back as I’m wanting to create my own site and want
    to know where you got this from or just what the theme is named.

    Appreciate it!

  18. Слушайте кто знает Близкий человек уже несколько дней в запое Родственники не знают что делать Нужен врач прямо сейчас Короче врач приехал и поставил систему — нарколог на дом круглосуточно без выходных Осмотрел и поставил капельницу В общем не потеряйте контакты — наркология на дому вызов нарколога https://stoimost.narkolog-na-dom-moskva-pcr.ru Звоните прямо сейчас Перешлите тем кто в такой же ситуации

  19. Люди подскажите Объездил кучу магазинов — везде одно и то же То механизм клинит Короче единственные кто честно рассказывает — лучшие настенные карнизы с гарантией Алюминий сталь пластик дерево В общем смотрите сами по ссылке — лучшие настенные карнизы лучшие настенные карнизы Не покупайте наугад Перешлите тому кто ищет карнизы