Estimate your project

Message sent

Thank you!

Your message has been sent. We’ll get back to you in 24 hours.

Back to page
24 hours

We’ll get back to you in 24 hours

to address your needs as quick as possible.


We’ll prepare an estimation of the project

describing the team compostition, timeline and costs.

Code Review

We’ll perform a free code review

if you already have an existing system or a part of it.

Our work was featured in:

Tech Crunch
Business Insider

Protocol-oriented vs object-oriented in Swift: translating complicated world into simple code

Protocol-oriented approach has been making strides in the Swift community in recent years. It is more of an extension rather replacement of the object-oriented paradigm – a prelude to evolution rather than a revolution. But it still provides tons of benefits for both developers and organizations. Find out all about them in this example-rich introduction to protocol-oriented programming with Swift.

Object-oriented programming is one of the most widely known of all programming paradigms. But it’s not all there is out there. In recent years, the Swift community has been adopting more and more of a protocol-oriented approach. It is neither something all-new and shiny, nor a silver bullet for all problems. Still, it might serve a useful role in structuring the code. In this particular area, I will discuss protocol-oriented programming with Swift today.

Object-oriented approach in Swift

Let’s imagine… (Have you noticed that almost all programming articles start like this?) you were asked to write a game – a quick and easy one, with just two levels. (This is how all the quick and easy projects start, don’t they?). Level one will take place on the ground. Level two will be…  the underground hell.

Let’s be object-oriented first. We need to find some similarities and hierarchies and simply model them. We will also need a couple characters: one for the player, one for the land creatures (enemies on the surface) and one to represent the hell monsters. Let’s start with a very basic type Creature to encapsulate common properties and behaviours.

Enemies on the ground should be able to walk and run in order to chase and fight the player. We can introduce LandCreature simply by subclassing Creature and adding extra capabilities.

So far so good. Let’s move on to some hotter areas… Monsters hidden in the deepest pits of hell are very dangerous, as they burn everything they see. When they cannot reach the target with flames, they need to walk or run up to the victim.

At this point, we would probably decide that running and walking are fundamental capabilities of all characters, so we should move them into base class Creature to remove redundancies. It’s good not to repeat the code, isn’t it?

After some refactoring:

Ladies and gentlemen, meet Lucifer, the HellCreature. He can burn, walk and fight.

Victory!??? The game is ready. It’s pretty fun to play. It is, I must say, a great success.

At this point, your boss would probably come up with an amazing idea of adding premium level to the game. Yes, the one with the rebellious pilot. Ooooookeeeey, it can’t be that hard, can it?

The rebellious pilot enters the game.

We need a new type of enemy: SkyCreature. It should be able to fly(). Easy-peasy.

Let’s create rebelliousPilot

Surprisingly, Kanimoor can walk. What the hell?! Yes, we’ve just moved run and walk capabilities to the base class because they seemed common. Unfortunately, it’s no longer the case. Of course, we can override run() and walk() in SkyCreature with fatalError() or no action at all. We can also… move run() and walk() back to LandCreature and HellCreature. It is the end of the project, after all. One little code duplication has never killed anybody, hasn’t it?

So we might end up with a structure like this:

Finally, Kanimoor can no longer run or walk.

Once again, the game is completed. Well… almost. In the New Year’s edition, there will be yet another extra level to play… against the DRAGON!

I think you can already smell the troubles we are going to encounter…

Of course, Wyvern is supposed to walk, run and burn as well. Once again, we can move walk() and run() to the base class… or copy and paste here and there…

Protocol-oriented programming with Swift – introduction

This time, let’s assume we have the opportunity to start the entire project all over again (it is quite a nice perspective, isn’t it?) and take a look at how we can use protocols to structure the whole universum better. To do that, first we have to find out what protocol-oriented programming with Swift is and what it offers. The documentation states that:

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.“

Protocols are similar to interfaces in other languages. Yet, in Swift there are a few unique and very useful features protocols have. First, they can have a default implementation of the required methods. For example:

From now on, every type which adopts the protocol Running will get the implementation of run() for free. Of course, you might want to override it sometimes with another implementation of running. When it is not the case, the default should be sufficient and helpful in avoiding code duplication.

