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

Dec 18, 2024 pm 04:57 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles