Sunday, January 29, 2017

Words of Radiance (The Stormlight Archive #2), by Brandon Sanderson

Book cover Brandon Sanderson does not disappoint with the sequel to Way of Kings. Quite the opposite, in fact, weaving more and more into the vast tapestry that is the world of the Stormlight Archive series. The characters converge towards a point in time and space where everything and anything will be decided, the fate of the entire world, with just a few courageous people standing between life and complete desolation.

Words of Radiance focuses more on the main characters, with less distractions that might take the reader out of the flow of the story. However, even if the scope of their achievements explodes, the power of their stories loses a bit of the desperation and energy from the first book. We no longer have powerless broken people trying to survive, but magical beings full of strength doing extraordinary things. Ironically, it is their success that makes them less easy to identify and empathize with. The author throws challenges in front of them, but they seem inconsequential compared to the ones in Way of Kings. I feel like he has grown attached to them and finds it difficult to torture them as a good writer should. On the other hand Sanderson is a positive person, most of this writing being lighthearted and less dark and brooding, so this is not a disappointment.

The climax is a gigantic clash between forces that have slowly grown since the beginning of the series. Sanderson does a wonderful job tying the separate strands of his world into a single story, maybe a bit too much so. The Roshar and Helaran connections felt a bit strained, not unlike Luke Skywalker discovering his greatest ally and greatest enemy are family members. The author better be careful not to put immense effort to create a vast universe, only to shrink it by mistake by connecting everything with everything and everybody with everybody.

And again the final pages of the book feel weak, as they come after the powerful climax, yet they are necessary to tie in some story arks and seed the beginning of others. Yes, the book ends with a promise that what happened in it is just the mere beginning, a small part of the larger picture, so expect little closure. Sanderdon is a prolific author and I am sure he will write the next books in the series fast enough to keep me engaged, but be aware the series is planned to be at least ten main books with about just as much companion stories and novels. This... will take a while. Oathbringer, the third book, is scheduled to be released in November 2017.

Bottom line: I recommend the book and the series and the author. No fantasy reader should ignore Brandon Sanderson if they are anything like me. Just make sure you are ready to get invested in the story only to wait every year for the next chapter to be released.

Friday, January 27, 2017

Ode to the White Man

I am hearing more and more this expression that leaves me baffled: "Check your privilege!". It is directed at us, White men, by women, colored folk and gays. It is intended to make us aware of our superior position in order for us to feel guilty over it. Really? That's what you got?

First of all, shit doesn't just happen: it takes time and effort! Do you think that God bestowed our supremacy onto us or something? No! If you believe that you have bought into all the stories we've fed you. We worked hard to get where we are! What have you done? Black people have been the majority of people on Earth for millions of years, but when does humanity grow exponentially together with the living standards? That's right! When the White Man takes control. Women have been ruling the Stone Age for millennia. Where did that get us? Nowhere, that's where! Stone fashion didn't do well, did it? And now you have the gall to ask us to check our privilege? Now the shoe is on the other foot and you are sour about it. Deal with it! Facts, bitches! Not alternative ones, either. The White Man management has brought this enterprise to new heights. Everything you have now is the direct consequence of our leadership. You are beneath us because we put you there!

Every time you people complain you call yourselves "minorities". No, you're not! Women are more numerous than men and White people are fewer than blacks and browns and yellows and whatever else there is on this planet. You know who's a minority? White Men! And still the privilege is yours, since we clearly allow you to exist and complain. The only group of people that have consistently been persecuted and have been a lot fewer than other folk are the homos. They are the only ones who have the right to whine. That's why everybody says whining is gay. It's true!

Yet when we complain, we are derided! You really think it is easy to keep under boot a majority of people on Earth. You think hitting women or slaves is fun? It fucking stings! You have to take all empathy and push it way way down, swallow your tears and do the right thing for everybody, because in the end we have led human kind into its Golden Age, all through our sacrifice. And if you don't like it, that's too bad, but it's mostly your fault, anyway. You make us behave like that, even when we hate it, because you keep getting above your station.

When the most powerful man on Earth is a White Man who rightfully knows the truth about the world and our place at its helm, you act all outraged. We even allowed you to vote the person you wanted and still you chose him. Oh, he lies, you say. He's a sexist racist White Man who twists the truth to further his needs. Have you even met politicians before? They are mostly White and mostly male because, statistically proven, we rule the world best. If you do something, at least do it right!

So you check *your* privilege! You get to complain, to fight for your rights, to live, all the while basking into the glory of the White Man and reaping the fruits of his labor and sacrifice. We carry you into tomorrow like a cross on Golgotha, never complaining, being spit at all the way up, but up we climb and high we reach. If you want to get to where we are, work for it like we do. Enslave some people, cull others, smack some around in the name of God. It's not fun, but it needs doing, for the betterment of humanity as a whole. In the end, you are where you are because you know it's the right place for you, otherwise you would have done something about it. You slack away while we run things for you, it's just the way of the world. Start complaining after a few million years, when you get your turn.

Wednesday, January 25, 2017

Javascript debounce function

Often we need to attach functions on Javascript events, but we need them to not be executed too often. Mouse move or scroll events can fire several times a second and executing some heavy computation directly would make everything slow and unresponsive. That's why we use a method called debounce, that takes your desired function and returns another function that will only get executed so many times in a time interval.

It has reached a certain kind of symmetry, so I like it this way. Let me explain how I got to it.

First of all, there is often a similar function used for debouncing. Everyone remembers it and codes it off the top of the head, but it is partly wrong. It looks like this:
function debounce(fn, wait) {
    var timeout=null;
    return function() {
        var context=this;
        var args=arguments;
        var f=function(){ fn.apply(context,args); };
It seems OK, right? Just extend the time until the function gets executed. Well, the problem is that the first time you call the function you will have to wait before you see any result. If the function is called more often than the wait period, your code will never get executed. That is why Google shows this page as *the* debounce reference: JavaScript Debounce Function. And it works, but good luck trying to understand its flow so completely that you can code it from memory. My problem was with the callNow variable, as well as the rarity of cases when I would need to not call the function immediately the first time, thus making the immediate variable redundant.

So I started writing my own code. And it looked like the "casual" debounce function, with an if block added. If the timeout is already set, then just reset it; that's the expected behavior. When isn't this the expected behavior? When calling it the first time or after a long period of inactivity. In other words when the timeout is not set. And the code looked like this:
function debounce(fn, wait) {
    var timeout=null;
    return function() {
        var context=this;
        var args=arguments;
        var f=function(){ fn.apply(context,args); };
        if (timeout) {
        } else {
            timeout=setTimeout(function() {

The breakthrough came with the idea to use the timeout anyway, but with an empty function, meaning that the first time it is called, the function will execute your code immediately, but also "occupy" the timeout with an empty function. Next time it is called, the timeout is set, so it will be cleared and reset with a timeout using your initial code. If the interval elapses, then the timeout simply gets cleared anyway and next time the call of the function will be immediate. If we abstract the clearing of timeout and the setting of timeout in the functions c and t, respectively, we get the code you saw at the beginning of the post. Note that many people using setTimeout/clearTimeout are in the scenario in which they set the timeout immediately after they clear it. This is not always the case. clearTimeout is a function that just stops a timer, it does not change the value of the timeout variable. That's why, in the cases when you want to just clear the timer, I recommend also setting the timeout variable to null or 0.

For the people wanting to look cool, try this version:
function debounce(fn, wait) {
    var timeout=null;
    var c=function(){ clearTimeout(timeout); timeout=null; };
    var t=function(fn){ timeout=setTimeout(fn,wait); };
    return function() {
        var context=this;
        var args=arguments;
        var f=function(){ fn.apply(context,args); };
            ? c()||t(f)
            : t(c)||f();

Now, doesn't this look sharp? The symmetry is now obvious. Based on the timeout, you either clear it immediately and time out the function or you time out the clearing and execute the function immediately.

Update 26 Apr 2017: Here is an ES6 version of the function:
function debounce(fn, wait) {
    let timeout=null;
    const c=()=>{ clearTimeout(timeout); timeout=null; };
    const t=fn=>{ timeout=setTimeout(fn,wait); };
    return ()=>{
        const context=this;
        const args=arguments;
        let f=()=>{ fn.apply(context,args); };
            ? c()||t(f)
            : t(c)||f();

Thursday, January 12, 2017

Way of the Kings (Stormlight Archive #1), by Brandon Sanderson

Brandon Sanderson proves again he is a brilliant writer. His Stormlight universe is not only vast and imaginative, but the characters are both compelling and well written.

Way of the Kings has some slow parts, though, and even if I kind of liked that, it is uneven in regards to its characters: some get more focus, some just a few chapters. That means that if you identify with the lead characters you will enjoy the book, but if you empathize with the lesser ones you will probably get frustrated.

I particularly enjoyed the climax. It was as it should be: the tension was rising and Sanderson just wouldn't let it go, it just kept pushing it and pushing it, filling in the motivations of the character, adding burden upon burden, making choices as difficult and as important as possible before finally allowing the release of his characters making one. Alas, the wonderful ending is followed by epilogues, several of them, which just seem boring afterwards, in comparison.

Great series, though, I recommend it highly.

Tuesday, January 03, 2017

Need help solving a code design problem: API validation

I am working on this issue that I can't seem to properly be able to solve. No matter what I do I can't shake the feeling of code smell from it. It involves a chain of validations and business operations that I want to separate. The simple scenario is this: I have a web API that receives a data transfer object and needs to perform some action, but then it gets murkier and murkier.

Simply code

The first implementation is pretty obvious. I get the DTO, perform checks on it, access the database to get more info, perform more checks, do more work until everything is done. It's easy to do, clear imperative linear programming, it does the job. However I get a bad smell from the code because I have mashed together validation and business logic. I would also like to reuse the validation in other areas of the project.

Manager and Validator

So the natural improvement is to create two flows instead of one, each with their own concern: a validator will perform checks so I know an operation is valid, then the manager performs the operation. But this soon hits a snag. Let say I want to validate that a record exists from the id that I send as a property in the DTO. If I do this check in the validator, then it accesses the database. It stinks! I should probably get the record with the manager, but then I have to validate that the record was returned and that the data in it is valid in the context of my DTO. What do I do?

Manager and Validator classes

OK, so I can split the validation and operational flows in methods that will live in their respective classes. In this scenario a validator checks the record id is not malformed, a manager attempts to get the record, then the validator executes another method to check the record exists and conforms to the expectations, and so on. Problem solved, right? But no. That means I have to pass the record to the validating method, or any number of records that I need to perform the validation. For example I want to check a large chain of records that need to be validated based on conditions in the DTO. I could get the list of all records, pass them to the validator and then check if they exist, but what if the database is very large?

Manager methods that help validation and Validator

Wait, I can be smart about it. I know that essentially I want to get a list of records then validate something. Can't I just create a specific method in the manager that gets only the records involved in validation? Just do manager.GetRelatedRecords(dto.Id) to get a list of records from the database, then pass them as parameters to the validator methods. Fixed it, right? Nope. What if there is a breaking condition that is related to validation? The original linear method would just go through the steps and exit when finished. It wouldn't get a bunch of unnecessary records then fail at the first later on. And there is even a worse problem: what if while I was busy getting the records and preparing for validation the records have changed? I am basically introducing a short lived cache, with all the problems arising from it, like concurrency and invalidation.


Hey, I can just new TransactionScope the shit out of it, right? Do steps of Validate, GetMoreData and repeat all inside a transaction. Anything fails, just rollback, what is the big deal? Well, concurrent access being slowed or deadlocks would be problematic, but more than that I am terrified of the result. I started with a linear flow in a single method and now I have two classes, each with a lot of methods which get more and more parameters as I move on: first I validate the DTO values, then a record in relation to the DTO, then two records in relation to each other and the DTO and so on. All these methods are being executed inside a transaction using a local ad-hoc memory cache to hold all the data I presume I will need. The manager methods are either using a big list of parameters themselves or repeatedly instantiating the same providers for the data they get. It's a lot more complex than the original, working design. It's also duplicated flow, as it needs to at least partially go through the data to populate what I need, then it goes through the same flow during the validation.


Ha! I know! Instead of passing an increasing number of parameters to validation methods, create a single context object in which I just populate properties as I go. No more mega methods. Anything can be solved by adding another layer of indirection, correct? Well, now I have three classes, not two, with the context class practically constituting a replacement of the local scope in the original method. The validation methods are now completely obscure unless you look inside them: they all receive the DTO and the context class. Who knows which properties in the context are being used and how?

Interfaces and Flow

Ok, maybe I rushed into things. Sometimes several layers of indirection are required to solve a single problem. In this case I will create an interface with the properties and methods used by every validation method. So the name validation will look like ValidateName(MyDTO dto, INameContext nameContext), the graph validation will look like ValidateGraph(MyDTO dto, IGraphStructure graph) and my context class will implement INameContext and IGraphStructure, even when the two interfaces have common members. I will do the same with the manager class, which will implement the interfaces required to populate the specific context interfaces.

I am not kidding!

This isn't one of those "how the junior and the senior write the same code" jokes. I actually don't know what to do. The most "elegant" solution turned a working method from an API class into three classes, transactions, a dozen interfaces and, best of all, still keeping the entire logical flow in the original method. You know how when a code block becomes too complex it needs to be split into several short methods, right? Well I feel like in this case I somehow managed to split each line in the original block into several methods. I can see the Medium article title now: "If your method has one line of code, it's too long!".

Unit Tests

Any software developer worth his salt will write unit tests, especially for a code such as this. That means any large validation method will need to be split just in order to not increase unit test size exponentially. Can you imagine writing unit tests for the methods that use the huge blob-like context class?

Cry for help

So help me out here, is there an general, elegant but simple solution to API separation of concerns in relation to validation?

Sunday, January 01, 2017

What I've learned from a year on social media

Last year I wrote a blog post detailing my experience with social media after four months. This is the followup, after I've had a whole year to take advantage of these tools.

Social Media - what is it?

To me social media means the big two: Facebook and Twitter. I still have no idea what Instagram is and I don't really consider LinkedIn as social media. And Google+ is not worth mentioning. I know there are a lot of other social sites, but I ignored completely photo and video platforms - since I rarely express myself visually, and I've tried some technical platforms like StackOverflow, HackerRank or GitHub, but again didn't consider that "social media". Probably I should, since I love software development and having people to share this with would truly be a social experience for me, but I started this experiment with focus on general social interaction. Also... Slack... what the hell is that?

What I used social for

In the previous post I said that I am using Blogger to express myself, as I have done for more than a decade, and use some tool to automatically share this on Facebook and Twitter. Not surprisingly, very little people were engaged by this method of communication. It works better than RSS feeds, that's for sure, but most of the time people on social media (including myself) want to shut off their brain and read something light, not my crazy ramblings or technical posts. I've created a Facebook page for my blog, so people can use that as an entry point, if they want, but all the posts there are shares from Blogger.

I was saying that I was pleasantly surprised by Twitter and the quality of content there and less enthusiastic about Facebook. However, Twitter changed some things lately, mostly allowing videos, images and smileys (what you, young folks, call emoticons - or is it emoji?) to take less space. The effect is that there are a lot more visual opinions (let's call them that) on Twitter and thus becoming harder and harder to read. Also the amount of postings there is overwhelming. I tried to look for some tools to limit the number of tweets or organizing them somehow, but unfortunately I found none that did what I envisioned. The result is that occasionally - every week or so - I scroll through Twitter until I get tired and put links in my to read list, but most of the time I only cover a day or two of content.

I found that whenever I see something that I believe is worth sharing I put it on Facebook, rather than Twitter, mostly because I have few friends on Twitter and there is that 140 character limitation. However, most of the time I just post the link anyway and maybe say a few words. I wonder if that short circuits me thinking about the subject and then writing my opinion on it, as I am doing with this blog, but most likely I would rather not share than write so much every time, so I don't know if the occasional Facebook posts are taking away Blogger posts. I will actively try to not make it the case. I noticed, though, that people that like my Tweets are often not in my friends list, so I guess it's more general an audience. That being said, all my Facebook posts are fully public, anyway.

Speaking of Facebook, when I compile my weekly reading list I also scroll down through the Facebook wall, but even with my extension to filter posts based on own content and less images, videos and likes, I still get bored rather quickly. Sometimes the jokes are funny or the pictures interesting, but I am not really a Facebook reader. Lately I have been unfollowing people in order to keep a modicum of content curation on my wall. I was really disappointed by the events system, as well. A lot of people just mark all events they could possible go to with 'Interested' and then they never go. Also the events that appear on Facebook feel like complete bullshit most of the time anyway. The ones that I would have liked to attend either don't even appear or they are so niche that I never hear about them until it is too late.

One thing that I thought I would use Facebook for was the messenger app. And I do use it, but very rarely. In the Yahoo Messenger days I would chat a lot with people. Somehow all that became frivolous, not only for me, but other people as well. Now I see young people just getting a lot of notifications and ignoring them. So what's the point, anyway?

And speaking of... God, notifications are annoying. Everything wants to notify you of the very important thing that happened on it. It does so by blinking, beeping, animating or any other histrionic method of getting your attention. They do it incessantly until I stop caring. Notify away, I will ignore you.

What I will be using social for

I don't foresee any change in the future other than maybe using less social media altogether. I am half convinced that I should try to develop meaningful human relationships, at least as another experiment. Clearly social media does NOT connect people on a personal level at all. I've heard about these young kids that share everything they do on social media. Maybe they do, but I am not following them. To me that's another network altogether. The occasional curiosity to see what is "trending" or "popular" disgusts me every single time. The things my friends share are not truly representative of them. And if I make the first step and post some weird feeling or situation I am in, I mostly get no reaction. People avoid negative emotions unless they are manic: hate, anger, disgust take first stage while depressive thoughts, sadness or desperation are avoided. Same for positive emotions, by the way, when people are extra happy about having a child or something like that. Just mildly enjoying something and feeling good about oneself is generally ignored.


I am not going to commit social media suicide or anything, but I concluded that I want to know what people think, rather than what people feel, and social media is used more for the latter. Therefore my commitment to online electronic expression is not going to increase towards Facebook and Twitter. As always, I do hope I will blog more meaningful posts. Wish me luck!

End of 2016

This is how 2016 ends, not with a bang but a whimper. After a relatively calm Christmas followed an eventless New Year celebration. Part of me was lamenting the oldness of it all: two people alone on New Year's Eve, drinking gin tonic and campari cola and sitting at their respective electronic devices. The other part of me was happy that no one bothers me, that I don't have to pretend to enjoy loud noises and strong lights and fake emotions. Was it a nice end of year or just another win for my comfort zone?

It was a strangely quiet year for me, as well. Most of it I was in a sabbatical during which I did nothing of note and the last part was about getting hired and getting acquainted with my new place of work, which was fine. No real drama, no dead relatives I cared about, no fuss. I wrote my code, I watched my TV series, I read my tech news. It was more than quiet, it was boring.

Meanwhile, though, everybody else was going crazy: beloved celebrities died, elections went to hell just about everywhere, terror scares, immigration issues, civil wars, cyber wars, cold wars, global warming and so on and so on. Weird contrast, isn't it? Part of me laments I am growing apart from the world and people, the other part enjoys the hell out of it. Is that what growing old is? Just getting off the train and raising a middle finger?

So what about my New Year resolutions? I have none. I have some hopes, but resolutions? Nah! I am too comfortable ignoring everything that matters. If I go down that road, defining priorities, finding solutions to get what I want, getting rid of what I don't want, setting up goals, then I have to change my entire life. I have to start over. I have to make an effort, hurt people, push the drama button. Who needs that? I do have the heart of a child. I keep it in the freezer, never to be thawed.