18 May 2020

Lexical functional programming — jargon and naming convention

See all blog posts

Heraclitus said that everything flows. The reactive paradigm followers like to say that everything is a stream. The phrase attributed to Heraclitus is valid for both functional and reactive paradigms. In the first one, we have pipelines, in the second one - streams. That testifies to the significant similarity between these paradigms and shows that reactive programming (but more FRP) is, in fact, an asynchronous implementation of a functional flow.

Lexical functional programming Straal

There are many studies on the subject of functional programming. However, finding noteworthy resources about naming or specific inspiring conventions is quite a challenge. It requires a healthy dose of creativity and often turns out to be far more complicated than it might seem at first glance.

How to standardize descriptive names?

Good programmers give functions descriptive names so that when we see the code, we can see the function names and understand what the function does.  — Eric Elliott, “Master the JavaScript Interview: What is a Pure Function?”

In essence, I’ve observed that many programmers have a problem with descriptive names. The style guide that my colleagues from Straal and I have created is a fulfillment of our experience and expectations, presenting a ready set of good practices and restrictions in our projects. It makes our code reviews much easier and effectively tackles issues such as naming dilemmas.

The article that you read is an analysis of our style guide, and you can find it on our GitHub repository. Besides, we apply strict ESLint rules, which are complementary to this style guide.

Why “Lexical functional”?

“Composition is a powerful tool for abstraction that transforms imperative code into more readable declarative code" — Kyle Simpson, “Functional-Light JavaScript”

The declarative composition is essential for understanding what FP is, but we’ll go one step ahead and think about the naming structure in our functions.

The inspiration for the title is “Lexical functional grammar”, which provides a specific grammar framework to focus on the syntax of multiple dimensions of the linguistic structure.

“Functional” is something more than just a common phrase — it’s a connection of both ideas to focus on specific problems for code writing. In this article, you will see the jargon and structures to the naming convention in the FP-inspired world. Sometimes I use specific FP-terms in brackets to provoke your curiosity or wink knowingly at those already familiar with them.

Constants only

code 1

It’s worth pointing out that constants are the strictest declaration. This is the first step in avoiding mutations because using other variable declaration can result in side effects appearing quickly.

For boolean values describing a state of something we mostly use the following convention:

code 2

As you see we have the following scheme for the functions with a specific role (I describe this part in detail in further sections):

code 3

Why do we use const operators in this case? Because it provides the temporal dead zone and helps to take care of a correct order in the code.

Operations and operator functions

code 4

The above scheme could be a base for most of your problems in a naming dilemma. As you see, our composition includes target collection (also known as a functor because it is mappable), reducer (an operator function), and optional argument — in this case “accumulator”.

Let’s start from “reduce” — the word is a verb which indicates an action, so it is an operation — a declaration with defined scopes per argument with all the information on what that function does.

We also have an operator called “reducer” (or “iteratee”) — a noun, which means it’s a role that provides functionality to realize “reduce” operation, we called it an operator function.

“Reduced” is an adjective and indicates that something has been completed — it is a result of our process.

Let’s check implementations of reduction in Lodash and vanilla JS — as you can see, that that terminology is nothing innovative and you have probably seen it before. Now it’s time to use it more consciously and look for analogies in your code.

For a more “lexical” way, we can use it in our code as a suffix — then you always know what the role of each of the individual variables is:

code 5

In the sort functions (“union”, “sort”), the invoke function per element is called a comparator. For “filter”, “some”, “find”, and similar operations (using probably pure functions) we use predicate function called checker or just predicate:

code 6

In the next part of the article, you can see we use that convention totally in all cases.

Pipelines

Pipelines are a handy thing to a flow between functions. It’s an essence of functional programming.

Pipe (or compose in the opposite direction) as a functional pipeline:

code 7

Pipe operator in a reactive stream:

code 8

Both ways - reactive and functional use the same concept of a pipe. The main difference is, of course, the approach to synchronicity.

Curry and partial

Forget about “this”, “apply”, and “call” methods. Everything you need is a flat description of flow and proper declarations that express your control flow with the partial transmission of arguments:

code 9

We have extended the example of reducing called “curriedReduce” (we can also call it “reduction”) — it means that you have to execute that function to end the process. Pay attention to vocabulary — call your curried functions “curriedSomething” or as an ongoing process (like in this case, “reduction”).

We can also create curried setters with predefined arguments or change the order of execution and use partial. The result of the implementation of both functions will be the same:

code 10

For a simple merging, “spread operators” will be enough. For more involved, you should remember about avoiding mutations on your reference, use Lenses, or immutable library like Immutable.js.

