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.

13,407 thoughts on “Stringly Typed Booleans

  1. Hi this is somewhat of off topic but I was wanting
    to know if blogs use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding know-how so I wanted
    to get advice from someone with experience. Any help would be greatly appreciated!

  2. This is the perfect blog for anyone who would like to understand this topic.
    You realize a whole lot its almost hard to argue with you (not that I actually will need to…HaHa).
    You definitely put a brand new spin on a topic that has been discussed for years.
    Wonderful stuff, just wonderful!

  3. My brother recommended I may like this web site.
    He was totally right. This publish actually made my day.
    You cann’t consider just how a lot time I had spent for
    this info! Thanks!

  4. Программа 12 шагов построена как последовательный путь: человек учится признавать болезнь принимать помощь разбирать причины употребления проводить моральную инвентаризацию исправить ошибки компенсировать нанесенный ущерб и поддерживать трезвость через регулярные действия. В основе программы лежит не давление а постепенная работа с отрицанием самообманом страхами и привычкой возвращаться к прежним решениям. Получить больше информации – reabilitaciya-12-shagov

  5. Современная реабилитация 12 шагов может сочетаться с медицинской помощью если пациент находится в тяжелом состоянии. При интоксикации запое похмелье ломке тревоге бессоннице психозе депрессии употреблении наркотиков или алкоголя сначала может потребоваться нарколог врач психиатр стационар капельница детоксикация УБОД по показаниям или медикаментозное лечение. После стабилизации начинается реабилитационный процесс где главный акцент делается на понимании зависимости честности ответственности группе и новой системе жизни. Изучить вопрос глубже – 12-shagov-programma-onlajn

  6. Реабилитация 12 шагов в Москве — это программа лечения зависимости которая помогает человеку после наркотической алкогольной или смешанной аддикции перейти от хаотичных попыток бросить к последовательной работе над собой. Программа 12 шагов применяется при наркомании алкоголизме лудомании игромании созависимости и других формах химической зависимости. Ее цель — помочь человеку признать болезнь прекратить употреблять психоактивные вещества получить опору научиться жить трезво и постепенно вернуть способность управлять своими решениями. Углубиться в тему – programma-12-shagov-dlya-sozavisimyh

  7. Реабилитация 12 шагов в Москве с последовательной программой восстановления участием специалистов и поддержкой на каждом этапе в наркологической клинике «Триумф». Ознакомиться с деталями – http://reabilitaciya-12-shagov-moskva13-1.ru

  8. Алкогольная зависимость — серьёзная болезнь которая часто сопровождается длительными запоями. Симптомы интоксикации этанолом требуют немедленного медицинского вмешательства. Признаки при которых нужно вызывать врача на дом: сильная рвота скачки артериального давления бессонница тревожность тремор спутанность сознания. Если вовремя не начать лечение алкоголизма могут развиться алкогольный психоз делирий серьёзные нарушения работы сердечно-сосудистой и нервной систем. Квалифицированная помощь на дому позволяет быстро снять абстинентный синдром и нормализовать самочувствие. Наш врач-нарколог приедет в течение 30–60 минут проведёт осмотр поставит капельницу и окажет необходимую психологическую поддержку. Не стоит заниматься самолечением — только профессиональный нарколог способен правильно оценить тяжесть состояния и подобрать эффективные препараты. Помните: каждый час промедления увеличивает риск серьёзных осложнений поэтому действовать нужно незамедлительно. Позвоните прямо сейчас и дежурный консультант оформит вызов сориентирует по ценам и ответит на любые вопросы. Выяснить больше – нарколог на дом круглосуточно

  9. Обратившись к нам вы получаете не только экстренную помощь но и полный комплекс услуг с гарантией качества и анонимности. Вот основные преимущества нашей работы: Детальнее – вызов врача нарколога на дом

  10. Great info. Lucky me I found your site by accident (stumbleupon).
    I’ve book marked it for later!

  11. Реабилитация наркоманов 12 шагов — это программа лечения зависимости которая помогает наркоману после употребления наркотиков алкоголя или других психоактивных веществ перейти к трезвому поведению разобраться с причинами болезни и выстроить новый порядок действий. Реабилитация подходит наркоманам наркозависимым алкоголикам людям с игроманией лудоманией созависимым родственникам и тем кто уже проходил лечение детоксикацию кодирование стационар вывод из запоя консультацию нарколога или врача но снова столкнулся со срывом. Выяснить больше – программа 12 шагов

  12. Реабилитация наркоманов по методу 12 шагов может сочетаться с психотерапией групповой терапией консультацией нарколога работой психолога наблюдением врача медикаментозной терапией стационаром детоксикацией и помощью родственникам. Если человек находится в острой интоксикации переживает ломку запой похмельный синдром тревогу бессонницу психоз или выраженное физическое истощение сначала может потребоваться наркологическая помощь срочный вызов стационар снятие ломки капельница вывод из запоя или детоксикация. После стабилизации начинается реабилитация как отдельная программа направленная на долгосрочные изменения. Углубиться в тему – программа 12 шагов самостоятельно

  13. Artikelnya sangat menarik! Sharing ini sangat
    relevan bagi mereka yang ingin mulai bermain taruhan daring.
    Memang benar, memilih platform terpercaya sangat penting agar permainan lebih fair.
    **SBOMAXX – Situs Bookie Taruhan Daring Indonesia Terpercaya** menjadi pilihan tepat karena menyediakan proses deposit withdraw cepat.

    Sukses selalu untuk blognya! Kunjungi SBOMAXX

  14. Thanks in support of sharing such a fastidious idea, piece of writing is nice, thats why i have read it entirely

  15. Hi there! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but
    I’m not seeing very good gains. If you know of any please share.
    Cheers!

  16. Hello, constantly i used to check web site posts here
    in the early hours in the morning, as i love to learn more
    and more.

  17. Hi! Do you know if they make any plugins to assist with Search Engine Optimization? I’m trying to get
    my blog to rank for some targeted keywords but I’m not seeing very good
    gains. If you know of any please share.
    Kudos!

  18. Запоя вывод в клинике Сочи: лечение алкогольной зависимости детоксикация капельница помощь нарколога на дому кодирование и реабилитация. Узнать больше – скорая вывод из запоя сочи

  19. Right here is the right web site for everyone who would like to understand this topic.
    You know a whole lot its almost tough to argue with you (not that I personally will need to…HaHa).
    You certainly put a fresh spin on a topic which has been written about
    for a long time. Excellent stuff, just wonderful!

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

  21. I am no longer sure where you are getting your information, but good topic.
    I must spend a while learning much more or working
    out more. Thank you for excellent info I used to be in search of this
    info for my mission.

  22. Hello, Neat post. There is an issue together with your site in web explorer,
    would test this? IE still is the market chief and a good component to people will pass over your magnificent writing due to this problem.

  23. Hello! Someone in my Facebook group shared this site with us so I came to take a look. I’m definitely loving the information. I’m book-marking and will be tweeting this to my followers! Fantastic blog and outstanding design.

  24. I’m in awe of the author’s ability to make complex concepts understandable to readers of all backgrounds. This article is a testament to his expertise and dedication to providing valuable insights. Thank you, author, for creating such an compelling and insightful piece. It has been an absolute pleasure to read!

  25. These are really fantastic ideas in regarding blogging. You have touched some
    nice points here. Any way keep up wrinting.

  26. Helpful info. Lucky me I found your site accidentally, and I’m shocked why this twist of fate didn’t happened earlier!
    I bookmarked it.

  27. ข้อมูลชุดนี้ อ่านแล้วได้ความรู้เพิ่ม ค่ะ
    ดิฉัน ไปอ่านเพิ่มเติมเกี่ยวกับ เนื้อหาในแนวเดียวกัน
    สามารถอ่านได้ที่ edm111 official site
    ลองแวะไปดู
    มีการยกตัวอย่างที่เข้าใจง่าย
    ขอบคุณที่แชร์ ข้อมูลที่มีประโยชน์ นี้
    และอยากเห็นบทความดีๆ แบบนี้อีก

  28. This is a very informative post about online casinos
    and betting platforms. I especially liked how it explains the importance of
    choosing a secure site before signing up.

    Many players often ask where they can find reliable
    gaming platforms with fair odds and smooth payouts.

    From what I’ve seen, checking platforms like vn22vip helps
    users compare features, bonuses, and overall experience.

    Thanks for sharing these insights — they’re
    helpful for both beginners and experienced bettors.

  29. Fastidious respond in return of this question with genuine arguments and explaining all
    about that.

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

  31. Excellent blog! Do you have any recommendations for aspiring writers?
    I’m planning to start my own blog soon but I’m a little
    lost on everything. Would you advise starting
    with a free platform like WordPress or go for a paid option?
    There are so many options out there that I’m completely confused ..
    Any suggestions? Cheers!

  32. What’s up, yes this post is genuinely good and I
    have learned lot of things from it on the topic of blogging.
    thanks.

  33. Its like you read my mind! You seem to know so much
    about this, like you wrote the book in it or something.
    I think that you can do with some pics to drive the message home a little bit, but other than that, this is excellent blog.
    A fantastic read. I’ll certainly be back.

  34. I’m really enjoying the design and layout of your blog.

    It’s a very easy on the eyes which makes it much more
    pleasant for me to come here and visit more often. Did you hire out a
    designer to create your theme? Excellent work!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>