Default implementations can also be provided for a selected part of the adopters only. In the following example, every type which will conform to Persevering and Walking protocols will gain a nice ability of achieving something stepByStep().

Types can adopt multiple protocols, as they can do multiple things. At the same time, they can only be one thing (inherit only one superclass). Another very important thing is the fact that protocols may be adopted by both reference types (classes) and value types (structs and enumerations), whereas base classes and inheritance are restricted to reference types only. We didn’t touch upon the difference between value and reference semantics here,  but I really suggest you check this as well. It is another key feature in Swift that is really worth knowing and using wisely.

Extensions let us model an application’s structure retroactively, instead of forcing us to make all the decisions upfront.

With this fundamental protocol-oriented programming with Swift introduction out of the way, we can start implementing the first two levels of the game. I think it will be useful for the base character class to at least have a name so I will introduce the class Creature (this time, without any capabilities). I will also extract a fundamental game action: fight() to the protocol Strikeable.

Declaring fight() separately in  Strikeable allows me to supply other game elements with the ability to attack (these may not necessarily be Creatures). The first level takes place on the ground, where player will fight against LandCreatures. Their basic actions (besides fighting) are walking and running. I will introduce two protocols to cover them:

With this, declaring LandCreature is pretty straightforward:

LandCreature Woolfie receives all of the following actions from the extensions of our protocols:

Let’s go to hell again (?)! Almost all pieces required to build HellCreature are ready at this point. We still need burn(), so let’s add a protocol called Burning, coupled with a default implementation, of course:

Now, let’s bring in HellCreature and invite Lucifer to the stage.

The Rebellion again – protocols to the rescue

This time,  we can accept the game’s success much more easily. We might even be thrilled to go back to the project!

Rebellion in the air zone (third level) will require adding SkyCreature, which will be able to fly() and fight(). While SkyCreature gains fight() with fists by default,  it seems there are other fighting methods that are more efficient in the air.

It was quick and clean, wasn’t it? Excited by this quick success, let’s add (by our own choice!) an extra bonus level with a?.

? What a great success! Our protocol-oriented creation is good to go!

By using protocols, we were able to compose all of the Creatures in the game by adding a set of suitable features, instead of creating a stiff hierarchy of classes. In many cases, it’s more flexible to define objects by what they are able to do, rather than what they are.

Here is another useful hint for those of you who are already thinking of delving into the world of protocol-oriented programming. With protocols, we can add convenient properties to check whether a given object can perform a particular task:

What’s awesome about it is that you don’t need to update these values when any of them stops conforming to the protocol. These are computed properties, so the results will alter automatically.

Where is the catch? The risks of protocol-oriented programming with Swift

Just as the object-oriented programming carries the risk of creating a very complex class hierarchy, the protocol-oriented paradigm may cause the structure to grow too much horizontally. Excessive granulation caused by creating many tiny protocols will make maintaining and using the application hard and annoying. For sure, it also requires keeping order in the project  so that you don’t lose track of what conformances were added to which classes. At the end of the day, it’s like with any other technique: a balance needs to be found and the problem should drive the solution, not the other way around.

Conclusion ?

In the object-oriented paradigm, we focus on what an object is, while the protocol-oriented approach allows us to focus more on what an object can do, its abilities and behaviours. Our simple game was meant to emphasise differences in structuring decisions during the development process using both of these paradigms.

The object-oriented approach may sound very straightforward, because it is all about finding relevant nouns and creating a hierarchy for them. However, even in this simple game we struggled with so many important decisions that had to be made early in the project.

Protocol extensions and default implementations at first may seem similar to base classes or abstract classes in other languages, but in Swift they play a bigger role. Why?

  • Types can conform to more than one protocol.
  • They can also obtain default behaviours from multiple protocols.
  • Unlike multiple inheritance in other programming languages, protocol extensions do not introduce any additional states.
  • Protocols can be adopted by classes, structs and enums, while base classes and inheritance are restricted to class types only.
  • Protocols allow retroactive modeling with extensions added to existing types.

What else can I say? „At its heart, Swift is protocol-oriented“ so learn as much as possible from the standard library – it is a great source of knowledge! Observe how the Swift team uses protocols to structure the code, separate concerns, share common algorithms etc. to get yourself inspired. Most importantly, give protocol-oriented programming with Swift a chance and find out yourself how it can improve your workflow.

7 reasons to use functional programming on frontend 2/2

In the first part of “7 reasons to use functional programming on frontend”, we’ve focused on some basics. I’ve mentioned immutability, pure functions and referential transparency. Now, it’s time to study some other features which are more frontend-related.

4. Time-travel debugging

Sometimes going back in time is the only way to fix a bug

Have you ever used Redux DevTools? It’s a very helpful tool if you want to debug React + Redux combination based app. Redux is a library capable of managing app state. One of its core principles is the ability to change the state only through pure functions.

The assumption that the app state is modified only through pure functions makes it simple to go back in time and study the application state. For example – right before a bug occurred. In fact, pure functional programming makes the “undo” feature easy to implement. It’s because you have a guarantee that before a new state is presented, the former one is not affected, so it can be easily stored in history.

However, Redux is just a JavaScript library and cannot enforce developers who use it to avail themselves of pure functions. Moreover, typical React app is not only about the state. There are many side effects to be made, AJAX requests to be sent, some components with their own state to be rendered in the DOM and so on. Because of that, Redux and Redux DevTools may get tricked if a developer does not follow the pure functions convention. But there are some alternatives which can fix that problem too. One of these is Elm programming language.

Using Elm can help you solve some problems

Elm is a frontend programming language which compiles to JavaScript. In contrast to JavaScript, it’s a pure functional programming language. One of the fun features which Elm offers is a time-travel debugging which is not limited to a raw app state as it is in Redux DevTools. In Elm’s Time Travelling Debugger, it’s possible to go back in time and observe the real app (instead of its raw state tree) in the way the users see it in their web browser.

What’s more, this tool can also import/export app state so a developer can debug any state saved in a file. This can be helpful not only for debugging sessions but also can give the QA team another tool that can improve the bug reports.

In fact, Redux has been inspired by Elm. Also, Dan Abramov (the creator of Redux) has been inspired by Elm Time-Travel Debugger and you can watch his cool presentation how he achieved a similar effect for React + Redux.

5. Functional patterns

Every JavaScript developer these days has to deal with its asynchronous nature. When Node came out, one of the anti-patterns became famous – callback hell:

In frontend, the asynchronous nature of JS can also be a problem for junior devs. Tasks like the following may not be easy for junior devs when relying on callbacks:

  1. post some data through AJAX to endpoint X and on success, get new data from endpoint Y,
  2. get data from endpoint X, Y and Z. Wait for all responses, combine them and then finally – display the combined data.

There are some patterns able to control the asynchronous code

But, there are Promises for the rescue. Promise is a well-known pattern that makes it easier to control the asynchronous code and can make it more readable in contrast to the typical callbacks. There are many tutorials in the web about it and also some other patterns which deal with asynchrony in JS that became popular, like “async-await”. But there is one thing that is worth mentioning in FP context. Promises have much in common with Monad which is a functional programming concept. What the Monad is? It is not crucial to understand it for the purpose of this article but there is a great cartoon-illustrated guide which I recommend if you want to learn more.

The thing is that Promise is a really similar pattern to Monad. As Monads can help you with wrapping a value to some context and can add specific behavior to operations that are applicable to them, Promises will help you with wrapping future value (which will come from asynchronous operation) and they add specific behavior which enables you to chain operations to be performed next through the chain of then.

Consequently, we can benefit from functional programming on frontend whilst day to day programming, even though at first glance it offers features which may look like complex structures closer to mathematicians terminology.

6. Declarative-style is readable when describing visual aspects

HTML, CSS and SVG are languages describing the structure of the elements rendered on the browser

When it comes to visual aspects, declarative style is desirable on the frontend side. HTML, CSS and SVG are languages which describe the structure and appearance of the elements rendered on the browser. So, naturally, when it comes to JavaScript frameworks, this approach is also popular.

For example, in Angular, you’ve got templates which look very similar to the plain HTML. There are also some additions like custom components, directives, interpolation through `{{}}` and other features. Template languages can make things better, although they have at least one disadvantage – new syntax to be learned. For instance, take this Angular snippet:

