On Calling Out

Did you call out on the other kids in School?

Do you call out on your colleagues at work when they screw up? Are you the one that always sends that email, CC’ing every supervisor, to make sure not only they know your colleague messed up, but you were attentive enough to notice?

Are you the one calling out every person doing wrong on the Internet?

In School, you’d soon be left with no friends.

At work, you’ll be considered somewhat of a jerk.

On the Internet…on the Internet things are different.

But, in all cases there will be casualties.

Don’t call someone out before knowing the full story, before talking to them, before reasoning with them,  before understanding them, and before helping them understand.

Refactoring to Functional–Why Class?

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

In College

Teacher: We are surrounded by objects in the real world. These can be cars, houses, etc. That’s why it’s very easy to associate real world objects with classes in Object Oriented Programming.

2 weeks later

Jake: I’m having a bit of hard time with these objects. Can you give me some guidance?

Teacher: Sure. There’s actually a couple of more or less formal processes to help you, but to sum it up, look for nouns. And verbs are like methods that can be performed on the class. The behavior so to speak.

Jake: Well that seems reasonable. Thanks!

Jake graduates.

Jake’s on the job

Phil: Hey Jake. I’ve been looking at this class of yours. It’s a little bit too big.

Jake: Sorry. And what’s the issue with that?

Phil: Well, thing is. It’s got too many responsibilities. It does too much.

Jake: And?

Phil: Well think about it. If it does too much, it means that it touches many parts of the system. So the probability of having to touch the class when changing code is higher, which means more probability of breaking things. Plus, 1000 lines of code in a single class is harder to understand than 30 lines.

Jake: Yeah. Makes sense.

Phil: Break these up into smaller classes. That way each class does only one thing and one thing alone.

A year later

Mary: Jake, I’m just reviewing this class of yours, there’s not much behavior in it.

Jake: Yeah well I wasn’t sure if that behavior belonged in the Customer class or to the Accounts class, so I placed it in this other class called CustomerService.

Mary: OK. Fair enough. But the Customer class isn’t really a class anymore. It’s more a DTO.

Jake: DTO?

Mary: Yes, a Data Transfer Object. It’s like a class but without behavior.

Jake: So like a structure? A record?

Mary: Yes. Kind of. So just make sure your classes have behavior. Otherwise, they’re not really classes. They’re DTO’s.

Jake: OK.

2 years later

Mathew: Jake, looking at this class. It’s tightly coupled to a specific implementation.

Jake: Huh?

Mathew: Well, you’re creating an instance of Repository inside the Controller. How you going to test it?

Jake: Hmm. Fire up a demo database?

Mathew: No. What you need to do is first off, program to an interface not a class. That way you don’t depend on a specific implementation. Then, you need to use Dependency Injection to pass in a specific implementation, so that when you want to change the implementation you can.

Jake: Makes sense.

Mathew: And in production, you can use an IoC Container to wire up all instances of the different classes.

3 years later

Francis: Jake. You’re passing in too many dependencies into this class.

Jake: Yeah but the IoC Container handles that.

Francis: Yes. I know but just because it does, it doesn’t make it right. Your class is still tightly coupled to too many other classes (even though the implementations can vary). Try and keep it to 1 to 3 maximum.

Jake: OK. Makes sense. Thanks.

4 years later

Anna: Jake. This class, why did you name it Utils?

Jake: Well. I didn’t really know where to place that stuff cause I don’t know where it really belongs.

Anna: OK. It’s just that we already have a class for that. It’s called RandomStuff

Over a beer…

Jake: You know Pete, I’ve been thinking. They teach us that we need to think in terms of objects and identify these with nouns among other techniques. We then need to make sure that we name them correctly, that they’re small, that they only have a single responsibility and that they can’t have too many dependencies injected into them. And now they’re telling us that we should try and not maintain state because it’s bad for concurrency. I’m beginning to wonder, why the hell have classes at all?

Pete: Don’t be silly Jake. Where else are you going to put functions if you don’t have classes?

Pete: Another beer?

Until next time.

Kotlin and ReSharper in Australia

I’ll be in Australia soon for YOW! Conference, where in addition to giving a talk I’ll be giving a workshop on Refactoring and dealing with legacy code with ReSharper, both in Melbourne and Sydney. There’s still time to sign-up!

In addition, the folks of the Melbourne JUG and Sydney JUG have been kind enough to host me to give a talk on Kotlin. We’ll be putting Kotlin to the test and I hope to be able to answer any questions you might have, so it will be as interactive as possible.

Finally I’ll also be at DDD Brisbane where I’ll be giving a talk and a Q&A Panel.

Hope to catch you at one of the events. And once again, thanks to YOW organizers for making this all possible.

Refactoring to Functional– Reducing and Flattening Lists

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

In this part let’s pick up some more primitives of functional programming and see how we can use them. We’re going to expand the previous list of albums to also include track information

