return first

Let me introduce the “return first” method? Fear not, this is not a treatise on guard-clauses. What it is, is both a code design approach and a refactoring method. It starts with a simple question to ask yourself whenever you want to call a function:

Can I return first?

That’s supposed to be catchy, but it is probably not terribly enlightening. Let me demonstrate with an example. I’ll be using C++, but I dare say that this method can be used in all imperative languages.

```void process_all(
std::vector<input_info_t>& input_list,
context_t const& context,
target_t const& target)
{
for (auto& each : input_list)
{
if (some_filter_applies(each, context))
{
hand_off_to(each, target);
continue;
}

process_one(each, context);
hand_off_to(each, target);
}
}
```

For the sake of this example, the three functions `some_filter_applies`, `process_one` and `hand_off_to` are immutable. Let us try to improve `process_all` by extracting a function:

```void maybe_process_and_hand_off(
input_info_t& input,
context_t const& context,
target_t const& target)
{
if (some_filter_applies(input, context))
{
hand_off_to(input, target);
return;
}

process_one(input, context);
hand_off_to(input, target);
}

void process_all(
std::vector<input_info_t>& input_list,
context_t const& context,
target_t const& target)
{
for (auto& each : input_list)
{
maybe_process_and_hand_off(each, context, target);
}
}
```

So what do we have now:

1. 26 instead of 17 lines. 22 instead of 13 if we do not count lines with just braces, a 70% increase.
2. A pretty clumsy name for the function called in the loop. Can you do better?
3. We have to pass the `target` all the way to `hand_off_to` without really using it directly in `maybe_process_and_hand_off`.
4. The complexity is more or less the same.

So that was not great. So let us try to use return first and focus on `hand_off_to`. What if instead of calling `hand_off_to`, we just return first, and then do it? In this case, it’s pretty easy, since `hand_off_to` is a tail-call in each case:

```void maybe_process(
input_info_t& input,
context_t const& context)
{
if (some_filter_applies(input, context))
{
return;
}

process_one(input, context);
}

void process_all(
std::vector<input_info_t>& input_list,
context_t const& context,
target_t const& target)
{
for (auto& each : input_list)
{
maybe_process(each, context);
hand_off_to(each, target);
}
}
```

Now we no longer have to pass target through a function that does not need it, which makes both the call site and the function declaration simpler. Now a few more other refactorings are available. Let’s assume some_filter_applies is pure and process_one only changes its input parameter, as the signatures suggest. We can use loop fission, and inline the function again:

```void process_all(
std::vector<input_info_t>& input_list,
context_t const& context,
target_t const& target)
{
for (auto& each : input_list)
{
if (some_filter_applies(each, context))
{
continue;
}

process_one(each, context);
}
for (auto const& each : input_list)
{
hand_off_to(each, target);
}
}
```

“return first” actually works for all control structures, not just functions. So in this case we returned from the first loop before starting to call `hand_off_to` multiple times. Often times, the code will not be as easy to refactor, because there is actually some data flowing between the function we’re in and the one we’re calling. The simple solution then is to pack all the parameters into a struct and return that, aka using data as the interface instead.

```void hand_off_individually(
std::vector<input_info_t>& input_list)
{
for (auto& each : input_list)
{
auto target = compute_target(each);
if (!target.valid())
continue;

hand_off_to(each, target);
}
}
```

That be turned into this:

```void hand_off_individually(
std::vector<input_info_t> const& input_list)
{
struct targeted
{
input_info_t info;
target_t target;
};
std::vector<targeted> valid;
for (auto const& each : input_list)
{
auto target = compute_target(each);
if (!target.valid())
continue;
valid.push_back({each, target});
}

for (auto const& each : valid)
{
hand_off_to(each.info, each.target);
}
}
```

This is definitely longer, and probably not worth the hassle for this contrived example – this is more to show how to do it, not that is is effective.

Evaluation

In real programs, this applying “return first” is often worthwhile. It makes the code flow “wider instead of deeper”, which is often easier to follow, especially if you try to debug or measure/profile your code. It is also a gold-recipe to enable batching, which is curcial whenever you’re dealing with latency, e.g. when using RAM or building web requests. Have you tried this technique before? Do you, maybe, know it by another name? Do tell!

3 good uses for the C++ preprocessor in 2020

