Wednesday, June 7, 2017

No ifs, no nulls

I have always been a strong proponent of clean code that's written with maintainability in mind. It's my firm opinion that performance should be addressed with proper architecture. In most applications, code trickery contributes very little to overall performance. What exactly causes code to be less or more maintainable? Simplicity and clear semantics are two main important things that contribute to this aspect.

What makes the code simpler to understand? Code with many execution branches is harder to understand and to test. Personally, I dislike deep nested if-then-else conditions. Even having overly complicated boolean expressions as part of if conditions, makes the code harder to understand. Straight-line code without explicit branches and loops would be ideal. But can non-trivial code be written like this? It's quite possible.

Keeping the semantics completely unambiguous requires some thinking. In last few years, I have also developed an acute case of "null-phobia". In Java (and many other languages), usage of "null" can be problematic. Especially while describing semantics. What does a return value of null mean? Is something not present, or is present and empty, or did something go wrong? There are ways to deal with this dilemma. Documentation, exceptions are part of the solution. Now Java 8 has borrowed the Optional from other languages that makes it very easy to deal with this.

In this post, I want to explain one simple measure that can be employed to eliminate some branching and null-checks.

Consider a common service layer pattern. The service layer needs to provide an API to read the business objects from the database. The database layer provides a similar API to return the record from the database associated with the id given.

In the above only the code relevant to this discussion is shown.

Even with this simple structure, it is clear that the usage of null is problematic. Each layer needs to check nulls, and forgetting to do that and passing the result around would generate a NullPointerException in some other part of the code. The programmer must read the documentation in order to understand that null values might be returned, there is no help from the compiler. These are some of the reasons for potential bugs in future.

It's very easy to replace this with the new Optional and remove any ambiguity, and provide a very clear semantics.

That's much better than using nulls as a return value. With the Optional as a return value, it provides a clear signal to the users of the method that they have to check for the existence of the actual result. The compiler enforces the usage of an explicit get() call, and most likely your IDE will warn you if use the get() without the isPresent() method. Now it takes willful ignorance to cause a NullPointerException. That's a win.

Of course the code as written, is nothing but a glorified null-check. The Java 8 Optional allows you to refine the code even further by using the streamlike fluent API. The Optional has much more than just isPresent() and get().

The Optional::map() method is smart. It can be used to convert Optional of one type to another. The isPresent() check is handled for you. It accepts a lambda which will be executed only if the Optional is not empty.

Of course, with a simple lambda like that it can be even further simplified using the new method references.

This is not code trickery at all. This is the correct usage of Optional. The unfamiliarity of the lambdas and the new Java 8 APIs will eventually go away.

This was a small snippet to convey the idea. I strongly argue that such concise straight line code is much easier to understand. It's also extremely easy to maintain due to lack of branching, and lack of the need to keep performing null-checks. To be precise, the branching and null checks have not disappeared, but they have been moved from our code to the JDK library code. That's still a huge win for maintainability.

I am also aware that lambdas, if not used in such concise manner, suffer from the same issues of anonymous classes. My rule of thumb is, lambdas should be simple one-liners, just a method call with descriptive name. Nothing more.

There are many such simple measures that can be employed to write code that has minimal branching, and clear semantics. More in future posts.

Friday, May 12, 2017

Song number 4 : Gaate Kon Manaat

Presenting song number 4

On behalf of the entire team, I am very happy to present the latest song. It's an old poem, written by late Vaa. Raa. Kaant. I liked it because it's simple, lyrical and at the same time meaningful. I am sure all artists have felt this poem in their heart, and the question it asks. Who is really driving the inspirations? The poem doesn't answer that question. Instead it reminds the artists, that they are not really creating the art, rather it's the other way around. It's the art that's shaping them. I believe this is true for all art forms.

I am very fortunate to have received support from very talented artists to shape this song :-)

Aparna Nimkar lent her sweet, melodious voice and sung this beautifully. After composing, I knew I wanted her to sing this song, and I am so glad that it materialized. Her voice gives a nice, pleasant and calming effect to this song.

The rhythm is excellently handled by the duo, Amey Thakur-Desai and Hanumant Rawade. This is the third time, Ameya has helped me with the rhythm.

