Oct 17 2020

Spring Boot + Docker = Love (or something like that)

Category: TechnicalIuliana @ 16:30

Feel free to open a beer and celebrate this technical entry. I don’t do this often, because I prefer to dedicate my spare time to projects that soothe my soul, like playing the piano. But, I want to improve the structure and capabilities of the project for my future books, so here I am combining my expertise on Spring with my expertise in cloud technologies in a (hopefully) graceful way.

In this entry I am going to show you how to create a simple Spring Boot Web application and deploy it to a Docker container. I will walk you thorugh my process, and assume I am starting with a black slate and install various tools as I need them.

Initial prerequisites:

  • JDK 15 (I usually set the JAVA_HOME environment variable and add $JAVA_HOME/bin to the system path)
  • Gradle 6.5.1(I set the GRADLE_HOME environment variable and add $GRADLE_HOME/bin to the system path). I know Gradle Wrapper exists, but I like having Gradle on my system and managing it with SDKMAN. I am stuck to the 6.5.1 version, since the Palantir plugin does not want to work with more recent versions.
  • IntelliJ IDEA IDE, the best Java editor I’ve worked with so far.

Continue reading “Spring Boot + Docker = Love (or something like that)”

Tags: , , ,


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, 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: , , ,


Jul 03 2018

A short skepticism story

Category: MiscellaneousIuliana @ 13:15

I started learning programming at age of 14. I was in high-school and the programming language did not really matter to me. For me it was all about algorithms and data structures as means to solving problems. Whether I was using FoxPro, Turbo Pascal or C, what it mattered was solving the problem and getting the results.

Then I went to the university and because of a series of unforeseen circumstances I ended up writing most of my solutions in Java. And it was all classes, interfaces and objects, OOP for short.

Almost my whole career was centered around the OOP way of solving problems. Even when I was writing JavaScript code, I was still stuck on classes , objects, fields and methods. It did not really occur to me that there was other way of thinking and designing my solutions anymore. OOP seemed so natural, it modeled real life objects and processes after all. But real life is most of the time inefficient and less than optimal, and real life solutions are based on things designs created by at least two generations before and propagated by adults that function based on the “it is known” principle. Because, after all, there is a risk involved in doing things differently, that most people prefer not to take. It is the “If it works, don’t fix it!” engineering principle.

Enter “Gica-Contra”, a Romanian term that describes people that “swim against the current”, people that feel compelled to be against the other 99%. This term has always been used by my mother to describe me because since I was a child I was quite rebellious and stubborn, and always felt the need to ask that  damn question loathed by parents who thought parenting is easy: “Why?”. If you think this kind of attitude changes with age, you are mistaken. I have become the kind of adult that does the following:

  • asks “Are you sure?”
  • says “Let me double-check that!”
  • says “Neah, there must be a different/easier way to do this!”
  • asks “But, what if …?”
  • asks “But how do you really know?”
  • says “If too many people have the same view on this, there is something shady about it.”
  • and many more.

And all that my friends, translates to a single term: skeptic.

Being so stuck on OOP, I was quite skeptical about functional programming. And rightfully so, as the only programming language I could associate it to was Turbo Pascal, and suffice to say, I did not like Turbo Pascal very much. Also there is so much hype about functional programming nowadays, that it tingles my Gica-Contra sense a little bit too much. And that’s the thing that got me worried. I’ve always considered my skepticism as a superpower, as the fuel for my out-of-the box thinking engine. But when it came to functional programming, it kept me from even taking it into consideration, it kept me in the dark. And that’s when it hit me: I was behaving exactly like the traditionalists and conservative narrow minded humans that I’ve always claimed to despise.

This had to change. I needed to come into the light. Thankfully I now work for a company that pays for independent study, we have 10 training days per year, when you are payed just to study whatever you are curious about and the conclusion of those days must be shared with your colleagues via a blog post or presentation. So I took advantage of my first training day to start learning Kotlin. And it was mind-blowing. Especially since one day earlier I also participated to a Scala workshop that went very well. All of a sudden, there was all this new information coming from comparing the two languages. It’s like the fog was lifted from my eyes and I finally could see the power and the versatility of functional programming.

And most of all, I could see the practical side of it. Solutions that needed 20 lines of code to be implemented in Java, needed only 2 lines in Kotlin, and surprisingly, they were still readable. Almost the same in Scala. Come to think of it, I have been bothered for a while by all the boilerplate code required in Java to fit the OOP principles and some coding conventions  that nobody asked me about. All these getters and setters, all the bloody curly braces and all the NPEs… Kotlin and Scala reduce that. And funny enough Java is going in that direction as well, I mean with modules, you might as well just declare your fields public and avoid writing setters and getters, because if the class is not in an exported package you have nothing to worry about.

So yeah, interesting times are coming. No worries, I’ll keep you in the loop. ;)

Stay safe, stay happy!

 

Tags: , , ,


Dec 07 2017

Experience cloud

Category: MiscellaneousIuliana @ 11:12

I created this for a presentation about my experience and skills and I thought it belongs here.

The word cloud above covers all my 11 years of development so far and clearly reveals which topics I am best at. Although I always wished myself to become an agnostic developer, also known as a polyglot developer, after all these years I have to accept the fact that Java & Spring are clearly my strongest points.

Where should I go from now? Well… I have considered learning Kotlin for a while. ;)

Tags: , ,