It does not look too complicated if you learn the syntax, although you have to admit that `*ngFor` attribute thing with “let hero of heroes” expression looks a little fancy to a person who just got started with Angular.

Functional programming is a declarative paradigm at the same time. Consider the following functions as an example:

We can read it like this:
add is a function which result is a sum of two arguments passed into it;
sum is a function which result is passed in array, reduced using the add function and 0 as an initial value.

Of course, we can try to read imperative programs in a similar manner but the point here is that in FP, functions are often written as expressions instead of a block of multiple instructions to be executed from top to the bottom. So our programs are more like definitions what the stuff is, instead of how a program should behave step by step.

Hence, when you learn a functional programming language, it can be reused also for visual aspects of your program in contrast to learning another separate syntax for templating. In React for example, thanks to the ingenious Virtual DOM system, we can easily apply: map, filter and reduce functions, well known in the functional programming. They can be easily applied in component rendering definition:

JSX syntax, which looks like a mix of HTML and JS is just a syntax sugar. You can write equivalent code in standard JavaScript. The thing is that functional programming functions can fit nicely when expressing the stuff to be rendered.

What’s more, we can extend this approach to some other visual APIs that are not purely declarative in standalone HTML. I’m thinking about the Canvas element which requires some imperative JavaScript code to paint a stuff on it but you can use for instance react-canvas which enables you to use the canvas as its contents were DOM elements like <Image>, <Text> (similarly to SVG):

And this is cool because you won’t be bothered with stuff like when to repaint the picture and how to do it, but your app code can focus on definition how app state should be represented visually. It can be implemented just with a simple function which takes the app state as an input and returns what’s to be rendered as an output. Doesn’t it sound great when you also think about the testing?

7. Straightforward optimization

Functional programming can make some programs predictable

You may think that programs written in the purely functional manner may have an impact on the performance. After all, Pure FP programs assume that value like array cannot be reused if you want to add a new element to it. Instead, you’re imposed to create a new version of such array with new value added on the end. Looks like a lot of stuff to be done (copying every element to a new array before appending the new one) by CPU, right?

Well, FP languages behind the scenes can be smarter than that. The fact that FP programs cannot perform some stuff directly limits the programmer. But on the other hand, it guarantees that program won’t do anything fancy on the runtime. In other words, it makes such programs predictable.

Moving back to the array appending example, we can just use an abstraction that looks like an immutable array, but under the hood it may store data in memory more efficiently, so creating a new version of an array (with new element appended) would reuse the previously allocated resources in contrast to copying blindly the values from the previous version for no reason. There is a great article that explains how immutable.js library achieves that. But that is just a proof that it’s possible to write FP programs which aren’t worse than imperative equivalents in terms of performance. Let’s study some examples where we can benefit from pure functions.


For instance, consider the memoization technique. Let’s simplify how it works a bit:

  • when function is called with specific arguments for the first time cache and return the result,
  • when function with specific arguments is called again, return the cached result.

This can be fairly easily implemented in JS. It can be really useful in cases when the time cost of calling a function is high and it’s often called. There is only one requirement – functions that you want to memoize in that way have to be pure because otherwise it is not guaranteed that the remembered result is the correct one that we expect after a call. Hence, score to pure functions.

Virtual DOM + laziness

Another good example where pure functions can shine in terms of optimisation is Virtual DOM. For instance, in Elm programming language, we can optimize re-rendering some DOM elements by decorating the function that produces a lot of DOM elements on each call with  Html.lazy function. Although you probably are not familiar with this programming language yet, I encourage you to read an article which explains how it works. In my opinion, the following quote together with diagrams from that article helps to grasp that idea:

One of the cool things about Elm is the “same input, same output” guarantee for functions. So, whenever we run into two “lazy” nodes while diffing virtual nodes, we ask is the function the same? Are the arguments the same? If they are all the same, we know the resulting virtual nodes are the same as well! So we can skip building the virtual nodes entirely! If any of them have changed, we can build the virtual nodes and do a normal diff.

By “same input, same output” we understand pure functions and we can clearly see that they can do a really good job in making an optimizable ecosystem. Perhaps, you may see some analogy in React’s Pure Components together with their implementation of shouldComponentUpdate method.

