Is it common to see all fields as nullable in backend models?

0
6
Asked By CuriousCoder92 On

I'm currently working on an application that was passed down to me. The backend is built with NestJS while the frontend is in Flutter. I noticed that the backend client for the frontend calls uses typed classes for the response models, but every field is nullable, even the required ones. There's a lot of placeholder values in the UI due to this, which seems pretty messy. I'm wondering if this is a common practice or just a way of playing it safe to avoid null exceptions. I have less than two years of experience and my past jobs haven't been great, so I'm trying to figure this out without asking my coworkers directly.

1 Answer

Answered By DevDiscovery99 On

It’s not uncommon to see this in handover codebases. It seems more like the previous developer was trying to avoid null exceptions by making everything nullable rather than it being a robust defensive coding strategy. The fact that you’re seeing so many placeholder values in the UI is a big giveaway. In proper defensive coding, you'd usually have a mapper or a DTO layer to manage nullability before the data hits the UI. You're probably just dealing with the fallout of some rushed work where they wanted to prevent crashes, but it left the codebase a bit messy.

The ideal scenario would be to define required fields as non-nullable in your models and handle missing data more explicitly with a `fromJson` factory. This way, your UI wouldn’t have to handle the guesswork. If you're looking to tidy things up, start by validating the API responses and adjusting the model fields accordingly. Using tools like Freezed and json_serializable can make this a lot easier if you're not using them already.

CodeFixer77 -

Yeah, it's pretty common to see after someone has had some bad experiences with crashes. In legacy projects, it’s all too frequent to find that people prioritized shipping over fixing underlying issues.

FlutterFanatic14 -

Thanks for clarifying! It's frustrating because it seems like they even handcoded all the network models, and that seems unnecessary for such a small codebase. What do you think would be a solid approach to ensure that backend responses stay in sync with the frontend, so we don't end up relying on nullable fields?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.