We’re going to solve two different exercises this time:

  1. Get a list of albums and their total duration.
  2. Get a list of tracks that are shorter than a certain length, along with the corresponding album title.

To get a list of albums and their total duration, we’ll go for the simplest approach, using some of the primitives we picked up in the previous part.

reducing to a single value

What we’re doing in the previous code is iterating through the list of tracks and summing them up. As expected, there’s a function for that: reduce. Reduce takes a list of items and returns a single value, applying a specific operation to the list.

Knowing this, we can refactor the code to use reduce.

reduce versus fold

Kotlin also provides a very commonly used function named fold which does the same thing as reduce. The difference between the two is that fold takes an explicit initial value, whereas reduce  uses the first element from the list as the initial value.

Dealing with trees

Up to now, we’ve used forEach, map, filter and reduce to perform operations on lists. The problem with trying to find a list of tracks that meet a certain criteria is that this list is a list inside another list, i.e. we have a tree, albeit a small one. Filtering the original list is not going to work since the information to filter is on a branch. We therefore need to filter out based on the branch.

Here’s a first attempt

What we’re doing is iterating through the list of albums, and then for each one, filtering out those that match a certain criteria. On each iteration we hold a reference using a closure to the current album, and then add those matching the criteria as a new pair to the result.

Once again we can avoid some of this manual work and delegate it to a function named flatMap that takes a list, applies a transformation to each item and returns a new list with these items.

With that, we can refactor the previous code to

There’s a more generic version of flatMap, named flatMapTo which allows us to specify the resulting collection.

Other constructs as they come

In addition to filtering results, we can also find out if an item on the list matches a certain predicate with any, or if all items match it with all and last but not least find the first item that matches it with find.

We can also group items of a list or zip two lists (combine items from each list into pairs into a new list) as well as perform a few more basic operations on lists. Hopefully with these constructs we’ll have enough to solve problems.

Until next time.

The Speaker Maturity Model

Levels

Dear Conference Organizers,

Eliminate Level 0. In other words, cover Travel Expenses for Speakers.

If you’re a conference backed by a large corporation or conferences are your business, you really don’t have an excuse not to. If you’re a community driven event, get some more sponsorship money from sponsors or cut some costs on promotional videos, or raise that ticket by a few euros.

Telling a speaker they’ll get a free pass to the conference is pretty much the same as saying they won’t be escorted in and out of their session.

Telling a speaker they get exposure and/or marketing is nice, it’s true. But there’s only so much exposure one can get.

Dear Speakers,

By accepting Level 0, you’re only promoting the practice.

*Level 3: Too demanded. Having to turn down events despite bucketloads of cash being thrown at you. Much like REST, great in theory, hard in practice.

Refactoring to Functional– Basic Primitives

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

Say we have a list of great albums (i.e. Pink Floyd’s discography*)

We want to get a list of all albums that were number one in both the US and the UK.

The Imperative Approach

Let’s go for the simple approach. A for loop iterating the length of the list and adding the new items to another list.

This works and is simple enough. But there are a couple of issues, if we’re trying to abide by the functional paradigms highlighted in the previous post. In particular, treating things as infinite. Here we’re consciously aware of the length of the list.

Refactoring to infinite lists

We want to avoid having to deal with indices, lengths and counts and worrying whether we have some element in or out of bounds. So the first step is to refactor to remove the actual loop index. In Kotlin, there is a for in loop which allows us to iterate through anything that has an iterator() function. In other words, anything that implements Iterable<T>.

Now we no longer need to deal with lengths.

Adding some syntactic sugar

The previous is better, but we can add some syntactic sugar. Instead of explicitly having a for in we can use an extension function that Kotlin provides, forEach which does the same thing

Since we no longer have the actual album element we can reference the current item the iterator is on using the it reserved word in Kotlin.

What we want instead of how we want it

If we look at the previous code, what we’re doing is removing elements that don’t match a certain criteria. We’re doing this by creating another list and adding the ones that do match to this new list. But if we were to remove the name of the function, to understand what we’ve just described, we’d need to mentally envision it taking into account the for loop, the temporary list, etc.

Of course, with this code it isn’t that hard but add another embedded for loop and things can start to get ugly.

The problem here is that we’re telling the computer how we want something done, instead of what we want done. What we want is to filter a list. What we’ve done is create another list and copy items to it, then return that list. Why not instead just filter the list?

Refactoring to asking versus telling

In Kotlin there is a filter function that takes a list and returns a new one that matches a certain predicate.

We can therefore refactor the code to

The reason we’re omitting the parenthesis is that by convention in Kotlin, if the last parameter to a function is another function, we can omit these.

As a side-effect of this refactoring, we’ve also removed the temporary list, and while in the previous code, hits was declared as immutable, the list itself (declared as ArrayList) was mutable. Win?

Changing data types

