Martin
Martin
Apr 1, 2018 · 3 min read

Have you ever typed a word so many times it looks misspelled? As someone who types for a living, I tend to have trouble with this. The beauty of a misspelled word in programming is consistency. If it’s wrong everywhere, it’s right- right? However, loosely typed identifiers can lead to problems down the road for both our future selves and other code maintainers.

Thanks, Spock.

Starting with Colors

With most UI/UX programs, we tend to work with color, generally stemming from a style guide. Let us consider this function:

This color view can be anything we want it to be but our guide says we can only use the colors given to us. Rather than having to remember an RGB value to create each time, let’s make it easier on ourselves.

With a small bit of setup, we can fix something that is prone to errors. We can utilize structs to achieve this.

bonus: tomato is a valid css color.

This is one of the simple use cases of a strongly typed identifier. The goal of this is to make sure we keep avoidable errors to a minimum.


Graduating to Strings

Another pain point and source of frustration is when strings are used all willy-nilly. For instance, this function here:

“No Strings” — Edna Mode
“In case you see a piñata”

A few things could happen when using this function. To name a few: misspelling of the id parameter, finding a different object with the same id or causing a crash when inside the function.

So let us take a second and strongly type these functions. We want to create a struct so we can be explicit and readability is at the highest.


Generics, Structs, and Strongly Typed Identifiers

More wisdom from Edna.

Even with the extra struct, both uses still pass the compiler. Do you know why our function still accepts these values? As with all types, a String is a String no matter the alias. How about we change the type alias into something that is unique to that struct?

This is when we implement the protocols RawRepresentable and Equatable and sprinkle in Generics to create this:

As for the usage of this new and improved function:


Voila!

We have now locked up our function and kept the errors at bay. There are many different ways you can keep function associations close and organized. My advice to you is to start with low hanging fruit and keep building.

Name this movie for a free cookie.

mrtnrst

Life as a developer all told by quips, longform, and gifs

Martin

Written by

Martin

Programmer. Designer. And pretty much anything else that floats my boat. -arista™

mrtnrst

mrtnrst

Life as a developer all told by quips, longform, and gifs

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade