Feb 02 2020

January Beer

Category: MiscellaneousIuliana @ 22:57

It has been a month since the beer button was added to this site. And the harvest is upon us.

Thank you for the beer, Juan!


Jan 31 2020

When I start my day like this …

Category: TechnicalIuliana @ 11:43

… it just makes all the sleepless nights that went into that book worth it.

Thank you for your feeback, Peter!


Jan 23 2020

One misconception about Java’s Optional

Category: TechnicalIuliana @ 15:26

Yes, my dear readers, this is a technical post. It’s not going to rock your world, it’s not going to give you an insight into this language that you’ve never had before, it will just make you think twice before writing code. This being said, let’s dig in.

When java.util.Optional was introduced in JDK 8, Java developers rejoiced because they could finally avoid the most common and hated exception in the language the NullPointerException. Just between you and me, I think it’s  useful to be able to have nulls, but using them correctly does require a certain mastery of programming in Java.

Before reading my article, I would recomment reading this one first. In case you do not have the time to, here’s a summary.

java.util.Optional is awesome because:

  1. NullPointerException is prevented at runtime.
  2. Null value checking is not required in the application.
  3. Boilerplate code is not required.
  4. It’s easy to develop clean and neat APIs.

I would like to attract your attention to number three in that list: Boilerplate code is not required. I would have formulated it as Writing boilerplate code can be avoided. But, really … can we avoid writing boileplate code using Optional? It depends. Certainly not for the example in that entry.

Let’s start with the setup. We need an Employee class that has two fields: id and name, both String values.

// Employee.java
package com.ic.one;

public class Employee {
    private String name;
    private String id;

    //constructor, setters and getters
    // or just use Lombok, whatever floats your boat
}

We also need a main class, that should contain two methods, one returning an Employee, one returning an Optional that will be used in the code that will be written to check exactly how much boilerplate can be avoided.

//IfPresentOrElse.java 
package com.ic.one;

import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;

public class IfPresentOrElse {
    public static void main(String[] args) {
        // here we'can call our special methods, to make sure the code actually runs as expected
    }

    public static Employee findEmployee(String id) {
        return id.equals("1234") ? new Employee("Gigi Pedala","1234"): null;
    }

    public static Optional<Employee> findOptional(String id) {
        return id.equals("1234") ? Optional.of(new Employee("Gigi Pedala","1234")): Optional.empty();
    }
}

Now that we have our methods to retrieve an Employee, or an optional, let’s do some comparisons.
Up until JDK 8, you could write something like this:

//IfPresentOrElse.java 
...
    // JDK 8 without Optional, version one
    public static void jdk8SimpleVersionOne (){
        Employee employee =   findEmployee("1234");
        if( employee != null) {
            System.out.println("Employee name is " + employee.getName());
        }
    }
...

The previous code is the most simple thing you can do when querying for an Employee, if an instance is returned, you print its name. Starting with JDK 8, the same code can make use of the Optional type to avoid returning a null value.

//IfPresentOrElse.java 
...
    // JDK 8 with Optional, version one
    public static void jdk8SimpleWithOptionalVersionOne (){
        Optional<Employee> optional = findOptional("1234");
        optional.ifPresent(employee -> System.out.println("Employee name is " + employee.getName()));
    }
...

It is said on this big bubble called the Java development world, that Optional spares you the pain of doing a null check. Yes, it’s true. But in regards to avoiding boileplate code, allow me to be the devil’s advocate here. Replacing an if statement with an ifPresent call and a Lambda expression, it’s just replacing an old-style boilerplate code with new-style boileplate code. The new boileplate code though, it does look prettyier and smarter though, right?

Anyway, let’s complicate the previous example, and introduce a message to be written when there is no Employee with id 1234 found, in other words, let’s see what can we do with an if-else statement.

//IfPresentOrElse.java 
...
    // JDK 8 without Optional, version one
    public static void jdk8ComplexVersionOne (){
        Employee employee =   findEmployee("1234");
        if( employee != null) {
            System.out.println("Employee name is " + employee.getName());
        } else {
            System.out.println("No employee with id 1234" );
        }
    }
...

What will Optional do for this scenario? Well, as it turns out …

//IfPresentOrElse.java 
...
    // JDK 8 with Optional, version one
    public static void jdk8ComplexWithOptionalVersionOne (){
        Optional<Employee> optional = findOptional("1234");
        if(optional.isPresent()) {
            System.out.println("Employee name is " + optional.get().getName());
        } else {
            System.out.println("No employee with id 1234" );
        }
    }
...

… not much. Boilerplate is still there, and the ifPresent function is no longer an option unless we want to write a monstrosity like this:

//IfPresentOrElse.java 
...
    // JDK 8 with Optional, monstrosity
    public static void jdk8ComplexWithOptionalMonstrosity (){
        Optional<Employee> optional = findOptional("1234");
        optional.ifPresent(employee -> System.out.println("Employee name is " + employee.getName()));
        if(optional.isEmpty()) {
            System.out.println("No employee with id 1234" );
        }
    }
...

Let’s try to simplify the no-Optional example even more, and try to have a single System.out.println call, by updating a local variale named message depending on the situation.(Employee found or not – that is the situation :D ). The code can be written like this:

//IfPresentOrElse.java 
...
    // JDK 8 without Optional, version two
    public static void jdk8ComplexVersionTwo (){
        Employee employee =   findEmployee("1234");
        String message = "No employee with id 1234";
        if( employee != null) {
            message = "Employee name is " + employee.getName();
        }
        System.out.println(message);
    }
...

Optional will not help much with this scenario either.

//IfPresentOrElse.java 
...
    // JDK 8 with Optional, version two
    public static void jdk8ComplexWithOptionalVersionTwo (){
        Optional<Employee> optional = findOptional("1234");
        String message = "No employee with id 1234";
        if(optional.isPresent()) {
            message = "Employee name is " + optional.get().getName();
        }
        System.out.println(message);
    }
...

So, what is there to do? The only thing that makes things a little bit better here is the JDK9 ifPresentOrElse method, added to the Optional class. This method is quite smart, because it allows us to define an action that does not involve the value of Optional, for cases where there isn’t one.

//IfPresentOrElse.java 
...
    // JDK 9 with Optional, version one
    public static void jdk9ComplexWithOptionalVersionOne (){
        Optional<Employee> optional = findOptional("1234");
        optional.ifPresentOrElse(
                (employee) -> System.out.println("Employee name is " + employee.getName()),
                () -> System.out.println("No employee with id 1234" )
        );
    }
...

It does look better, but news flash, the boiler plate just moved now to the horizontal. So, what if we really want to have a single System.out.println call? Well… things become even more convoluted, because variables used in Lambda expressions should be final or effectively final, so we need to use an atomic reference for our message. And this leads to the previous example being written like this:

//IfPresentOrElse.java 
...
    // JDK 9 with Optional, version two
    public static void jdk9ComplexWithOptionalVersionTwo (){
        Optional<Employee> optional = findOptional("1234");
        AtomicReference<String> message = null;
        optional.ifPresentOrElse(
                (employee) -> message.set("Employee name is " + employee.getName()),
                () -> message.set("No employee with id 1234" )
        );
        System.out.println(message.get());
    }
...

Damn, there is no way to get rid of this boileplate code is it?

The truth is, in programming there will always be statements and constructions that will need to be used more than others. These are fundamental parts that make up a program, you cannot avoid using them. And there is a limit to how much they can be reduced in size that is specific to that language. It’s like your daily commute. Sure, there are multiple routes and you can walk, or cycle, or drive, or take the train, but depending your situation and your other plans for the day, there is a way to commute that is more suitable than the others. And in the end there is a limited list of ways to commute, and you will end up using them over and over again, until you quit your job and move to Ibiza.

All of the examples above can be compiled and run with JDK 9-14. And they all do the same thing. I won’t touch the subject of performance, because an investigation into which statement is quicker than the other is overkill for me. There is not a best way to do it. It’s just a matter of preference and keeping the code readable.

I’m not particularly fond of any of those, and I decide the way I write my code depending on the situation.

And since we talked about the limit of reducing boilerplate code that is specific to the language, do you want to see how the same things can be done in Kotlin?

It was a rethorical question, I know you do. :D

//IfPresentOrElse.kt 
...
package com.ic.one

data class  Employee(val name: String, val id: String)

fun main() {
    // 2
    println("Employee name is ${findEmployee("1234")?.name}")

    // 3
    val  employee = findEmployee("1234")
    employee?.let { println("Employee name is ${it.name}") }

    // 4
    println (if ( employee != null ) "Employee name is ${employee.name}" else "No employee with id 1234")
}

// 1
fun findEmployee(id: String): Employee? =  if (id == "1234") Employee("Gigi Pedala","1234") else null
...