As this weird year, 2020, comes to a close, I noticed that I am still using the preprocessor in my C++ programs. And not just for `#include`s which might, at last, slowly fade away with C++20’s modules. The preprocessor’s got a pretty bad rep, and new C++ programmers are usually taught to stay as far away as possible. Justifiably so – some things, like the dreaded X-Macros really should go the way of the dinosaurs.

But there are still some good uses left in the thing, and here’s my top 3 of those:

0. Commenting out big-chunks of code

I’ve often seen people comment out big parts of code with block comments: `/* this is not active */`. However, that will only work as long as the code does not contain any other block comments, let alone a stray `*/` in a string. A great alternative is to use the preprocessor:

```#if 0
auto i_do_not_want_to_compile_this() -> auto
{
std::vector<std::deque<std::mutex>> baz{};
return baz;
}
#endif
```

This can easiely by wrapped multiple times around bigger parts of code, which is very helpful when refactoring large chunks of legacy code. It can very easiely be toggled on and off while in this state. And the IDE will usually still show a dimmed version of syntax highlighting in the disabled region.

1. Conditionally throw away “cross-cutting” concerns

Some parts of aspects of programs can be “cross-cutting”, which means they cannot easiely be separated from the rest of the code-base by putting them in a separate module. The most prominent example is probably logging. While you can typically modularize the actual implementation, the actual log calls will be all over your code. Another of those concerns is “profiling”. This is also something that you typically want to take out of your application when deploying it, because users will rarely profile the end-product. Again, the preprocessor comes to the rescue. For example, in the excellent Optick, most of the code you insert is actually macros that can be completely eliminated with a simple compile-time switch. Consider this “tag” that add some additional metric to your profile:

```OPTICK_TAG("CoolMetric", compute_cool_metric());
```

When Optick is turned off via the aforementioned compile-time switch, `compute_cool_metric()` is never called. The call is not even compiled. Just turning Optick off will completely remove it from your source. Now this can be potentially dangerous, if the function has a side effect, but you wouldn’t do that anyways, would you?

2. Making forward declarations more visible

Presumably owing to its history as a continuously-evolved language, C++ has a very limited set of reserved keywords, often avoiding to introduce keywords to not interfere with any working software out there. Do not get me wrong, that is a great reason. But because of this, some language constructs can sometimes be a bit cryptic, for example forward declarations: `class will_be_defined;`. If you ever worked with a big, old or big and old code-base with lots of those, you probably know that maintaining them can be a bit of a chore and prone to error. So I think it is a great idea to at least make them more visible with your own macro “KEYWORD”:

```#define FORWARD_DECL(x) class x

FORWARD_DECL(will_be_defined);
```

That `FORWARD_DECL` immediatly stands out visually and helps me keep track of those subtle declarations.

Bridging Eons in Web Dev with Polyfills

Indeed, web development is kind of peculiar. On the one hand, there‘s seldom a field in which new technologies overturn each other at that pace, creating very exciting opportunities ranging from quickly sketching out proof-of-concepts to the efficient construction of real-world applications. On the other hand, there is this strange air of browser dependency and with any new technology one acquires, there‘s always the question of whether this is just some temporary fashion or here to stay.

Which is why it hapens, that one would like to quickly scaffold a web application on the base of React and its ecosystem, but has the requirement that the customer is – either voluntarily or forced by higher powers – using some legacy browser like Internet Explorer 11, for which Microsoft has recently announced its end of life support for 30th November this year. Which doesn’t sound nice for the… *searching quickly* … 5% of desktop/laptop users that still use this old horse, but then again, how long can you cling to an outdated thing?

For the daily life of a web developer, his mind full of peculiarities that the evolution of the ECMAScript standard which basically is JavaScript, there is the practical helper of caniuse.com, telling you for every item of your code you want to know about, which browser / device has support and which doesn’t.

But what about whole frameworks? When I recently had my quest for a IE11-comptabile React app, I already feared that at every corner, I needed to double-check all my doing, especially given that for the development itself, one is certainly advised to instead use one of the browsers that come with a quite some helpful developer tools, like extensions for React, Redux, etc. — but also the features in the built-in Console, where it makes your life a lot easier whether you can just log a certain state as a string of “[Object object]” or a fully interactive display of object properties. Sorry IE11, there are reasons why you have to go.