The superb flute interludes are thanks to Pranav Haridas and guitar is played by Amogh Dandekar.

Finally, the music arrangement, mixing and mastering is done by Aniket Damale. His perfect arrangement is soothing and blends seamlessly with the main melody. Without his enthusiastic support, the song wouldn’t be this good.

I have kept the melody in the contours of Raag Jaunpuri. Hope you enjoy the song as much as we all enjoyed making it. If you like it, please support it by sharing. Thank you!

गाते कोण मनात, कळेना, गाते कोण मनात ?

जरी शतावधि कविता लिहिल्या
शंभरदा वाचिल्या गायिल्या
शब्द कुणाचा, सूर कुणाचा, अजुनि मला अज्ञात

पुशिले त्याचे नाव फुलाला,
गाव तयाचे उषे निशेला
मिचकावुनि कुणि डोळा जातो, काळ्याभोर जळात

अभिमानाने कधी दाटता
“रचिले मी हे गाणे” म्हणता
“गीतच रचिते नित्य तुला रे” फुटे शब्द ह्रदयात

My feeble attempt at translation ...

कौन गाता है मेरे मन में, पता नहीं, कौन गाता है मेरे मन में

सैकड़ों कविताऐं लिखी, सौ बार गायी, पढ़ी
है शब्द किसके, सुर किसके - हूँ इससे अबतक अंजान मैं

पूछा उसका नाम फूलोंसे, पता सबा से, रात से
मटका कर आँखे बस चला जाता है कोई काले गहरे पानी में

अभिमान से कभी कहुँ, “गीत लिखा यह मैंने”
“गीत ही लिखते है नित तुम्हे”, उठता है जवाब, अंदर दिल में

Saturday, March 4, 2017

Marathi Rubaai - 3

Rubaai number 3. With Hindi translation.

#रुबाई #काहीतरी #उगाचच

होते कधी साजिरे, चित्र झाले जुने
गडद गडद रंग विरले, पृष्ठ फाटले
उरली फक्त माझी पुसटशी छबी
आजूबाजूचे सारे, सारे सारे मिटले

थी कभी रंगीन, हाँ, थी कभी सुहानी
मिट गए रंग, हो गयी तस्वीर पुरानी
रह गयी सिर्फ मेरी धुंधलीसी छवि
न बची और कोई, कोई भी निशानी

Sunday, February 26, 2017


Review : Westworld
Aired On : HBO (2016-)
My Rating : 7 out of 10

Just like it happened with Boardwalk Empire, the promos of Westworld ensured that I was going to watch the series. The reason in both cases being the association of big names. When you see Anthony Hopkins, Jeffrey Wright, Ed Harris in the promo, it’s bound to generate interest.

Westworld is based on Michael Crichton’s 1973 Sci-Fi movie of the same name which I have not watched. This is a very hi-tech theme park of sorts. There are no rides, there are stories. Stories in which lifelike robots with very advanced AI play the same role, every day. The visitors (or guests) in the park play the role of super humans - as in - they can do whatever they want with these robots. Whatever, as you can expect, happens to be nothing but mayhem, sex, and some darker fantasies they may have. The robots are programmed to be unable to hurt. Their weapons have no effect on humans, but humans can kill them at ease. The premise being, these are robots without feelings, emotions or even life. After every “death”, they are repaired in the night, to be put in the same cruel loop all over again.

At least that’s how it was set up, till the creator, founder and the almost-God of the park, Dr. Robert Ford (Anthony Hopkins) decides to tweak the algorithm to make the robots even more human like. The results are less deterministic, and the robots (or hosts, as they are called in the series) start acting differently than what was planned. Some of them start to retain memories, and things get interesting.

In the first half of the season, the series focuses almost exclusively on the mayhem part. We get to see how the park works to some extent, some corporate politics, some operational aspects. It is slow, a bit confusing and definitely repetitive. What held my interest to keep me going was the visual aspect. It’s stunningly beautiful - both the world inhabited by robots, as well as the inside where humans recide. We don’t get to see anything beyond these boundaries. It’s set in some future, but no hint is given as to how far. And yes, there is standard hollywood tech mumbo jumbo that shouldn’t be paid much attention to.