Concurrency and parallelism

Although JavaScript engines run the single-threaded event loop, it’s possible these days to use concurrency in your apps, we have WebWorkers API for instance. It’s worth noting that programs that are written in Pure FP manner are easier to be parallelized than imperative snippets. Also, Evan Czaplicki, the creator of Elm (frontend functional programming language) wrote a great thesis which touches Concurrent Functional Reactive Programming topic.


There are some arguments for functional programming not being only a matter of hype

It’s time to answer the question that we’ve asked in the previous part of this article. Functional programming is not only a hype. The concepts that it introduces have already become handy in frontend development practice. Let’s wrap up what we’ve learned about functional programming on frontend in both parts:

  • it proved that object-oriented programming is not the only way of composing maintainable apps,
  • it can help when dealing with a large amount of various type of data which our app state consists off,
  • it can make some contribution to TDD by simplifying or eliminating mocking,
  • time-travel debugging is possible,
  • it fits well for expressing visual content which frontend domain is about,
  • even if an immutable approach to the data may look wasteful for the memory resources and performance at first glance, it opens the doors that enable optimization just at another level of abstraction,
  • perhaps you use some patterns because that’s the way you are told to do in your favourite framework without being aware of the fact that the used framework has been inspired by ideas from the functional programming world?

More reasons could have been listed here in favor of the functional programming on frontend approach. I hope that the examples that I’ve chosen, convinced you to write your frontend code in FP style (if you’re not doing it willingly already). Especially in the era when it is difficult to avoid it.


7 reasons to use functional programming on frontend 1/2

Functional programming has recently become a big thing in the frontend development domain. Why so? Is it an example of hype-driven development or are there any reasonable arguments to use it? To answer this question, I’ve prepared a list of 7 reasons which may make you decide to use functional programming on frontend during your next software project. Below are the first 3 of them.

1. JavaScript object-oriented programming used to be weird in the past

This is one of the reasons why functional programming on frontend might have gained such popularity rather than an argument to use functional programming paradigm. Although, it’s worth mentioning this “weirdness” in the name of the better context. A little bit of history…

In the early days, object-oriented programming in JavaScript used to be slightly weird. It was possible to use this kind of programming, however it wasn’t even close to the OOP known from C++, Java or other popular OOP languages. Just take a look at this example:

It’s due to the fact that JavaScript offered a prototype-based inheritance in contrast to class-based one which is the most popular approach in other object-oriented programming languages. So, why JavaScript took the other way?

In the 90s, we had less powerful computers and obviously, less sophisticated browsers. When JavaScript was invented, prototype-based inheritance has been chosen. It was easier to create an interpreter for it and preserve OOP features at the same time. And probably that’s the reason.

Before the age of transpilers like Babel and alternative frontend programming languages, there was almost no alternative for programming language than ones ran in a browser. If we exclude plugins like Java Applets and Flash. Oh… and VBScript which worked on the famous Microsoft Internet Explorer only.

It took 20 years before ECMAScript 6 with final semantics for classes were introduced

What’s more, it took 20 years before ECMAScript 6 with final semantics for classes were introduced. Before that, people got used to the prototypes and some of them also made use of JavaScript functional programming features. These were truly powerful concepts and were available a long, long time before ES6 classes.

Hence, it might be the reason why not all the people adopted ES6 classes syntax in their codebase. Of course, classes have become popular in React or Angular based apps, although considering standalone micro-libraries which NPM repositories are famous for, the class keyword is rare and functional approach beats it.

2. Immutability can reduce bugs

JavaScript is now something more than just an extra script

Thanks to the solutions like single-page applications, JavaScript is no longer just an extra script that improves the user experience when navigating through the page. Enabling JavaScript support in the browser is something you must do if you want to surf the internet these days.

Sites became applications and the bigger apps are, the more complex issues developers have to deal with.

Frontend developers already have a “bug-friendly” environment thanks to the things like:

  • browser inconsistencies,
  • innumerable amount of devices with different parameters where the app should display correctly (responsive web design tries to deal with it),
  • API connection problems which have to be handled neatly.

And many more. So, naturally, tools and approaches which help narrowing the scope of problems down are highly appreciated.