But actually, then, I figured, that my request is maybe not that far outside the range of rather widespread use cases. Thus, the chance that someone already tried to tackle the problem, aren’t so hopeless. And so this works pretty straightforward:

• Install “react-app-polyfill”, e.g. via npm:
```npm install react-app-polyfill
```
• At the very top of your index.js, add for good measure:
```import "react-app-polyfill/ie11";
import "react-app-polyfill/stable";
```
• Include “IE 11” (with quotes) in your package.json under the “browserlist” as a new entry under “production” and “development”

That should do it. There are people on the internet that advise removing the “node_modules/.cache” directory when doing this in an existing project.

The term of a polyfill is actually derived from some kind of putty, which is actually a nice picture. It’s all about allowing a developer to use accustomed features while maintaining the actual production environment.

Another very useful polyfill in this undertaking was…

```// install
npm install --save-dev @babel/plugin-transform-arrow-functions

// then add to the "babel" > "plugins" config array:
"babel": {
"plugins": [
"@babel/plugin-transform-arrow-functions"
]
}
```

… as I find the new-fashioned arrow function notation quite useful.

So, this seems to bridge (most of) the worries one encounters in this web dev world where use cases span eons of technology evolution. Now, do you know any more useful polyfills that make your life easier?

Crashes when returning references to vector elements

Recently, I was experiencing a strange crash that I traced to a piece of C++ code looking more or less like this:

```template <class T>
class container
{
public:
std::vector<T> values_;
T default_;

T const& get() const
{
if (values_.empty())
return default_;
return values.front();
}
};
```

This was crashing when calling `get()`, with a non-empty `values_` member. It looks fairly innocent. And it ran in production for a couple of years already. So what changed?

I had, in fact, never instanciated this template with `T = bool` before. And that was causing the crash, while still compiling without any errors. Now if you’re a little versed in the C++ standard library you might know that std::vector is a special snowflake indeed. In an effort to save space, and, I suspect, prove the usefulness of template specializations, it is not really a “normal” container holding bool values. Instead, it holds some type of integers and packs each pseudo-bool into one of their bits. The consequence is that the accessor functions like `operator[]`, `front()` and `back()` cannot return a reference to a bool. Instead, they return a “proxy” object that supports assignment to and from a bool.

Back to the `get()` function: it tries to return a reference to a bool. Of course, that bool doesn’t really exist except as a temporary, and so this results in a dangling reference that causes a segmentation fault when used.

I suspect there could have been a warning about a dangling reference somewhere there. I have seen clang-tidy especially report things like this (with a few false positives too), but it did not show up for me. To fix it, I am now just returning a `bool` instead of a `bool const&` for `T = bool`. A special case in my case to work around a special case in `std::vector`.

Co-Variant methods on C# collections

C# offers a powerful API for working with collections and especially LINQ offers lots of functional goodies to work with them. Among them is also the `Concat()`-method which allows to concatenate two `IEnumerables`.

We recently had the use-case of concatenating two collections with elements of a common super-type:

```class Animal {}
class Cat : Animal {}
class Dog : Animal {}

public IEnumerable<Animal> combineAnimals(IEnumerable<Cat> cats, IEnumerable<Dog> dogs)
{
// XXX: This does not work because Concat is invariant!!!
return cats.Concat(dogs);
}
```

The above example does not work because concat requires both sequences to have the same type and returns a combined sequences of this type. If we do not care about the specifities of the subclasses be can build a `Concatenate()`-method ourselves which make the whole thing possible because instances of both subclasses can be put into a collection of their common parent class.

```private static IEnumerable<TResult> Concatenate<TResult, TFirst, TSecond>(
this IEnumerable<TFirst> first,
IEnumerable<TSecond> second)
where TFirst: TResult where TSecond : TResult
{
IList<TResult> result = new List<TResult>();
foreach (var f in first)
{
result.Add(f);
}
foreach (var s in second)
{
result.Add(s);
}
return result;
}
```

The above method is a bit clunky to call but works as intended:

```public IEnumerable<Animal> combineAnimals(IEnumerable<Cat> cats, IEnumerable<Dog> dogs)
{
// Works great!
return cats.Concatenate<Animal, Cat, Dog>(dogs);
}
```