The analogic situation with getter functions:

code 11

Avoid if/else

Instead of them, you can use conditional (ternary) operators and cond functions. That increases clarity, and helps to avoid imperative chaos in your code.

Conditional (ternary) operators — the condition can be a predicate (returns true or false) or boolean (e.g. hasFoo):

code 12

A better choice for more complicated cases:

code 13

Objects

We have three typical use cases: dictionaries, switches, and factories.

Dictionaries

We use dictionaries just like in other languages to keep key/values:

code 14

Switches

In most cases, we can replace typical JS Switch (with break/return) by cond operation function. But in this case, any conditional will be executed if none of them comes true. In some extreme situations, getting a specific function by a key value is a better choice. The following code shows behaviour similar to a classical switch.

code 15

Factories

We use neither classes nor constructors. Factories are functions that create objects of any kind— singleton or instances. The term “middleware” is used to define the factory function with partial arguments, e.g., initial options. Our implementation of Factory is quite specific — we don’t use this (to use more explicit contexts and for more FP-friendly style), so you can’t chain methods, but you can use the pipeline:

code 16

Reactive streams

It’s customary to use a “$” suffix in streams. We distinguish two types of observables: hot and cold — everything will be more apparent with the rules below.

Hot observables:

Hot observables are independent of subscribers — it can emit some changes without an observer. In this case, we use suffix ‘Dispatcher’ because we use them like a singleton — for one event, we have only one declaration on the whole code and reuse it by importing:

code 17

Cold observables:

In any other case, the observable will be cold:

code 18

Stream creators:

For functions that create a new observable:

code 19

Summary

I know that the topic has not been exhausted, yet hope that the analysis of tools and approaches will be helpful and useful for you. I hope that you enjoy the presented proposition of a solution for a common problem of many teams — a naming inconsistency in code. If you have any ideas for improvements, feel free to leave me a comment.

If you have seen that you can improve some of this, I’m waiting for your comment, or you can think about your own “lexical guide”.

Spread the word!

What’s next?

For more information about FP I can recommend these lectures:

“Functional Light JavaScript” by Kyle Sympson

“Composing Software: The Book” by Eric Elliot

“Functional Programming Jargon”

Aleksander Kućma

JavaScript Tech Lead

Aleksander is an admirer of spiritual expression that in JS translates into a functional and reactive paradigm. His curiosity about the world has enhanced by a front-end passion and the need to eternal improving everything around him.

At Straal, Aleksander Kućma is a technical lead of Front-end developers team and is responsible for technical aspects for front-end and JavaScript language.

Before joining Straal, he spent many years as a developer at Grupa Wirtualna Polska and Grupa O2.

You might also like...
Merchants to follow #1: Piesotto. Polish Pioneers of Pet Food Subscriptions
27 May 2020

Learn how Piesotto - a company founded by some true dog lovers out of genuine care for their four-footed “kids” - has become a leading subscription-based pet food supplier in Poland and one of the cutest brands we have ever seen.

Read more
C2B Bank Accounts. Filling the Missing Link to the Open Banking Revolution
29 April 2020

The Open Banking Revolution is happening right now. When it comes to online payments, initiating transactions via banking APIs is undoubtedly a gamechanger for the whole ecosystem. But access to tech-savvy corporate banking is limited. Fortunately, challenger banks come to the rescue. Here is what you need to know.

Read more
Ecommerce Management Issues Most Entrepreneurs Forget About: Part II
20 April 2020

In my previous entry, I listed several strategic ecommerce issues omitted by most mid-sized businesses when launching online sales. You already know that most of the starting-point mistakes result from treating an online shop just like another physical store. Here goes the second part where you’ll find even more topics to tick on your strategic to-do list.

Read more
Ecommerce Management Issues Most Entrepreneurs Forget About: Part I
6 April 2020

Ever more companies develop online sales channels, also in traditionally offline industries. Big players apply advanced ecommerce management strategies, which increase the chances of e-success, but smaller entities tend to neglect the strategic part. In this entry, I explain why it’s a mistake and what strategic issues to mind in the context of ecommerce management.

Read more
Choosing Payment System for MaaS App: What to Remember
3 March 2020

The MaaS market is one of the most prominent beneficiaries of the development of digital economy. MaaS apps have not only changed the way people commute but also how they pay for it. Increasingly often, payments affect the competitiveness of MaaS companies. What makes payment solutions so important for the MaaS industry, and what to mind while choosing a payment platform for a mobility system?

