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.

683 thoughts on “Stringly Typed Booleans

  1. Thanks for your tips about this blog. One thing I would want to say is the fact purchasing electronic products items over the Internet is not something new. In truth, in the past decade alone, the marketplace for online gadgets has grown significantly. Today, you can get practically just about any electronic gizmo and other gadgets on the Internet, from cameras along with camcorders to computer elements and video games consoles.

  2. Казино 1вин очень разнообразное много провайдеров и интересных игр. Слоты работают без зависаний процесс плавный. Вывод денег прошёл спокойно и без проверок: 1 win

  3. Greetings from Colorado! I’m bored at work so I decided to check out your blog on my iphone during lunch break. I love the knowledge you provide here and can’t wait to take a look when I get home. I’m amazed at how fast your blog loaded on my phone .. I’m not even using WIFI, just 3G .. Anyhow, very good site!

  4. okmark your blog and check again here regularly. I am quite certain I?ll learn lots of new stuff right here! Best of luck for the next!

  5. снятие наркологической ломки

  6. Играю на 1xbet уже давно официальный сайт работает стабильно без вылетов. Вывод средств всегда приходит вовремя без лишних проверок. Удобно что все функции легко найти https://1xbet-loss.top/

  7. Everyone loves what you guys are usually up too. Such clever work and reporting! Keep up the good works guys I’ve included you guys to my blogroll.

  8. I’m really inspired with your writing abilities and also with the format on your weblog. Is that this a paid topic or did you customize it your self? Either way stay up the excellent quality writing, it?s uncommon to see a great blog like this one nowadays..

  9. Thanks for your submission. I would like to say that the first thing you will need to accomplish is verify if you really need repairing credit. To do that you will have to get your hands on a copy of your credit profile. That should really not be difficult, because government mandates that you are allowed to acquire one no cost copy of your own credit report per year. You just have to ask the right folks. You can either check out the website for the Federal Trade Commission or perhaps contact one of the major credit agencies immediately.

  10. Зеркало 1win всегда открывается даже если основной сайт недоступен. Все функции сохраняются полностью. Вывод средств оформил без трудностей: 1 вин

  11. I?m impressed, I must say. Actually not often do I encounter a weblog that?s both educative and entertaining, and let me let you know, you have hit the nail on the head. Your thought is excellent; the difficulty is something that not sufficient individuals are talking intelligently about. I am very blissful that I stumbled throughout this in my search for something referring to this.

  12. Hello there, just became alert to your blog through Google, and found that it is really informative. I?m gonna watch out for brussels. I will appreciate if you continue this in future. Many people will be benefited from your writing. Cheers!

  13. The following time I read a blog, I hope that it doesnt disappoint me as much as this one. I imply, I know it was my choice to read, but I truly thought youd have one thing attention-grabbing to say. All I hear is a bunch of whining about one thing that you possibly can repair in the event you werent too busy looking for attention.

  14. Thank you a bunch for sharing this with all people you actually understand what you are talking about! Bookmarked. Kindly also discuss with my website =). We can have a link trade contract among us!

  15. Can I simply say what a relief to seek out someone who actually knows what theyre speaking about on the internet. You undoubtedly know learn how to convey a problem to light and make it important. Extra people have to learn this and understand this aspect of the story. I cant imagine youre no more in style since you positively have the gift.

  16. I simply could not leave your site before suggesting that I really loved the usual information a person provide in your guests? Is gonna be back regularly to investigate cross-check new posts

  17. Ни разу не подвели даже в самые загруженные часы. Алкоголь всегда оригинальный сервис на уровне. Всё приходит быстро и точно. Теперь если нужна доставка алкоголя 24 7 москва заказываю только здесь: https://drinkio70.ru/

  18. Очень интересная статья! Я был поражен ее актуальностью и глубиной исследования. Автор сумел объединить различные точки зрения и представить полную картину темы. Браво за такой информативный материал!

  19. Уже несколько раз брал горячие туры через это агентство и каждый раз поездка получалась удачной. Всегда радуют адекватные цены и то что можно улететь буквально на следующий день. Консультанты подбирают варианты так будто ищут тур для себя. Все документы оформляются быстро и без лишних вопросов. За последние годы я ни разу не столкнулся с задержками или непонятными моментами. Очень удобный и надёжный сервис для спонтанных путешествий: туры в египет горячие

  20. Attractive component to content. I simply stumbled upon your blog and in accession capital to say that I acquire actually loved account your weblog posts. Any way I will be subscribing to your feeds and even I success you access consistently fast.

  21. Hey there would you mind letting me know which webhost you’re working with? I’ve loaded your blog in 3 completely different browsers and I must say this blog loads a lot quicker then most. Can you suggest a good internet hosting provider at a fair price? Kudos, I appreciate it!

  22. I was more than happy to search out this internet-site.I wished to thanks on your time for this wonderful read!! I positively enjoying every little bit of it and I’ve you bookmarked to check out new stuff you weblog post.

  23. Thanks for revealing your ideas here. The other issue is that any time a problem arises with a computer system motherboard, people should not take the risk with repairing it themselves for if it is not done properly it can lead to permanent damage to the complete laptop. It is almost always safe just to approach the dealer of that laptop for that repair of its motherboard. They’ve got technicians who definitely have an know-how in dealing with laptop computer motherboard issues and can get the right prognosis and accomplish repairs.

  24. Hey! Someone in my Facebook group shared this site with us so I came to look it over. I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers! Terrific blog and great design.

  25. Another thing is that when you are evaluating a good on the internet electronics store, look for web shops that are frequently updated, maintaining up-to-date with the newest products, the top deals, and helpful information on goods and services. This will make certain you are handling a shop that really stays on top of the competition and provides you what you need to make educated, well-informed electronics acquisitions. Thanks for the important tips I’ve learned from the blog.

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>