A variant of the above is a `Concatenate()`-method can be useful if you use a collection of the parent class to collect instances of subclass collections:

```private static IEnumerable<TResult> Concatenate<TResult, TIn>(
this IEnumerable<TResult> first,
IEnumerable<TIn> devs)
where TIn : TResult
{
IList<TResult> result = first.ToList();
foreach (var dev in devs)
{
result.Add(dev);
}
return result;
}

public IEnumerable<Animal> combineAnimals(IEnumerable<Cat> cats, IEnumerable<Dog> dogs)
{
IEnumerable<Animal> result = new List<Animal>();
result = result.Concatenate(cats);
return result.Concatenate(dogs);
}
```

Maybe the above examples can serve as an inspiration for more utility methods that may improve working with collections in C#.

Changing the keyboard navigation behaviour of form inputs

The default behaviour in HTML forms is that you can move the focus from one input element to the next via the tab key and submit the form via the enter key. This is also how dialogs work on most operating systems when using the native UI components. This behaviour is consistent across all browsers, and changing it messes with the user’s expectations and reduces accessibility. So I would normally advise against changing this behaviour without good reasons.

However, one of our customers wanted a different behaviour for an application developed by us. This application replaced an older application where the enter key did not submit the form, but moved the focus to the next input element. The ‘muscle memory’ effect made users accidentally submit the form by hitting the enter key, causing frustration. Since this application is not a public web site, but merely a web technology based intranet application with a small and specialized user base, changing the default behaviour is acceptable if the users want it.

So here’s how to do it. The following JavaScript function `focusNextInputOnEnter` takes a form element as a parameter and changes the focus behaviour on the input elements within this form.

```function focusNextInputOnEnter(form) {
var inputs = form.querySelectorAll('input, select, textarea');
for (var i = 0; i < inputs.length; i++) {
var input = inputs[i];
input.addEventListener('keypress', (function(index) {
return function(event) {
if (!isEnter(event.which)) {
return;
}
var nextIndex = index + 1;
while (nextIndex < inputs.length) {
var nextInput = inputs[nextIndex];
if (nextInput.disabled) {
nextIndex++;
continue;
}
nextInput.focus();
break;
}
};
})(i));
}

function isEnter(keyCode) {
return keyCode === 13;
}
}
```

It works by handling the `keypress` events on the input elements and checking the key code for the enter key (code 13). It has an additional check so that disabled input elements are skipped.

To apply this change in behaviour to a form we have to call the function when the DOM content is loaded:

```<form id="demo-form">
<input type="text">
<input type="text" disabled="disabled">
<input type="checkbox">
<select>
<option>A</option>
<option>B</option>
</select>
<textarea></textarea>
<input type="text">
<input type="text">
</form>

<script>
document.addEventListener('DOMContentLoaded', function() {
focusNextInputOnEnter(document.getElementById('demo-form'));
});
</script>
```

I want to reiterate my warning that you should definitely not do this for public web sites, and elsewhere only if you know that this is what your users want.

Using (elastic)search with .NET Core

Many modern applications require powerful search mechanisms to become useful and make their users more productive. That is in large part due to the amount of data available to work with. Thankfully there are already powerful tools to index your data and make it searchable.

One of the most well known state-of-the-art solutions is ElasticSearch and it has an API to be used from .NET called NEST. While the documentation is ok I want to give a quick rundown on how to add searching capabilities to your .NET Core application. Some ideas are borrowed from the great post “Using Elasticsearch with ASP.NET Core and Docker“.

Getting ElasticSearch running

The easiest way to get up and running with elasicsearch is to use their docker images and just run the container on your development machine. I like to a docker compose file like the following to get elasticsearch and its tooling application kibana up and running fast:

```version: '3.8'
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:7.8.0
container_name: elastic
environment:
- node.name=elastic
- cluster.initial_master_nodes=elastic
ports:
- "9200:9200"
- "9300:9300"
volumes:
- type: bind
source: ./esdata
target: /usr/share/elasticsearch/data
networks:
- esnetwork
kibana:
image: docker.elastic.co/kibana/kibana:7.8.0
ports:
- "5601:5601"
networks:
- esnetwork
depends_on:
- elasticsearch
volumes:
esdata:
networks:
esnetwork:
driver: bridge
```

After you run it with docker compose you can talk to the search service on http://localhost:9200/ and the kibana management GUI on http://localhost:5601/. On the Kibana UI especially the Dev Tools and its console are interesting for experimenting with search queries.

Access ElasticSearch from your .NET Core app

I find it quite elegant to write a extension method for the IServiceCollection to configure the ElasticClient and register it as a Singleton to the dependency injection framework of .NET Core like so

```    public static class ElasticSearchExtension
{
public static void AddElasticsearch(
this IServiceCollection services, IConfiguration configuration)
{
var url = configuration["elasticsearch:url"];
var settings = new ConnectionSettings(new Uri(url))
.DefaultMappingFor<SearchableDevice>(deviceMapping => deviceMapping
.IndexName("devices")
.IdProperty(dev => dev.Id)
)
;
var client = new ElasticClient(settings);
var response = client.Indices.Create("devices", creator => creator
.Map<SearchableDevice>(device => device
.AutoMap()
)
);
// maybe check response to be safe...
services.AddSingleton<IElasticClient>(client);
}
}
```

The configuration block looks like following

```  "ElasticSearch": {
"url": "http://localhost:9200/"
},
```

and allows for future extension.

Our search service has to be registered in `Startup `of course:

```public void ConfigureServices(IServiceCollection services)
{
...
services.AddElasticsearch(Configuration);
}
```

Indexing our objects

In the above example we built a SearchableDevice class whose public properties are going to be indexed by ElasticSearch. The API allows for a much more fined grained control about what and how to index but we want to keep things simple without having to worry about excluding Properties and so on. If you have set it up that way indexing a `SearchableDevice `is merely one simple call:

```// SearchClient is the injected IElasticClient
// mySearchableDevice is an instance of SearchableDevice
SearchClient.IndexDocument(mySearchableDevice);
```

Searching for objects

When developing a search query I like to try it in the Kibana Dev Tools and then transform it to a NEST call. A simple query to look in all device properties if they start with “needle” looks like this:

```{
"query": {
"multi_match": {
"type": "phrase_prefix",
"fields": ["*"],
"query": "needle"
}
}
}
```

The nice thing about the Kibana Dev Tools console is that it can display and complete the possible values for fields like “type” in your multi_match query.

That search query can then be translated to a NEST call in a straightforward way and looks this way:

```var response = SearchClient.Search<SearchableDevice>(sd => sd
.Query(q => q
.MultiMatch(query => query
.Type(TextQueryType.PhrasePrefix)
.Fields("*")
.Query("needle")
)
)
);
```

The search response contains the hits with their source objects and some metadata like the score and result count.

Bear in mind that ElasticSearch only returns the first/best 10 matches by default, so specifying the result size often might be closer to what you want.

Wrapping it up

Getting started with ElasticSearch in .NET Core does not require too much boiler plate an setup work if you use tools like docker and the NEST library. Making it usable and tuning the indexing and querying may require a lot of work to achieve the best results. On the other hand smaller applications can start-off with a simple search setup like shown above and simply evolve it when need be.

State Management for emotionally overwhelmed React rookies

State Management for overwhelmed React rookies

The topic of React state management is nowhere near new. Just to be safe what we‘re talking about here: Consider a multitude of components, which, in nice React-fashion, are finely interleaved into each other, each one with a Single Responsibility, each one only holding as much information as it needs. Depending on the complexity of your application, there can now be a lot of complex dependencies, where one small component somewhere might cause another small component totally-elsewhere to update (re-render), without these having to really know much about each other, because we strive for Low Coupling. In front-end development, this is not only done in terms of „cleaner code“, but also in the performance problem of having to re-render stuff that is not actually changing.

So, just a few months back, a new competitor appeared in the question of React state management, which was open-sourced by Facebook and is called Recoil. The older top dog in this field is the widely-used Redux, with smaller interventions of libraries like MobX, that also aimed to offer an alternative of managing state in smaller applications, and when React in version 16.3 opened up a new standard of Context API, it already officially advanced quite a step into the direction of an official React solution to these questions.

There‘s probably not a single web developer on earth who wouldn‘t agree that in our field, one of the most fun…fundamental challenges is the effort of staying afloat on top of the turbulent JavaScript-osphere. If you are the type of person who doesn‘t want to jump on every bandwagon, but still don‘t want to miss out on all the amazing opportunities that all this progress could give you, you better start a bunch of side projects (call them „recreational“ if you like) and give yourself a chance to dive into particular technologies with confined scope, for some research time.