Sep 18 2013

The repetitive programmer

Category: TechnicalIuliana @ 12:36

You know who you are. I know who you are. And I hate you. And I despise you. Every time I have to  work with your code my brain keeps screaming WHY? WHY?WHYYYYYYY?  and I begin to think you are retarded. Or maybe just not retarded, but maybe you learned to program on another planet, because no programmer from this Earth, not even a mediocre one would write code like you do and also be paid for it. I would not pay you for it, I would send you do dig holes or clean shit pipes or something that does not imply any brain power whatsoever. Because you have none!

Sample:

// [bla bla  bla - code that I won't put here]
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
	Document document = new Document(PageSize.A4);
	PdfWriter writer = PdfWriter.getInstance(document, bos);
        // [bla bla  bla - code that I won't put here]
	if (document != null) {
	    document.close();
	}
	if (writer != null) {
	    writer.close();
	}
        // [bla bla  bla - code that I won't put here]
        OutputStream outputStream = new FileOutputStream(attachmentURL);
	bos.writeTo(outputStream);
        // You might notice that the outputStream was not closed
} catch (MailException e) {
        if (log.isWarnEnabled()) {
                log.warn("Cannot send email for something " + something.getId(), e);
	}
	sendAdminMessage("Error sending email message to user", "Cannot send email for something nr "
			+ something.getId() + ". Message is = " + e.getMessage());
			return false;
} catch (MessagingException e) {
	if (log.isWarnEnabled()) {
		log.warn("Cannot send email of something " + something.getId(), e);
	}
	sendAdminMessage("Error sending email message to user", "Cannot send email for something nr "
			+ something.getId() + ". Message is = " + e.getMessage());
			return false;
} catch (IllegalArgumentException e) {
	if (log.isWarnEnabled()) {
		log.warn("Cannot send email ofsomething " + expressOrder.getId(), e);
	}
	sendAdminMessage("Error sending email message to user", "Cannot send email for something nr "
			+ something.getId() + ". Message is = " + e.getMessage());
			return false;
} catch (MalformedURLException e) {
	if (log.isWarnEnabled()) {
		log.warn("Cannot send email of express order " + something.getId(), e);
	}
	sendAdminMessage("Error sending email message to user", "Cannot send email for something nr "
			+ something.getId() + ". Message is = " + e.getMessage());
			return false;
} catch (IOException e) {
	if (log.isWarnEnabled()) {
		log.warn("Cannot send email of something " + something.getId(), e);
	}
	sendAdminMessage("Error sending email message to user", "Cannot send email for something nr "
			+ something.getId() + ". Message is = " + e.getMessage());
			return false;
} catch (DocumentException e) {
	if (log.isWarnEnabled()) {
		log.warn("Cannot send email of something " + something.getId(), e);
	}
	sendAdminMessage("Error sending email message to user", "Cannot send email for something nr "
			+ something.getId() + ". Message is = " + e.getMessage());
			return false;
}

So, 7 catch-es, for seven types of exceptions, we do the same thing for every type of exception, write the same code, because it looks good in the SVN if somebody looks, he will see that you wrote a lot of code. A lot of crap more like it. And why the hell do you not make sure all your streams are closed??
The person who wrote this code is payed a few thousand euros to write code like this. Yeah, I guess the recruitment department sucked ass when this person was hired.

So yeah, if you write code like this, quit programming now and look for another job. You clearly are not made for this and you are a despicable person.

Tags: ,


Oct 13 2012

Learning Spring, part III

Category: TechnicalIuliana @ 18:15

I have a new hot question for you:

We have two classes AccountServiceImpl and ClientServiceImpl. Any of these classes inherits from each other, meaning one is a subclass of the other. What will happen if we define a pointcut like this:

"execution( * *..AccountServiceImpl.update(..)) 
       && execution( * *..ClientServiceImpl.update(..)) "

And here are your options:

  1. The pointcut matches any public update methods of the two classes whatever the arguments.
  2. The pointcut matches any update methods of the 2 classes whatever the arguments and the method visibility.
  3. The pointcut matches any update methods of the two classes, with one ore more arguments and whatever the method visibility.
  4. No join point is defined.
  5. Something else will happen.

Continue reading “Learning Spring, part III”

Tags: ,


Sep 15 2012

Learning Spring

Category: TechnicalIuliana @ 23:47

A few months ago the company where I am currently employed sent me to Belgrad to train me in Spring Core. The training lasted 4 days and at the end I was supposed to take the Spring Core certification exam and pass it.

I delayed that for a while, but because now I have some spare time I decided it was time for me to do this thing. So I went over the slides and the spring code samples again. But after doing some mock tests I concluded I will most likely fail the certification, because the official materials were not enough so I started reading Spring in Action. Still I noticed that in the tests there was still stuff that I hadn’t covered. So I started reading Spring Reference. And because I have some problems in retaining information just by reading it, I stared to test the recommended examples. And this is where I hit some walls.

But before telling you what is not clear for me I shall tell you what technologies I’m using for development: Maven 3.0.0, Jdk 1.7, Intellij Idea 11.1.3 and Spring 3.1.2 (I know the certification is for 3.0, but as the Spring reference manual has 840 pages, I might as well read about the new and useful stuff added in 3.1)

The first problem I had was with the compound property names. I tried using them. Idea does not recognize them and my test fails.

Continue reading “Learning Spring”

Tags: ,