What happens now if we need something slightly different? We’re not always bound to work with the same type of data. Let’s assume for instance we want to return the years where an album made it to number one in both the UK and the US. We could of course do the following

The problem is that we re-introduce again some of the issues we had previous, namely using a temporary variable and again telling the computer how we want something versus what we want.

Using Map to transform results

Much like filter, Kotlin offers another function to help us do this: map.

which takes a function that given an input of type T produces an output of type R, returning a list of R. We can therefore refactor the previous code to

Once again we’ve gone from saying how to do something to asking for it.

Basic Primitives

The two functions we’ve just used: map and filter are some of the main primitives in functional programming. With them we can start to treat lists as infinite, chain them and transform results to what we need without having to deal with for loops, lengths, indices or complicated loops. We’ll see if they actually do help dramatically as we start working on more complex scenarios.

Until next time.

*The true Pink Floyd.

Writing Kotlin in the Browser

Did you know that Kotlin can target JavaScript as well as the JVM? Don’t be too surprised if you didn’t know, as we’ve not been giving it too much coverage, despite already shipping a successful product that uses this capability. But here’s hoping to change things.

The Basics – A Simple Project

First step is to set up a new project. When using Kotlin in a project, we have the ability to target either the JVM or JavaScript. If we’re adding a new Kotlin file to an existing project, Kotlin will prompt us for this. If we’re starting a new project, we can choose the target during the setup wizard, assuming we’re using IntelliJ IDEA.

image

We also need to add the Kotlin standard library to the project. Clicking on the Create button we’ll be prompted with the location where we want these files copied. By default it copies is to a folder named script. And we’ll get to this later on as it’s important.

image

Project organization

The resulting structure of the project should be

image

The project has two files that are added:

  • The lib folder contains the header files, as a jar file, which are used during development.
  • The script folder contains a single kotlin.js which is the Kotlin runtime library. This is used in production.

All our Kotlin source code should be placed in the src folder. Once this is compiled, it will generate some JavaScript files that need to then be shipped along with the kotlin.js runtime file.

All other source code, be this external JavaScript libraries or files, CSS and HTML files can be placed anywhere, preferably in the same project to make development easier but not necessarily. For our example we’re going to place this in a folder called web and create a series of subfolders to structure our code.

image

Setting up a workflow

When we write Kotlin code,the compiler will generate some JavaScript which needs to be shipped as part of our application. By default, IntelliJ IDEA will output this file and its sourcemap to a folder named out/production/{project_name}

image

During development we need to have an up to date version of these files so ideally we’d like to have these located in our web/js/app folder. We can do this in many ways, either using IntelliJ IDEA artifacts or Maven/Gradle. In our case we’re just going to use an artifact. We can set one up to copy the corresponding files to the desired output location and additional also copy the kotlin.js file that was originally copied to the script folder to the same location*.

*This is a one-time operation so a better alternative is to define the output location of this file directly to our required output folder when setting up the project. We have done it this way to explain things step by step.

Interacting with DOM Elements

Now that we have the project layout ready, let’s start writing some code. The most basic thing we can do is manipulate some DOM elements. We can create a simple HTML page (named index.html) and place it under the web folder

The idea is to now update the value of the input field using Kotlin.  For that we can create a new file called main.kt and place it under our src folder.

Web-targeted Libraries

Kotlin provides a series of libraries targeted specifically at the web. In our case, since we want to manipulate the DOM, we can import the js.dom.html to access the documentvariable. The resulting code would be

which is very straightforward. We’re using the document.getElementById to retrieve the DOM element and then setting its value using setAttribute. Exactly the same way we’d do it using JavaScript, except here we’re using Kotlin and have the benefit of static typing, among other things.

The standard library already provides support for DOM manipulation, HTML 5 features such as Canvas and Local Storage, as well as wrappers for common libraries such as jQuery. We will be adding more as we go along, and we’ll cover some of them in future posts.

Running the code

Now that we have the code compiled, we need to actually run it. For this we have to reference both the kotlin.js as well as the generated (basic.js) file from our index.html page.

The code corresponding to the main function will automatically be called when the page is loaded.

Once we load our index.html page, we should see the result.

image

Calling Kotlin from JavaScript

What if we have for instance some code in Kotlin we want to use from JavaScript? For instance, think of scenarios where you need to do some sort of business logic that needs to be repeated both on the client and the server. Well all we need to do is write it and then call it. Here is a simple function written in Kotlin

This is placed inside the same module as the application and we can call it referencing it by the Kotlin module name*

*This API is not final and will most likely change in the future, and probably will be much more compact.

Next Steps

That’s not all that is possible with Kotlin. One thing we haven’t mentioned is the ability to call JavaScript code from within Kotlin and that is something we’ll be covering in a another post, as this one has already become too long!

If you want to play with Kotlin to JavaScript without having to install anything, you can also try it directly in the browser. And as always, give us your feedback!