Declarative vs. Imperative
What is Declarative vs. Imperative?
Declarative vs. Imperative: These are two opposite styles of writing code. Imperative code describes every step of the algorithm. Declarative code describes the desired outcome and lets the runtime figure out the steps. Imperative and declarative are two ways of writing code. Imperative code gives step-by-step instructions: loop over the users, check each one, add the active ones to a new list. Declarative code states the outcome: give me the active users.
Frequently asked questions about Declarative vs. Imperative
How is Declarative vs. Imperative used in practice?
Most real code mixes both. A Laravel collection call like $users->filter(fn ($u) => $u->active) is declarative at the top, with a small imperative piece inside.
What should you keep in mind with Declarative vs. Imperative?
Neither style is better in general. Declarative code is usually easier to read and harder to get wrong for common tasks such as querying, filtering and describing infrastructure. Imperative code gives full control when you need a specific algorithm or fine-tuned performance. A good rule is to state what you want as declaratively as the tools allow, and drop down to imperative steps only where it adds clarity or speed.
At a glance
| Category | Programming paradigms |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |