DoYouEvenFlutter? [EP.2] API Enum Mapping
Welcome!
Since you are here I assume you’ve read the title. Since we cleared that out next question may be: “What the hell does he mean by API Enum mapping?”. Thanks for asking!
In Dart, we have a special class that represents a group of constants. When discussing OOP usually we see en examples like this.
Imagine we have a car:
We can see that the brand of the car is a type of CarBrand. Then we can assume the enum for that will look like:
Then if we write some function with those objects in mind:
Everyone is happy about our good objective approach to the subject. The problem starts when we start using some APIs. When sending data using e.g. JSON we may come across something like this:
Then usually when writing an object for this response we will create a properties for it like:
- int id
- String name
- STRING brand
The type of a brand property is highlighted because we usually leave it as it is. As a string. Then somewhere in the code, we are comparing object.brand to a STRING. Seams innocent. Right?
When we run search and replace at the end of the feature development our matches will return 50+ repetitions of:
object.brand == “TESLA”
For the sake of an argument, let's imagine that while adding another condition like this we make a typo, or the API changed the response type from String to int. Then we need to replace every occurrence of it, rewrite all unit tests, etc, etc.
Why giving yourself more work?
Let’s map that
What I like to do is to create 3 elements for that type of models:
- enum
- RESPONSE-map
- REQUEST-map
Response-map is a map for translating the language of our API to our ENUM.
Request-map is not mandatory but if you’re sending the object back to the API (saving or updating) then we need something that translates our ENUM to API friendly format.
This is a code that I’m usually ending up with is:
So when we get the API response and we run:
Car.fromJson(json)
We’re automatically ending up with an object the has an ENUM out of the box, and again everyone is happy in out OOP approach 😊It’s easy to test and refactor. Doesn’t require a lot of boilerplate code and it’ easily refactorable.
Hopefully, in the future, we’ll see in Dart some more refined enum implementation. Particularly I wouldn’t mind associated values, for sure.
Thank you very much for this 3 min spend with my article. Please remember I’ve described what I like to do in my projects. This helps me a lot while developing.
Flutter is a platform where your imagination is the limit. I love this about it 😊
If you want, you can check the full working example here. The code there contains all the code from the series including the previous episode: DoYouEvenFlutter? [EP.1] Scroll to Element in list. The code has some other perks that I will be describing in future episodes. If you have some questions, write them here in the comment section or DM me on Twitter.
Cheers,
Luke
P.S.
Yes I call my car “THE BUG” 😂