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.

5,108 thoughts on “Stringly Typed Booleans

  1. Legacy of Undead Dragon Abyssways Den blændende grafik og det elektrificerende gameplay på Gates of Olympus kan være fængslende, men husk, at selv de modigste helte har brug for en slagplan! Mens jagten på episke gevinster er en del af det sjove, er ansvarligt spil afgørende for en virkelig mindeværdig fornøjelse. Her er nogle enkle tips, der kan hjælpe dig med at navigere i den spændende verden på Gates of Olympus 1000 og minimere potentielle tab, så du kan blive ved med at dreje hjulene (og forhåbentlig vinde gevinster) i længere tid. Lavet med kærlighed Elegance Dette spil er en klon af Gates of Olympus 1000, men med en dårligere matematisk model. Du kan sagtens spille det, men det er bedre at holde sig til originalen. Hos iGaming Explorer gør vi det nemt for dig at finde de bedste demo slots og få adgang til free-to-play funktioner. Vi opdaterer løbende vores platform med nye anmeldelser og anbefalinger, så du altid har adgang til de nyeste og bedste slots på markedet. Uanset om du er til actionfyldte eventyr, klassiske frugtsymboler eller komplekse strategispil, har vi noget for enhver smag.
    https://salamastra.sviluppo.host/wanted-dead-or-a-wild-en-spiloplevelse-med-hacksaw-gaming/
    Strategisk spil: For strategiske spillere tilføjer Køb-funktionen et nyt lag af beslutningstagning. At vælge hvornår og hvor ofte man skal bruge denne funktion kan være en integreret del af deres overordnede strategi for at maksimere afkastet. Gates of Olympus Super Scatter leverer en vellykket evolution af den elskede serie med dramatisk øget gevinstpotentiale. Super Scatter-funktionen tilføjer en spændende dimension med mulighed for øjeblikkelige massive udbetalinger, mens de klassiske elementer som tumbles og progressive multiplikatorer bevares. Nedenfor finder du nogle vigtige informationer omkring Gates of Olympus. Da jeg spillede Gates of Olympus, blev jeg faktisk overrasket over, hvor ofte den gav gevinst. I et spil med så høj volatilitet ville man ikke forvente, at der så tit var en vinderkombination, men det skete ret ofte. Jeg fik i mine første fire til fem spins ikke den helt store udbetaling, men allerede i sjette spin indtraf en imponerende “Mega Win”, hvor jeg opnåede omkring 300 gange indsatsen i et enkelt spin.

  2. La slot machine Pirots 3 prodotta da Elk Studios si immerge in un contesto western, ricreando con vivacità e minuzia un’atmosfera del selvaggio West. Il setting del gioco è una piccola cittadina al tramonto, caratterizzata da costruzioni in legno tipiche dell’epoca quali saloon, ufficio dello sceriffo e negozi di souvenir. La palette di colori dominante nel cielo, con sfumature di viola e rosa, contribuisce a instaurare un senso di mistero e intrigante avventura. 0% 4star reviews  Il nostro articolo di confronto su Pirots propone uno sguardo più approfondito sulle tre slot della saga. Pirots 4 è un vero trionfo di animazione digitale. La qualità grafica è simile a quella dei migliori film d’animazione, con dettagli curati e uno stile cartoonesco che non scade mai nel banale. I pappagalli sono espressivi, le ambientazioni mutano dinamicamente e la griglia sembra un’entità viva, pulsante.
    https://vfkeducacao.com.br/recensione-di-plinko-di-bgaming-il-gioco-casino-che-sta-conquistando-litalia/
    Di seguito puoi consultare l’offerta di gioco di Totosì e decidere a cosa giocare, che tu sia un appassionato di scommesse sportive o un fan del casinò trovi un’ampia gamma di intrattenimento tra cui scegliere. Per giocare basta essere maggiorenni, procedere con la registrazione sul sito ed effettuare una prima ricarica del conto gioco. Dopodiché si avrà pieno accesso a tutti i giochi disponibili ed ai bonus dedicati, come il bonus di benvenuto scommesse o il bonus di benvenuto casino. Per farlo, tre e quattro solo. Sicurezza e responsabilità Non c’è nulla che impedisca loro di utilizzare le scommesse multiple mentre si cancella il bonus di benvenuto, ma il loro totale di vittorie potrebbe scendere al quarterback DJ. Raccogliere una combinazione di sette e ha colpito il jackpot, è sufficiente fare clic su Deal. KiTTY Cabana svolgere un ruolo di wild-simbolo, l’attivazione Wild Train rimane sui rulli.

  3. В джунглях ставок где каждый ресурс стремится привлечь гарантиями легких джекпотов рейтинг казино с лицензией является именно той картой что проводит сквозь дебри подвохов. Игрокам ветеранов и дебютантов которые пресытился с фальшивых заверений он инструмент чтобы ощутить настоящую rtp будто тяжесть ценной фишки в ладони. Минус ненужной ерунды только проверенные сайты там отдача не лишь цифра а ощутимая везение.Собрано из поисковых трендов словно сеть что захватывает наиболее свежие тенденции в рунете. Здесь отсутствует места про стандартных фишек каждый момент словно карта в игре где блеф раскрывается мгновенно. Игроки знают: по России стиль разговора с подтекстом в котором ирония притворяется как намёк позволяет избежать обмана.На https://don8play.hashnode.dev/rejting-onlajn-kazino-don8play-kak-vybrat-nadyozhnyj-brend-i-ne-oshibitsya?showSharer=true данный список лежит как раскрытая раздача приготовленный для игре. Загляни если хочешь ощутить биение реальной ставки минуя мифов и неудач. Тем тех любит ощущение приза он словно держать ставку в пальцах минуя пялиться по экран.

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>