Read more
In Search of an International Payment Gateway
6 February 2020

The decision to start selling internationally is a big step for every company. There’s much more strategic planning involved in the process than it may seem at first glance. One of the technical challenges that online merchants face is the choice of an international payment gateway. How to pick the right one? What features matter most when selling internationally? I’ve listed them for you.

Read more
5 Subscription Business Trends to Watch in 2020
8 January 2020

2019 was another year of massive migrations to the subscription-based business model. The subscription market has grown substantially, taking over nearly all product and service categories one can think of. Nonetheless, it has not saturated yet, and every subscription business owner should keep track of the tendencies shaping consumer habits. What to expect in 2020? See our list of major trends!

Read more
5 Vendor Lock-In Strategies for Your Online Business
18 December 2019

Why do you keep using Android despite its common errors? Or not change your bank although its mobile app drives you crazy? The answer is simple: you’ve been locked-in. If you want to retain your customers with the same effectiveness, take a look at our 5 vendor lock-in strategies crafted for online businesses and take advantage of the lock-in effect and switching costs management!

Read more
How (and Why) Subscription Model Works
27 November 2019

You may have heard about the ongoing subscription boom. Every month, more and more subscription-based companies enter the market. Some of them change the rules of the game while other disappear in no time. Go through this entry to learn how to join the former: embrace the subscription business model with all of its pros and cons, and translate this knowledge into profitable decisions!

Read more
KYC: What Does it Mean in Online Payments?
5 November 2019

Once you have gone through dozens of websites explaining how to open an e-store, terms such as KYC or merchant onboarding may ring a bell with you. You will deal with them before jump-starting your online business, so understanding what they mean in advance is going to save you much time. What is KYC in the context of online payments and how does it relate to the merchant onboarding procedure?

Read more
Prepaid vs. Postpaid: Models Comparison
10 October 2019

Prepaid or postpaid: that is the question. Which payment model should you choose for your business to simplify user experience and boost the company’s revenue? Should your customers add money to an e-wallet and be limited by the amount paid upfront or be charged after every single use of your service? In this blog entry, I compare both approaches using the Mobility-as-a-Service industry as an example.

Read more
How to Prepare Your Website for Online Payments
18 September 2019

Online payments are a must-have in the e-commerce world. Period. The times when you gave the clients your bank account number are far behind us. Once you find your perfect-match payment service provider, you should prepare your website/application for accepting online payments. Why is it so important and what to keep in mind while getting ready?

Read more
What is One-Click Payment and How to Use it Smartly
26 August 2019

Reducing your online checkout process to a single click is tempting, isn’t it? In the face of phenomena such as the *mobile first* approach, demand for instant gratification among young generations of consumers, and conversions taking a matter of milliseconds, one-click payment might seem to be the Holy Grail of modern online commerce.

Read more
What is Subscription Management Software and Why You Need It
5 August 2019

Let’s face it: the subscription-based model provides you with loads of valuable customer data but, unless you hire a full-time data analyst, it’s impossible to make full use of them. Moreover, managing subscription plans of every single subscriber manually is a real nightmare. That’s why subscription management software has been created. What is it and how to make the most of it?

Read more
Optimizing Card Payments: Smart Retry
19 July 2019

In the face of Subscription Economy, offering your merchandise in the form of a subscription-based service may seem tempting. Before you pivot, however, it is worth getting familiar with technology designed to make recurring payments more effective. Here comes Smart Retry aimed at increasing card authorization rate. How does it work and why should you implement it?

Read more
What to Look for in a Payment Gateway? Part II
19 June 2019

In my previous entry, I have proposed some basic questions an online merchant should ask before selecting a payment gateway. If you run a subscription-based business, you should get acquainted with several extra questions specific to your business model. A subscription-friendly payment gateway is a way to gain higher control over your business.

Read more
What to Look for in a Payment Gateway? Part I
10 June 2019

If you’re reading this, you’re probably searching for the best tool to collect payments from your customers and need to understand the differences between diverse solutions available on the market. Here’s a brief guide to selecting the right payment gateway for your online business.

Read more
Subscription Metrics to Track and Optimize
9 May 2019

Customer retention is paramount for companies operating in the subscription-based model. One should learn how to measure it and make the most of the statistics at hand. What subscription metrics to track? And how to convert them into actionable insights?

Read more
Predicting Your Subscriber’s Behavior
25 April 2019

Despite the uniqueness of every customer, the purchasing process they carry out doesn’t vary so much from one to another: they follow specific patterns. The marketing concept of customer lifecycle can help you improve your commercial effectiveness. Learn how to make the most of your subscribers' behavior analysis.

Read more
New Chargeback Thresholds – Don’t Panic. Get Ready.
15 April 2019

As of October 1st, 2019, Visa, the world’s largest card organisation, is updating its fraud and chargeback monitoring policy. Will it affect you? If you accept cards online – it certainly will. Should you be concerned? Not necessarily, if you have a well-thought risk management strategy. If, however, you do not yet have any fraud prevention mechanisms on board, you better hurry up in getting some.

Read more
Customer Transaction Costs and How to Cut Them
28 March 2019

Selling is all about addressing your customers’ needs. Offline or online, you seek to get to know your clients and offer them what they’re looking for. However, it’s a human thing that we like when things go quickly and effortlessly. On the internet, we can shop the way we like: saving our time and effort. But is it enough to let your customers buy online? Can you still make their shopping experience less absorbing?

Read more
6 Subscription Business Trends for 2019
30 January 2019

2018 was without a doubt prosperous for subscription businesses. The model has matured, evolved and boldly developed in a number of new industries and markets. Here’s a list of 6 trends that will have the greatest impact on companies operating in the subscription model in 2019: trends one cannot afford to overlook if they aim high on this promising yet ever more competitive market.

Read more
Anything-as-a-Service: the Future of Distribution
16 January 2019

Anything-as-a-Service (or XaaS) is a product distribution model, where companies shift from selling products to providing their value proposition as a service. Since XaaS can, quite literally, be anything, it isn’t hard to get lost in the jumble of buzzwords, jargon and concepts. This brief article will help you get an in-depth understanding of the new, service-based economy.

Read more
4 Tips to Win the Holiday Shopping Season
22 November 2018

Whilst Black Friday and Cyber Monday, or “Black Friday Weekend and Cyber Week” according to some experts, do not mean as much as, say, 2-3 years ago, the pre-x-mas shopping spree is still among the key determinants of the thickness of your top line. Here’s how to - in the realm of intangible merchandise - make the most of the daddy of all holiday sales.

Read more
3 Tips to Grow Your Online Business
15 October 2018

Simplicity of User Experience, efficient billing model and a well-thought risk management strategy. These are the keys to unlock your business potential on the ever more competitive market of digital services, as uncovered by e-commerce professionals at the very first edition of Warsaw Ecommerce Tech Sessions (WETS) – a new series of meetups powered by Straal and Business Link.

Read more
Your Business in the Face of Fraud
17 July 2018

Have you fallen victim to fraud? If the answer is "yes", I assume you have learnt your lesson and already thoroughly inspected what went wrong. The “no” answer does not exist in the case of fraud. It’s only “not yet”. Be my guest and let me invite you to explore the dark side of ecommerce.

Read more
Is the Freemium Strategy Right for Your Startup?
20 May 2018

Look at you, a fledgling entrepreneur at the threshold of international success. I bet it feels fantastic to see your idea come to life. So now that you’re inevitably positioned for success, give your product away for free - that's how the freemium model works. But is it really that simple?

Read more
When One Second Costs $2.5 Million
17 April 2018

Your customers won’t wait or engage in cumbersome processes to get your products and - if your competitors are able to provide the service faster – why would they? Straal presents the mathematics of instant e-commerce. Lean on these statistics to put your business in the fast lane!

Read more
The Essentials of Subscriber Experience
28 February 2018

In the times of flourishing sharing economy, we’re renting, sharing and getting access to everything we need. The line between products and services is becoming thinner and thinner, whereas possession is no longer guarantee for the customer satisfaction. What is in that case?

Read more
4 Reasons to Migrate to the Subscription Business Model
8 February 2018

Do you remember the first time you sold your product or signed a contract for your service? I bet it felt good. Do you know what feels even better? Becoming a trusted provider of your services and products to your loyal customers. That lasting feeling is what the subscription-based business model holds in store for success-hungry entrepreneurs.

Read more
3 Must-knows about the Role of Payment Solutions
16 January 2018

How do payment solutions chosen by your company influence your business performance? It's important to decide on such that will not only meet your current requirements but also support your development strategy in the long term and smoothly scale your business.

Read more
5 Things You Should Know about the Payment Ecosystem
30 November 2017

Fintech insiders oftentimes erroneously assume that consumers, let alone merchants, know much more about the payment ecosystem than they actually do. This might lead to disturbing misunderstandings, make companies miss business opportunities, consumers get a headache and vendors fritter away their marketing budgets.

Read more
Show more releases