This is what I‘ve done now and I try to focus completely on the issues that an ambitious developer can experience when having all these choices. This is what I want to outline for you now, because as usual – if you have lots of time studying a single technology, you can succeed in spite of many limitations, and you also get used to certain kinds of things you might have to do that you originally didn‘t want to do, and so on and so on.

So with Redux, nobody really appeared to talk a lot of bad things about it and there even are some Mariuses who seem to be absolutely in love with the official Redux documentation, that are actually more of a guide to time-tested Best Practices, giving you the opportunity to do things right and have a scaleable state container which supports you even if your application grows to large dimensions. Then there‘s stuff like a time-travelling state debugger and the flexible middleware integration which I didn‘t even touch yet. When your project has a number of unrelated data structures, there‘s the Ducks pattern that advises you to organize your required Reducers, Actions and Action Creators in a coherently arranged files. Which, however, turned complicated in my one project in which the types of data objects aren‘t as unrelated, and I had to remove all the combineReducer() logic and ended up with one large global state object; I now have one source file that just consists of everything-related-with-redux and for my purpose, this seems fine, but I still have to write rather cumbersome connect(mapStateToProps, mapDispatchToProps) structure in every component in which I want to access the state. I would prefer to have smaller state containers, but maybe it‘s due to the structure of my project that makes these complicated.

It really is that way: Due to the everchanging recommendations that come with the evolution of React, the question of how to do things best (read: best for your specific purpose), always stays fresh. Since React 16.8 and the arrival of Hooks there is a procession towards less boilerplate code, favoring functional components with a leaner appearance. In this spirit, I strived for something less Redux-y. E.g. if I want some text in my state to be set; I would have to do something like

```// ./ducks/TextDucks.js
// avoid having to rely on a magical string, therefore save the string to a constant
const SET_TEXT = 'SET_TEXT';

// action creator
export const setTextCreator = (text) ==> ({type: CLEAR_TEXT, payload: {text}});

const Reducer = (state = initialState, {type, payload}) => {
//... other state stuff
if (type === SET_TEXT) {
return {...state, text: payload.text};
}
}

================
// Component file
import {setTextCreator} from './ducks/TextDucks.js';
const mapDispatchToProps = (dispatch) => ({
setText: text => dispatch(setTextCreator(text));
});
const Component = ({setText, ...}) => {
// here can I actually use setText()
};
export default connect(..., mapDispatchToProps)(Component);
```

Which is more organized than passing along some setText(‘‘) function through my whole component tree, but still feels a bit overhead.

Then there was MobX. Which seemed to be quite lightweight and clearly laid out a coherent use of the Observable pattern, implemented with its own JavaScript decorators that follow a simple structure. Still, however, the lookandfeel of this code would appear to differ quite a lot from my usual coding style, which kept me from actually using it. This decision was then advanced by certain statements online, who, some years ago, actually predicted that the advancement of React’s own Context API would make any third-party library redundant. Now to be fair, React’s current Context API, with its useReducer() and useContext() also makes it possible to imiate a Redux-like structure already, but consider it as ways of thinking: If you write your code in the same style as you would with Redux’ recommendations, why not use it directly? Clearly, the point of avoiding Redux should go towards the direction of thinking differently.

The Context API actually supplies the underlying structure on which Redux’ own <Provider> builds. Insofar, it is not a big astonishment that you can accomplish similar things with it. Using the Context API, you wrap your whole Application like

```// myContext.js
import React from "react";
const TextContext = React.createContext();
export default TextContext;

// App.js
import TextContext from './myContext';
const App = () => <TextContext.Provider value={"initial text"}>{/* actual app components here */}</TextContext.Provider>;

// some subComponent.js
import React from 'react';
import TextContext fom './myContext';
const SubComponent = (props) => {
const [text, setText] = React.useContext(TextContext);
// now use setText() as you would with a local React useState dispatch function..
}
```

Personally, I found that arrangement a bit clearer than the Redux structure, if you ‘re not used to Redux’ way of thinking anyway. However, if your state grows and is more than just a text, you would either keep state information in one large object again, or wrap your <App/> in a ton of different Contexts which I personally disdained already when I just had three different global state variables to manage.

Having all these possbilities at hand, one might wonder why Facebook felt the need to implement a new way of state management with Recoil. Recoil is still in its experimental phase, however, it didn’t take long to find one aspect very promising: The coding style of managing state in Recoil feels a lot like writing React code itself, which itself makes it very smooth to operate, as you don’t have to treat global state much different than local state. Our example would look like this

```// textState.js
import * as Recoil from 'recoil';
export const text = Recoil.atom({key: 'someUniqueKey', default: 'inital text'});

// App.js
import {RecoilRoot} from 'recoil';
const App = () => <RecoilRoot>{/* here the actual app components */}</RecoilRoot>

// some Component.js
import * as TextState from './textState';
const [text, setText] = Recoil.useRecoilState(TextState.text);
// from then on, you can use setText() like you would as a React useState dispatch function
```

Even more simple, with Recoil you directly have access to the single useRecoilValue() function to just read the text value, and the single useSetRecoilState() function to just dispatch a new text. This avoids the complication of having to re-think your treating of whatever-in-your-state-is-global differently from what is local. Your <App/> component doesn’t grow to ugly levels of intendation, and you can neatly organize everything state-related in a separate file.

As someone who considers himself quite eager to learn new technologies, but also wants to quickly see some results without having to learn a lot of fresh basic understanding first, I had the most fun trying out Recoil in my projects, I have to admit. However, I totally believe that the demise of Redux is not closing in that soon at all, due to its focus on sustainability. For the future, I would aim to see my one Recoil project grow, and I keep you updated on how well this grows…

Be precise, round twice

Recently after implementing a new feature in a software that outputs lots of floating point numbers, I realized that the last digits were off by one for about one in a hundred numbers. As you might suspect at this point, the culprit was floating point arithmetic. This post is about a solution, that turned out to surprisingly easy.

The code I was working on loads a couple of thousands numbers from a database, stores all the numbers as doubles, does some calculations with them and outputs some results rounded half-up to two decimal places. The new feature I had to implement involved adding constants to those numbers. For one value, 0.315, the constant in one of my test cases was 0.80. The original output was “0.32” and I expected to see “1.12” as the new rounded result, but what I saw instead was “1.11”.

What happened?

After the fact, nothing too surprising – I just hit decimals which do not have a finite representation as a binary floating point number. Let me explain, if you are not familiar with this phenomenon: 1/3 happens to be a fraction which does not have a finte representation as a decimal:

1/3=0.333333333333…

If a fraction has a finite representation or not, depends not only on the fraction, but also on the base of your numbersystem. And so it happens, that some innocent looking decimal like 0.8=4/5 has the following representation with base 2:

4/5=0.1100110011001100… (base 2)

So if you represent 4/5 as a double, it will turn out to be slightly less. In my example, both numbers, 0.315 and 0.8 do not have a finite binary representation and with those errors, their sum turns out to be slightly less than 1.115 which yields “1.11” after rounding. On a very rough count, in my case, this problem appeared for about one in a hundred numbers in the output.

What now?

The customer decided that the problem should be fixed, if it appears too often and it does not take to much time to fix it. When I started to think about some automated way to count the mistakes, I began to realize, that I actually have all the information I need to compute the correct output – I just had to round twice. Once say, at the fourth decimal place and a second time to the required second decimal place:

```(new BigDecimal(0.8d+0.315d))
.setScale(4, RoundingMode.HALF_UP)
.setScale(2, RoundingMode.HALF_UP)
```

Which produces the desired result “1.12”.

If doubles are used, the errors explained above can only make a difference of about $10^{-15}$, so as long as we just add a double to a number with a short decimal representation while staying in the same order of magnitude, we can reproduce the precise numbers from doubles by setting the scale (which amounts to rounding) of our double as a BigDecimal.

But of course, this can go wrong, if we use numbers, that do not have a short neat decimal representation like 0.315. In my case, I was lucky. First, I knew that all the input numbers have a precision of three decimal places. There are some calculations to be done with those numbers. But: All numbers are roughly in the same order of magnitude and there is only comparing, sorting, filtering and the only honest calculation is taking arithmetic means. And the latter only means I had to increase the scale from 4 to 8 to never see any error again.

