Chapter 4
Provide Contexts

We communicate more effectively when we know the context. We tend to use fewer words and reduce ambiguity and errors when the context is clear.

At a family dinner, when someone mentions a name, it generally refers to a close family member or a friend. The family serves as the implicit context in conversations around the dinner table. At the office meeting, however, a name often refers to a team member, as the team serves as the context. It may also refer to a well-known person at a major client. It’s not unusual for us to operate simultaneously with multiple contexts. Furthermore, we often switch contexts during the day, going from a context of the team to the context of the family, for example.

Likewise, within DSLs we often switch between different contexts of execution. A function may be called in the context of an argument provided to a lambda. Alternatively, it may be executed in the context of an implicit receiver. We may actively change the context of execution of a part of a DSL, when compared to other parts. By setting an execution context, we can reduce clutter, ambiguity, and errors, and at the same time make the code more intuitive.

Code written using DSLs often needs to use variables. However, we rarely will want a user to explicitly define variables, as that would feel like coding and disrupt the flow for the user. Instead of expecting an explicit definition, DSLs may pull in variables from an implicit context of execution. Likewise, the user may refer to a property or a function that they don’t define. These may, once again, come from an implicit context.

In object-oriented programming, instance methods run in the context of a receiver, often referred to as this or self, depending on the programming language. In addition to that, in the case of Kotlin, lambda expressions run in the context of multiple receivers. When a property or a function is mentioned within a lambda expression, it comes from the scope of one of the receivers. Using these concepts, we can provide execution context for DSLs.

In this chapter, we’ll see how to create an execution context for variable definitions. Then we’ll look at some examples of how DSLs are used in common build tools, like Gradle. We’ll then explore the implicit parameter name for lambda expressions and how that can help in creating fluent DSLs. We’ll also discuss the use of the this execution context. Finally, we’ll look at creating and simultaneously using multiple contexts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.236.55.137