Home > Web Front-end > JS Tutorial > Embracing Declarative Data Access to Respect Your Intelligence as a Developer

Embracing Declarative Data Access to Respect Your Intelligence as a Developer

Susan Sarandon
Release: 2024-12-18 16:57:09
Original
557 people have browsed it

Embracing Declarative Data Access to Respect Your Intelligence as a Developer

In the world of software development, we often find ourselves torn between two paradigms: imperative and declarative. For many developers, the lure of imperative code is its simplicity—just write instructions step-by-step, and you know exactly what the computer is doing. However, as complexity grows, that step-by-step approach turns into a tangled mess of logic scattered across the codebase. In contrast, the declarative approach aims to let you describe what you want rather than how to get it, freeing you from micromanaging details.

In this post, we’re not here to prove that declarative is the “best” approach. Instead, we’ll explore how a declarative design can create a system that respects your intelligence as a developer—allowing you to grow your application gracefully and maintain it with far less cognitive overhead.


Imperative: A Road of Detailed Instructions

Imagine you’re building a small application to fetch posts and users from various APIs. The imperative way might look like this:

const axios = require('axios');

// Imperative approach: You write every step for every request
async function fetchAllPosts() {
    const response = await axios.get('https://jsonplaceholder.typicode.com/posts');
    return response.data;
}

async function fetchUsers() {
    const response = await axios.get('https://dummyjson.com/users');
    return response.data.users;
}
Copy after login

At first glance, this is straightforward—just do a GET request and return the data. But what happens when complexity creeps in? You might need:

  • Multiple endpoints for different models.
  • Authentication headers.
  • Pagination, filtering, and complex queries.
  • Data validation and relationships between models.

You’ll soon find yourself copying and pasting code, hardcoding endpoints and headers all over the place, and managing a web of intricate logic manually. The imperative style starts to feel like a chore: you’re writing the same instructions again and again, and it’s easy to lose track of where all the logic lives.


Declarative: A World of Intent and Patterns

Now let’s look at a more declarative design. Instead of telling the system how to fetch each resource, you describe what each resource looks like, where it lives, and how it relates to others. Then, you let a flexible adapter or manager handle the details under the hood.

Here’s an example:

class PostAdapter extends APIAdapter {
    static baseURL = 'https://jsonplaceholder.typicode.com/';
    static headers = {};
    static endpoint = 'posts';

    async *all(...args){
        // Insert custom business logic here (e.g., logging, pagination)
        return await super.all(...args)
    }
}

class UserAdapter extends APIAdapter {
    static baseURL = 'https://dummyjson.com/';
    static headers = {};
    static endpoint = 'users';
}

class CustomValidatedPost extends Post {
    static schema = {
        ...Post.schema,
        email: 'string',
        body: 'string',
        userId: 'number'
    };
    static adapter = PostAdapter;
}

class CustomUser extends User {
    static adapter = UserAdapter;

    async _post() {
        return await CustomValidatedPost.objects.query({ id: this.id });
    }
}

// Using the declared models and adapters:
const userIterator = await CustomUser.objects.all();
async function processNextUser() {
    const { value: user, done } = await userIterator.next();
    if (done) return;
    // Handle your user data here
}
Copy after login

At first glance, this might look more complex because we have classes, static properties, and adapters. But look closer:

  • No Hardcoded URLs Everywhere: The base URL, endpoint, and headers are defined once at the class level. Any request for that model uses these defaults automatically.
  • Relationships Declared, Not Forced: CustomUser defines a _post method that returns posts related to the user. This feels almost like a query, not a bunch of imperative code. You’re stating your intention: “I want posts for this user.”
  • Extend and Customize With Ease: Need custom logic for fetching posts? Just override all() in PostAdapter. By making this logic a clean extension of the default behavior, you reduce the chance of accidentally breaking something else.

In other words, you’re building a system that reads more like a set of declarations than a set of instructions. The adapters and models form a pattern that the rest of the code can rely on, rather than an ad-hoc cluster of random axios.get() calls.


The Real Win: Respecting Your Developer Intelligence

Why go through this effort? Because as projects grow, you don’t want to waste time navigating a minefield of imperative logic. Declarative design sets expectations:

  • When you see CustomUser.objects.all(), you know immediately what it means: it returns an iterator of all CustomUser instances. No guesswork.
  • When you declare static adapter = UserAdapter;, you know that any data operation on CustomUser uses UserAdapter under the hood. Consistency and clarity are built-in.
  • When you define static schema on a model, you can trust that the system knows how to validate or handle those fields without you writing repetitive imperative code all over again.

This approach respects your intelligence as a developer. It doesn’t force you to recall which endpoint belongs to which model or where the headers are defined. Instead, it lets you think at a higher level: define what your data looks like and how it relates, and let the framework handle the rest.


Not About Being “The Best,” But Being Sustainable

We’re not claiming that a declarative approach with adapters and static fields is universally better than raw imperative code. For a small script, axios.get() might be all you need. But as systems scale, the declarative approach creates a sustainable environment where changes are less painful, features are easier to add, and the overall complexity is managed gracefully.

You could say it’s about building a system that treats you—the developer—more like a smart engineer and less like a transcriptionist of instructions.


Conclusion

The declarative approach might feel foreign at first if you’re used to writing every step by hand. But once you experience the calm of having a consistent pattern, clearly declared endpoints, and a place to neatly add custom logic, it becomes hard to go back to imperative sprawl.

It’s not about proving superiority. It’s about offering an approach that’s kinder to your future self, more respectful of your time, and more in tune with how you think about data and relationships. Instead of micromanaging every request, you write code that reads like a story, focusing on what you want, not every tedious detail of how to get it.

The above is the detailed content of Embracing Declarative Data Access to Respect Your Intelligence as a Developer. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template