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.

21,168 thoughts on “Stringly Typed Booleans

  1. you’re actually a good webmaster. The site loading velocity is
    amazing. It kind of feels that you are doing any distinctive trick.
    Also, The contents are masterwork. you have performed a magnificent activity in this topic!

  2. Слушайте кто сталкивался Отец не выходит из штопора Родственники не знают что делать Таблетки не помогают Короче врачи приехали и поставили систему — вывод из запоя щелково круглосуточно Через пару часов человек пришёл в себя В общем вся инфа по ссылке — вывод из запоя в щёлкове https://chastnyj.vyvod-iz-zapoya-na-domu-moskva-snp.ru Звоните прямо сейчас Перешлите тем кто в такой же ситуации

  3. Здорова народ Муж просто потерял себя Дети напуганы Нужна срочная помощь на дому Короче врачи приехали и поставили систему — вывод из запоя на дому срочно Через пару часов человек пришёл в себя В общем не потеряйте контакты — вывод из запоя на дому в люберцах https://anonimno.vyvod-iz-zapoya-na-domu-moskva-jst.ru Не ждите пока станет хуже Перешлите тем кто в такой же ситуации

  4. 서울 강서구 마곡나루의 프라이빗 테라피샵 유럽식 스웨디시 로미로미 오일 바디
    테라피와 스페인 천연 왁싱을 1 1 프라이빗
    룸에서 진행합니다

  5. hi!,I really like your writing very a lot! share we keep in touch
    extra about your article on AOL? I need an expert in this house to
    unravel my problem. May be that is you! Having a look forward
    to see you.

  6. Клиника Обновление также активно занимается просветительской деятельностью. Мы организуем семинары и лекции которые помогают обществу лучше понять проблемы зависимостей их последствия и пути решения. Повышение осведомленности является важным шагом на пути к улучшению ситуации в этой области. Выяснить больше – kapelnicza-ot-zapoya-czena irkutsk

  7. Люди помогите советом Муж просто потерял себя Соседи стучат в стену Таблетки не помогают Короче единственное что вытащило из запоя — нарколог вывод из запоя мытищи с опытом Приехали через 40 минут В общем телефон и цены тут — закодироваться от алкоголя мытищи дома https://czena.vyvod-iz-zapoya-na-domu-moskva-snp.ru Звоните прямо сейчас Перешлите тем кто в такой же ситуации

  8. Давно хотел съездить в Териберку. Видел фото — красота невероятная. Переживал что не найду дорогу. Хорошо что нашёл — проводника по Териберке. Показал все локации. И историю этих мест. Короче — один бы точно потерялся. Закаты туманы птицы — всё объяснил. Теперь понятно — с проводником всё по-другому. Настоятельно рекомендую — это стоит того. местные гиды в териберке местные гиды в териберке Там можно договориться. Цены адекватные. Приедет в Мурманск встретит. Обязательно вернусь. Если собираетесь — смело связывайтесь. Проверил лично. И вам советую. Счастливого пути

  9. Капельница на дому применяется при похмельном синдроме слабости дрожи тошноте тревожности нарушении сна и обезвоживании если отсутствуют признаки критических осложнений. Следует обратиться к специалисту если запой продолжается несколько дней человеку становится тяжелее отказаться от спиртного или ранее выход из подобных состояний сопровождался ухудшением самочувствия. При больших объемах выпитого особенно важно исключить серьезное токсическое поражение внутренних органов. Получить больше информации – vyzvat-kapelnicu-na-dom-ot-zapoya-anonimno

  10. Слушайте кто сталкивался Ситуация критическая Соседи стучат в стену Нужна срочная помощь на дому Короче только это реально спасло — вывод из запоя щелково круглосуточно Приехали через 40 минут В общем жмите чтобы сохранить — вывод из запоя в щелково на дому https://reabilitacziya.vyvod-iz-zapoya-na-domu-moskva-snp.ru Звоните прямо сейчас Перешлите тем кто в такой же ситуации

  11. This is hands down one of the finest articles I’ve read on this topic! The author’s thorough knowledge and zeal for the subject shine through in every paragraph. I’m so grateful for coming across this piece as it has enriched my understanding and sparked my curiosity even further. Thank you, author, for investing the time to create such a outstanding article!

  12. One thing I would like to say is always that car insurance cancelling is a hated experience and if you are doing the best things as being a driver you simply won’t get one. Some people do obtain notice that they are officially dumped by their insurance company and many have to struggle to get supplemental insurance after having a cancellation. Low-cost auto insurance rates are frequently hard to get following a cancellation. Knowing the main reasons pertaining to auto insurance cancellation can help people prevent sacrificing one of the most important privileges accessible. Thanks for the ideas shared by means of your blog.

  13. Продолжительный запой создает высокую нагрузку на печень сердце сосуды головной мозг нервную систему и органы пищеварения. На фоне регулярного поступления алкоголя нарушается баланс жидкости и электролитов растет концентрация токсических продуктов распада этанола появляются тремор слабость головная боль тревога бессонница тошнота рвота и колебания давления. Профессиональный вывод позволяет контролируемо прекратить употребление спиртного провести детоксикацию и начать восстановление организма. Изучить вопрос подробнее – скорая вывод из запоя Санкт-Петербург

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>