Fortunately, the series takes interesting turns in the later half. Then it starts to become a puzzle that seems worth solving. Actually, a multi-layered, multi-dimensional puzzle. It can get even more confusing, but it’s also gripping. You keep wanting to know more. Eventually by the end you will know more. And I think you will be surprised. And satisfied. That’s the important part. The answers to the puzzles are surprising and satisfying. 

In addition to being a Sci-Fi mystery, the series also tries to set up some deeper philosophical questions. I wouldn’t take them too seriously. Most Sci-Fi requires some leaps of faith to believe that the technology shown can actually come to exist. That’s fine. But here, since there are robots, and they are human like and they are developing memory - the question of consciousness and how it begins, serves as the device that the series uses to stand out. It works to keep things interesting, but I doubt if this season would ever spawn the pseudo- philosophical discussion like The Matrix trilogy did. That’s OK. 

As you can imagine, this is not a character driven drama. You will know precious little about the human characters. The robots are more interesting, but they are also stuck in a loop. HBO is not expecting us to watch it for intricate relationships. It’s a Sci-Fi mystery, no other pretensions. The stellar cast helps tremendously. Apart from their acting, there is nothing to firmly root the characters. Every one is brilliant. Not a surprise considering who they are.

It’s a great combination. Perfect acting, unusual concept, interesting plot surprises, stunning visuals, capable direction and dash of philosophy. The script was a bit confusing to me, but most of the confusion was cleared up by the end.

This is not a great series, but a very good series. It’s also different and gripping in the second half, hence totally watchable. I definitely recommend it. It’a correctly rated TV-MA and is not for kids.

Saturday, February 4, 2017

Big Little Lies

Book Review : Big Little Lies
Author : Liane Moriarty
My Rating : 4 out of 5 stars

I will be honest about this. This is not a book that I would have read at all. I didn’t even expect to like it. This book is simply not my type. HBO has been advertising about a series based on this book that stars Nicole Kidman, Reese Witherspoon and Shailene Woodley. With that kind of cast, I know I am going to watch it. In my opinion a book should be read before watching the screen adaptation. So I read it, and I was surprised to find myself liking it.

The story has three main characters, all women, living in a beach town in Australia and who have kids going to the same kindergarten class. In the very beginning of the book, the reader is told that a death happened during a function organized by the school, and most likely it was a murder. Who died and how is not told till the very end. The story starts a few months before the event. Jane, a single mother movies to the small beach town. On the very first day, she meets Madeline, who also was a single mother once. Madeline, and her friend Celeste, become Jane’s support system. She needs one, as the Kindergarten Mom Politics is quite strong in that town. As the story progresses, we learn a lot of details about these three characters and a bit about men in their lives. Eventually, the fateful night arrives and all the threads and sub-plots converge.

The double mystery, who dies and who did it, is smartly handled. We don’t even know who dies till the very end. That keeps the reader guessing, at least till the half-point. It’s a bit easy to narrow-down the options of who might die, but how remains a nice mystery. But this is not just a mystery book. The characters are developed nicely, and they are not single dimensional. The dialogues are smart, and the pacing is smooth.

The book also touches on many other aspects - domestic abuse, self-esteem, petty politics. It is also a satire on current parenting style. The school politics is completely far-fetched. I just don’t buy it. That’s one big negative. There are other small defects, like one character using Google to discover a simple fact, while the character which is most affected doesn’t. Not very believable. But if that character had used Google, the whole story wouldn’t have been possible. At the end of each chapter, there are dialogues from secondary characters about the investigation, that are cliched to the extreme. Finally, the male characters are only mentioned in passing, most of the time, and strictly from a woman’s point of view.

Leaving the defects aside, the book does a fantastic job of achieving the right balance between all the elements it uses. The character portrayal, shining light on domestic abuse, satire on modern parenting and of course the mystery. This is really the strength of the book. This balance is what keeps the book interesting, and makes us invest our time in it.

