What is the functional programming style


What do building blocks and programming have in common?

Nothing and everything.

In the programming world, we have various paradigms. For simplicity, we can call them styles. One of them is functional style. The functional style is similar to building a tower from building blocks:

The basic element (building block) is a function:

output function (input)

Functions are composed together to provide functionality:

output functionC( functionB( functionA( input ) ) )

The output of one function goes as input to another function. Visually it looks like this:

Yes, building blocks tower!

If you imagine it horizontally – pipeline, my preffered way:

In programming it is important to visualize the data flow, and how the elements interact.

Examples

Streams, at low level:

Set<Person> getPersonsWithCredit (Set<Person> persons) {
  return persons.filter(Person::hasCredit).collect();
}

Functions composition:

sendNotifications( createNotifications (getPersonsWithCredit (persons)))

Streams, at a higher level, using functions:

persons.filter(hasPersonACredit)
       .map(::createNotification)
       .foreach(::sendNotification)

When to use functional style?

  • transforming and processing a set of data/events
  • linear flow a -> b -> c
  • processes in the background – do not require user interactions

When not to use functional style?

  • complex flow/logic
  • managing/changing the state
  • interactions between objects

I will sum it up in one sentence: if you feel/see that a problem can be easily solved in a functional way, do it, otherwise don’t.

Benefits

You can ask chat/copilot. It gives you quite good answers. I will put the most important in my opinion:

  • Testing and Debugging: Functional programs are often easier to test and debug because functions are generally small and pure, meaning they depend only on their input and produce no side effects.
  • Concurrency: Functional programming avoids mutable state, which makes it easier to write safe concurrent code.

Summary

My colleague programmer said that every function you can express like:
output function (input)
I agree, but building a business application with multiple conditions, business logic, state management, flows, processes, etc. will be difficult using a functional approach.

I repeat the recommendation: use functional programming to linearly transform and process the data set.


Leave a Reply

Your email address will not be published. Required fields are marked *