Functional programming itself has more strict variation called “pure functional programming”. Pure FP is a paradigm that imposes strong restrictions: immutability and side-effects avoidance. At first glance, these may feel like an unnecessary complication (especially for developers with an imperative programming background). But they bear fruit when it comes to the master application state.

In terms of immutability, let’s study the two following functions:

Perhaps you have already spotted a bug. ???? Nevertheless, let’s test their behavior in JS console:

> median([2, 1, 3, 7, 2, 4, 0, 5])

> getLast([2, 1, 3, 7, 2, 4, 0, 5])

They seem to work properly and would pass the unit tests easily. But note what happens in the following code:

The console.log output for such case is:

  • 5 for getLast which is correct,
  • 2 for median which is not the value that we expected.

The problem is that values.pop function inside getLast function mutates the array which is passed into by popping the last of elements.

So, let’s redefine getLast function with immutable (or, so called, pure) principle in mind:

Then, let’s try again:

Did it work as expected or not? Well, there’s another bug we might have missed.

Let’s try to change just one, tiny thing. Namely – let’s swap the console.log lines:

The console.log output is as follows:

  • median gives us 2.5, as we expected,
  • getLast gives us… 7!?

The problem here is that our median function is not pure. It mutates the array that is passed in as it was in our first implementation of getLast.

What makes this function not pure is that it calls another not-pure function – Array.prototype.sort:

Array.prototype.sort behavior may confuse. It returns a sorted version of an array that has been passed into it, although the sorted version is just a reference to the original array which has been mutated.

Taking the functions from preceding code examples into consideration, we can see that mutation made them not working properly when we used them one by one and swapped the order of their execution. It has revealed another bug which might have been missed at first glance.

So, let’s finally fix the code example:

What we’ve done in the code above is that we implemented a sort function. And it does not mutate the original array.

Our pure sorting solution makes use of a simple trick of calling Array.prototype.slice(). It creates a copy of the original array before sorting. This behavior guarantees that our sort function won’t mutate the passed in argument, hence it is pure.

And as we use our pure sorting function in the median function, it’s also pure. It guarantees that median won’t mutate the argument neither.

Now, no matter which function is executed at the first place, the results are always predictable and correct:

3. It’s easier to test

No matter which programming language I use, there’s a thing that I always associate with tests. It’s mocking/stubbing. When you write unit tests, sooner or later you’ll have to fake some objects and functions that tested unit relies on.

Pure functions can help you with that. The way they work is simple:

Here is how pure functions work

just compare them to functions that are not pure:

Here is how non-pure functions work

Due to the fact that in pure functions there is no mutation, side-effects and functions have referential transparency (we’ll focus on this later), it’s guaranteed that the only place where you can change the result of such function are arguments that are an input.

Consider how much easier is writing tests for functions that rely only on what you pass to them explicitly. For instance, functions that have to deal with date and time. Normally, it would be tempting to write such a code:

But because such function relies on the current time (which passes by), you’ll have to mock fthe date object before testing the function. Although this function is easy to write, it’s more difficult to test, as it requires you to fake the time when writing the tests.

Referential transparency is something that can help us in such cases because it guarantees that the function is deterministic. Referential transparency guarantees the specific input which will always give you the same result – no matter how many times (and when) function is called. Hence, call expressions of functions that met the referential transparency condition can just be replaced with output value like in the following example:

The number variable can be replaced with the following:

let number = 4;

So, coming back to our tokenExpired function example. We can rewrite it to a pure version which meets the referential transparency requirement:

This function will no longer depend on the current time behind the scenes, and the tests can be simplified as the current time has to be passed explicitly as the second argument:

To be continued…

In the first part of the article about functional programming on frontend, I’ve focused on the history of JavaScript’s object-oriented programming early state. I’ve mentioned how it might have generated interest in alternative or subsidiary approach which functional programming can be.

We’ve also learned some basic features of functional programming on frontend in practice. Nevertheless, these features are universal and frontend is not the only domain which can benefit from it. Having some basics though, we’re ready to study some further examples.

So, stay tuned. In the second part, we’ll focus on another four reasons to use functional programming on frontend. And on some other features that frontend can benefit from.