So, what happens in there? Well… let me explain each numbered section in the previous code snippet:

  1. The findEmployee function returns an Employee instance or null. The compiler knows that because the return type of the function which is Employee?. That question mark is not a mistake, is how we specify in Kotlin that a function can return a null value.
  2. That function can be called by a println function (the equivalent of the Java’s System.out.println) and here’s the fun part: the question mark can be used to test the returned value. That is why the question mark is called the safe call operator in Kotlin. If it is null, the name property won’t be accessed, instead null is returned, which in the case of line 2, will cause the message Employee name is null to be printed in the console, if no employee with id “1234” exists.
  3. NullPointerException avoided, but the behaviour is not what we actually want. Because we do not want to print anything in case there is no Employee in this case. Well, that can be achieved by using the safe call operator and the let inline function. Combining these two results in a function being called only for values that are not null.
  4. This section has the same effect as a if-else statement with a different message being printed for each scenario.

Side note: Yes, Kotlin supports placeholders too. You have no idea how much I hate writing System.out.println(“Employee name is ” + employee.getName()) or System.out.println(“Employee name is “.concat(employee.getName())).

I hope this proves my point. Boilerplate cannot be avoided, but it can be reduced within the limits of the language. And Kotlin does allow for a better job to be done than Java. And it doesn’t require an Optional type for it.

I know this is not an advanced technical entry, I know it seems to be no other conclusion than: do it as you feel more comfortable doing it.

But, I know for sure  somebody will find this entry useful. You are welcome, my darlings!

Stay safe, stay happy!

Tags: , , ,


Jan 20 2020

The bad one

Category: MiscellaneousIuliana @ 12:15

As a social animal I am programmed to be longing and actively looking for companionship. But at the same time it angers me that it is frowned upon being totally inert and doing whatever the hell you want with your life without involving another.

As a bonus I’m in my late thirty’s which makes dating terrifying, because I know to much. I know about the billion ways in which relationships can go wrong. Also I am not worried only about me getting hurt, but I am also worried about hurting someone, because I do not want to feel guilty about it. Because felling guilty, feeling ashamed of the consequences of my actions keeps me up at night. And I need my sleep to keep functioning normally in this society.

I “fell in love”-or-whatever-that-means the previous year and it was like getting out in front of my house to pick up a package and having a piano dropped on me. Yes. Just like in a cartoon, but the pain was real.

I think I “fell in love” or “got infatuated” or just had a crush, no idea how to name it in 2016. It felt as falling in the shower. Here you are being comfortable, in a cozy familiar place and then bam, you are down on the floor in an uncomfortable position and some things sorta hurt. I felt like I was losing control of my life, making decisions that I wouldn’t have done under normal circumstances. Like now, then I was writing one of my technical books. I lost entire nights chatting with him on facebook messenger, going on late night drives and I’ve even designed the itinerary of my US vacation so I could see him. And I did not mind doing all that, but you know what hurt the most? He wasn’t making the same effort for me. At some point, after other sleepless nights asking myself where was that going, the rational part of me won and I stopped making decisions as to favour my relationship with him. Because he obviously wasn’t doing it. It takes two knowledgeable and in sync partners to tango. We were none of those things.

I was wondering whether some people simply were meant to be completely alone, to be actual islands unto themselves.

Most look for the partner that completes them, we even have a legend about people being wonderful creatures with 2 heads, 4 arms and legs and how they were split in two by an evil envious god and now they spend their life looking for their half.

But I do not consider myself a half-person; actually this idea terrifies me. Because if I’m missing something, I’ll be using another person to get what I need. And what if I cannot offer them what they need? I do not want to be the bad one. The one that took advantage of the feelings of another person. I do not want the guilt that comes it it. Because guilt leads to insomnia. Insomnia leads to bad decision making.

Stay safe, stay happy!


Jan 16 2020

Time for atonement

Category: MiscellaneousIuliana @ 0:45

Although I am proud of myself for finally being able to keep my assumptions to my self, this doesn’t apply to the internet. Or at least not to this blog. I still have to learn when to wait and digest things before posting a reply to a comment.

On this blog I am the author. I speak to my readers and I use the second tense. When I read my own posts my perspective is that of the author. And because I am the author and those are my opinions I don’t feel offended by them. How could I be, I am subjective right?

When reading the comments my perspective changes. I am the reader and my comments are directed to me.

Just look at this exchange:

This is a series of comments at my previous entry. It took me more than twenty four hours to realize that my reader Cip indeed did not meant what I thought he did. Because his perspective was that of an author too. My perspective was that of the reader of his comment and I felt like the target of that “you”.  And because of my own frustration of not having enough time to read as much as I wish, I felt attacked and reacted like that.