It’s a good read, not literary, but nice for relaxing lazy times. I am giving my recommendation, but I will admit again. It’s not a book that I would have read, even after reading a review like this, my own review. Because, I rarely feel satisfied after reading fiction, and on top of that, this is absolutely female centric. It still kept me glued and made me turn pages. Now, I look forward to the HBO series. 

Saturday, January 14, 2017

Marathi Rubaai - 2

Rubaai number 2. This time with translations in Hindi as well as English.

#रुबाई #काहीतरी #उगाचच

खिन्न लाटा, खिन्न किनारा
मावळतीचा खिन्न पसारा
त्यासमोर हा एकटाच मी
छेडित बसलो तुटल्या तारा

मायूस लहरें, मायूस किनारें
मायूस शाम के मंज़र सारे
बैठ के तन्हा छेड़ रहा हूँ
साज़ पुराना, टूटी तारें

gloomy ocean, gloomy shore,
as the sun sets, gloom galore
sitting alone, I keep strumming
broken chords, songs of yore

Rubaai 1

Saturday, January 7, 2017


Movie Review : Dangal
Released : 2016
Language : Hindi
Director : Nitesh Tiwari
Genre : Biography
Starring :  Aamir Khan, Sakshi Tanwar, Fatima Sana Shaikh, Sanya Malhotra, Aparshakti Khurana, Zaira Wasim, Suhani Bhatnagar
My Rating : 9 out of 10

Movies about Sports pose interesting challenges. They have to do a balancing act between focusing on the sport and focusing on the characters. The actors have to take on intensive efforts to appear believable. The drama around the sporting scenes has to be exciting, but should not feel far fetched. Last but not the least, if the ending is predictable, the movie has to ensure that the viewers stay engaged till the end.

Dangal wrestles these challenges (pun intended) and scores a gold medal. It walks the sport movie tightrope without ever losing its balance. Its focus on wrestling is unwavering, but it also manages to pack a social message. While taking us along on a near straight-line journey of Geeta Phogat towards the Gold Medal, it still manages to make us visit the special bonds between all the characters. It ignites nationalism without being melodramatic. Most importantly, it keeps us on the edge of our seat even when there is no real villain and we know how it’s going to end. Yes, it fabricates an exaggerated fictionalized ending for the cinematic effect, but doesn’t push it beyond the borders of believability.

This success is a result of the entire team. The director Nilesh Tiwari never lets the movie go out of his control. The actors, all of them, from Aamir Khan to the kid actors, have put in phenomenal efforts in their roles as wrestlers. The music sticks to taking on a just a supportive role. The picturization of the wrestling scenes is undoubtedly the highlight of the movie. They can be described with one word - electrifying. That’s because of efforts of actors, wrestling consultants, director - and the camera crew and the editors. In presenting such high octane sports scenes, so much depends on camera angles and skillful editing. Hats off to the technical crew.

As must be obvious, I really enjoyed this latest Aamir Khan movie. He is one of the rare Bollywood stars whose movies I look forward too. I have been very happy with hist last few movies, such as PK, or 3 Idiots. Only Dhoom 3 was a huge disappointment for me.

Dangal is another feather in the cap for Amir Khan. I still remember watching him sing “Papa kehte hai”. This journey from a chocolate hero to a super serious dedicated actor has been a delight to witness. Here he plays the middle aged humorless father perfectly. A lot has been and will be talked about his physical transformation. I was equally impressed by his acting effort. The way he talks, the way he sits on the scooter, the way he runs at the end of the movie. Everything is perfect. This is perhaps his best performance. 

He presents the real life story of wrestling champion Mahavir Singh Phogat and his efforts to earn a gold medal for India via his daughters. This is a fairly recent story, with both the daughters still active as athletes. It’s a story of dedication, hard work and courage to fight against the social norms.

It’s impossible to talk about this movie without talking about the acting performance of the two child actresses. They are adorable, and admirable for the amount of effort they put in. Both  Fatima Sana Shaikh and Sanya Malhotra have done justice to their roles as elder Geeta and Babita. Even the unenviable role of the cousin is played superbly by Aparshakti Khurana.

I absolutely recommend this movie. It’s fast, does not extend longer than needed and safe for kids. Actually, it’s a great family movie. Do not miss this one.

Related Posts Plugin for WordPress, Blogger...