Let’s examine that distinction with more detail. Where declarative programming favors a description of the target state, imperative programming details the actions that should be executed in order to produce that outcome. The distinction between “declarative” and “imperative” may seem superficial or pedantic, but using the appropriate techniques for the situation will have tangible benefits.
Other properties are either derived from this, or shared with imperative programming, making referential transparency the primary difference between the two paradigms. If the operation “add” is truly referentially transparent, we can replace the first statement with:įormally speaking, this is the only requirement of declarative programming. As an example of referential transparency, consider a function that adds together two numbers given as input and then returns their sum: For a program to have this property, you should be able to replace any expression with its result.
However, declarative is not synonymous with intuitive, and the implications of a declarative design can affect much more than just readability.Ī commonly cited aspect of declarative code is that it does not “produce side effects,” which is formally described as “referential transparency.” Referentially transparent code relies only on the input to a procedure when determining the output. Order = sorted(filter(fruit.all(), ), by=price)įollowed by a generic banality: “it’s just that easy!” Yes, a declarative style can sometimes promote more readable code, but those details have to come from somewhere-often they are abstracted into reusable components. If you’ve researched this topic before, you may have come upon simple examples like:
The goal of declarative programming is to describe your desired result without (directly) dictating how to get it.