Embrace Your Problem Domain With Strong Types!

Published: 05 August 2021
on channel: Utah Cpp Programmers
539
12

Every piece of software we write fits into some sort of specific problem domain. Programming isn't about writing programs! Programming is about solving problems. Every problem we solve comes from some sort of domain that has its own terminology and concepts. Knowledge from the domain appears most obviously in the names of things in our source code: variables, functions, classes, files and so-on. They all need names and we pick names from our problem domain in order to impugn these named entities with meaning.

One area that is often overlooked when modeling our problem domain is coming up with abstractions for the most common and simple values used in our programs. "We need to store a telephone number for the customers in our inventory system." "OK, let's use a std::string, that ought to do it."

That's certainly an expedient solution, but is it a good solution? Think of all the member functions on std::string; do all of them really apply to the concept of a telephone number? For instance, does it make sense to take arbitrary substrings of a telephone number? Think of all the places where a std::string, which can model a container of characters, can be used in the standard library. Do all of those uses make sense for a telephone number? Is there any reason we should be sorting the characters in a telephone number with std::sort? (see https://godbolt.org/z/89WET6WPE)

The way out of this unfortunate situation is to use types that directly represent the values in our problem domain instead of the primitive types provided by the language (int, char, float, etc.) or the standard library (string, map, vector, etc.). With a domain specific type, sometimes called a strong type, we can control which operations are defined for those types and let the compiler alert us when we are misusing our domain values in ways that don't make any sense.

This month, Richard Thomson will give us a guided tour on how we can write domain specific types in C++. We'll take a look at facilities provided directly by the language to roll our own types and we'll look at some library solutions that save us from writing lots of boiler plate.

Future topics: https://utahcpp.wordpress.com/future-...
Past topics: https://utahcpp.wordpress.com/past-me...


Watch video Embrace Your Problem Domain With Strong Types! online without registration, duration hours minute second in high quality. This video was added by user Utah Cpp Programmers 05 August 2021, don't forget to share it with your friends and acquaintances, it has been viewed on our site 53 once and liked it 1 people.