So, this solution might look a bit sketchy, but in the end it solves the problem with the limited time budget, since the only change happens in the output function. And it can also be a valid first step of a migration to numbers with managed precision.

A Code Centric World

In main-stream OOP, polymorphism is achieved by virtual functions. To reuse some code, you simply need one implementation of a specific “virtual” interface. Bigger programs are composed by some functions calling other functions calling yet other functions. Virtual functions introduce a flexibility here to that allow parts of the call tree to be replaced, allowing calling functions to be reused by running on different, but homogenuous, callees. This is a very “code centric” view of a program. The data is merely used as context for functions calling each other.

Duality

Let us, for the moment, assume that all the functions and objects that such a program runs on, are pure. They never have any side effects, and communicate solely via parameters to and return values from the function. Now that’s not traditional OOP, and a more functional-programming way of doing things, but it is surely possible to structure (at least large parts of) traditional OOP programs that way. This premise helps understanding how data oriented design is in fact dual to the traditional “code centric” view of a program: Instead of looking at the functions calling each other, we can also look at how the data is being transformed by each step in the program because that is exactly what goes into, and comes out of each function. IS-A becomes “produces/consumes compatible data”.

Cooking without functions

I am using C# in the example, because LINQ, or any nice map/reduce implementation, makes this really staight-forward. But the principle applies to many languages. I have been using the technique in C++, C#, Java and even dBase.
Let’s say we have a recipe of sorts that has a few ingredients encoded in a simple class:

```class Ingredient
{
public string Name { get; set; }
public decimal Amount { get; set; }
}
```

We store them in a simple `List` and have a nice function that can compute the percentage of each ingredient:

```public static IReadOnlyList<(string, decimal)>
Percentages(IEnumerable<Ingredient> incredients)
{
var sum = incredients.Sum(x => x.Amount);
return incredients
.Select(x => (x.Name, x.Amount / sum))
.ToList();
}
```

Now things change, and just to make it difficult, we need a new ingredient type that is just a little more complicated:

```class IngredientInfo
{
public string Name { get; set; }
/* other useful stuff */
}

class ComplicatedIngredient
{
public IngredientInfo Info { get; set; }
public decimal Amount { get; set; }
}
```

And we definitely want to use the old, simple one, as well. But we need our percentage function to work for recipes that have both `Ingredient`s and also `ComplicatedIngredient`s. Now the go-to OOP approach would be to introduce a common interface that is implemented by both classes, like this:

```interface IIngredient
{
string GetName();
string GetAmount();
}
```

That is trivial to implement for both classes, but adds quite a bunch of boilerplate, just about doubling the size of our program. Then we just replace `IReadOnlyList<Ingredient>` by `IReadOnlyList<IIngredient>` in the `Percentage` function. That last bit is just so violating the Open/Closed principle, but just because we did not use the interface right away (Who thought YAGNI was a good idea?). Also, the new interface is quite the opposite of the Tell, don’t ask principle, but there’s no easy way around that because the “Percentage” function only has meaning on a `List<>` of them.

Cooking with data

But what if we just use data as the interface? In this case, it so happens that we can easiely turn a `ComplicatedIngredient` into an `Ingredient` for our purposes. In C#’s LINQ, a simple Select() will do nicely:

```var simplified = complicated
.Select(x => new Ingredient
{
Name = x.Info.Name,
Amount = x.Amount
});
```

Now that can easiely be passed into the `Percentages` function, without even touching it. Great!

In this case, one object could neatly be converted into the other, which is often not the case in practice. However, there’s often a “common denominator class” that can be found pretty much the same way as extracting a common interface would. Just look at the info you can retrieve from that imaginary interface. In this case, that was the same as the original Ingredients class.

Further thoughts

To apply this, you sometimes have to restructure your programs a little bit, which often means going wide instead of deep. For example, you might have to convert your data to a homogenuous form in a preprocessing step instead of accessing different objects homogenuously directly in your algorithms, or use postprocessing afterwards.
In languages like C++, this can even net you a huge performance win, which is often cited as the greatest thing about data-oriented design. But, first and foremost, I find that this leads to programs that are easier to understand for both machine and people. I have found myself using this data-centric form of code reuse a lot more lately.

Are you using something like this as well or are you still firmly on the override train, and why? Tell me in the comments!