Please notice my reply full of malice. I am fully ashamed of that reply, but I will leave it there as a reminder to do better. So dear Cip, I am truly sorry for snapping at you.

I’ve always believed that we view the world the way we are, not the way it is. And on a smaller scale, most times, we treat people the way we are, not the way they are. And yesterday I’ve been an asshole. But there is something that is important in my comment.

You shouldn’t give a fuck about people assumptions. Thier assumptions are rooted into who they are, not into who you are. Assumptions are conclusions drawn with a lot of missing context. So do not let them affect you too much.

Stay safe, stay happy!


Jan 14 2020

On being able to shut up

Category: MiscellaneousIuliana @ 23:47

Depending on how we are raised, some of us are talkers, some of us are taciturn, some seem to ability to recognize perfectly the moment when they should talk, or they should shut up.

I’ve struggled all my life with my  inability to shut up. I’m not even sure how I became like this. Maybe I was thirsty for attention, maybe I just hated that people kept think and lied around me all the time when I was a kid during the communist time and my mother and father never bother to explain to me why. They just told me to shut up and threaten to bet the shit out of me if I didn’t. So I guess never keeping things to myself was an act of rebellion.

The most difficult part for me was when I started to be interested in people romantically. Because when it is not reciprocated, the normal outcome is to shut up and move on. That was not me, and being motivated by all romantic movies and books I read about love, it’s better to be sorry for what you said, than for you did not said, right?  WRONG.

A while ago I made an assumption about somebody. I was so convinced I was right and so enraged and almost blew up and trashed that person. But for some reasons I kept my mouth shut. And recently, through some turn of events, my assumption was proven wrong. I don’t think I’ve even been so relieved and happy about keeping my mouth shut and keeping my assumptions to myself.

There are moment when we must react, we must say something, spat out mean things trying to defend ourselves. But words hurt too, and they have long term consequences. You have no idea how happy I am for finally being slapped in the face for the shit my brains comes up with. And I am so happy that I was bitch-slapped and the fucked up assumption and the bitch-slap are only mine to know and to learn from.

So, welcome to 2020, the year when I’ve started being able to keep my mouth shut. You have no idea for how long I’ve tried to become this person, and how many times I’ve failed. This is good start of the year for me. I wish the same for you.

Stay safe, stay happy!


Jan 10 2020

On being environmentally friendly

Category: MiscellaneousIuliana @ 0:35

I mean, if you really want to be environmentally friendly this is the secret: limit your consumption. Because if you consume, somebody will see a way to make money out of it and they will produce. And to produce what you need, they will consume in turn from this environment, sometimes cutting corners, polluting and who knows what else.

For years in Romania I’ve listened about jokes about Scottish people being stingy, but after moving here I’ve realized that we were so wrong about this people. Scottish people are not stingy, they are efficient. If something can be repaired, they repair it. If something can be reused, they do so. They donate things when they no longer need them and most times are still in the best shape and you can buy them at reduced prices in second-hand shops that donate a high percent of their profits to charities. The Scottish people are very environmentally friendly. Well, most of them anyway.

I’m not bragging. I am not the best when it comes to being environmentally friendly. I eat meat usually once a month. I am doing intermittent fasting so I’m down to two meals per day. It would be nice to get to one meal per day, but … force of habit. I changed my car because I had to in the past, but the one that I have now, I will take care of it and I will give it up only if they outlaw this type of  car. I stopped buying clothes and shoes. I mean, it’s not like I need more clothes, or shoes. I am trying to keep my carbon footprint as small as possible by keeping my consumption as low as I can.

And another thing, you really want to save the planet? Stop multiplying. Seriously, one kid per family is enough. And some of us shouldn’t have kids anyway. Just ask your psychologists how many of us are actually able to take care and guide a small human to become a functional adult.  You would be surprised by the answer.  This planet is dying because we are eating it like termites. Just have one kid and raise him or her well. I admire the adults that have managed to afford to make more than one and if all of them get to be proper adults, kudos to them. But unless you know what you are doing and you have that village to help you raise them right, just settle to one if you want to save the planet.

But these are my not so humble opinions. And who knows what the future holds? I might come back and read this in two or three years while my beautiful twins sleep next to me and I might laugh of the silly human I was now. But following the rule of the universe, where nothing is lost because everything transforms. If you want to slow down the transformation, reduce your consumption and reduce the production of consumers. :P

Stay safe, stay happy!