What is Common Expression Language (CEL)? A Beginner's Guide
Natan Mohart
Tech Entrepreneur | Team Lead & Software Engineer | Author & Speaker | Follow for daily posts about Mindset, Personal Growth, and Leadership
What is CEL?
Common Expression Language, or CEL, is a language designed by Google to safely and efficiently execute checks and calculations in applications. At its core, CEL helps developers create flexible rules and conditions that can be easily integrated into applications without needing to alter the main code. It is particularly useful for defining logic without hardcoding rules directly into the software.
Why Should You Use CEL?
Imagine you manage an online store and want to offer discounts based on specific conditions, such as:
Instead of hardcoding these rules into your app, CEL allows you to write them as simple expressions:
// Discount rule example
order.total >= 100 && (user.birthday == today || user.status == "VIP")
This approach makes it much easier to modify and scale your logic without diving into your app's core code every time a rule needs updating.
Why CEL is Beneficial
Here are some key reasons CEL is an excellent choice for handling complex conditions:
Getting Started with CEL
1. Basic Expressions
To understand how CEL works, let’s look at some simple examples:
// Check if the user is under 18
age < 18
// Check if a username has at least 3 characters
size(user.name) >= 3
// Check if a user has the "admin" role
"admin" in user.roles
These examples showcase the simplicity of writing basic conditions with CEL.
2. Combining Conditions
As your application’s logic becomes more complex, you’ll likely want to combine multiple conditions. Here’s how you could do it in CEL:
// Check if an order qualifies for special processing
order.total >= 100 && order.delivery.country in ["USA", "Canada"] && user.status == "VIP"
This is a real-world example of a business rule applied to an order in an e-commerce platform.
3. Working with Data Types
CEL supports different types of data, which makes it versatile for a variety of checks:
// Perform arithmetic on numbers
price * 1.2 // Increase price by 20%
// Concatenate strings
user.name + " " + user.surname
// Check if a number exists in a list
[1, 2, 3].exists(n, n < 2) // Check if there's any number smaller than 2
// Access key-value pairs in maps
settings.theme.color == "dark"
Real-Life Use Cases of CEL
1. Validating Forms
You can use CEL to validate data in forms, ensuring that user input meets your requirements. For example, validating a user’s registration details:
// Validate the registration form
size(user.password) >= 8 &&
matches(user.email, "^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$") &&
size(user.phone) == 11
2. Filtering Data
CEL is also great for filtering data, such as showing products that meet certain criteria:
// Product filter
product.price >= minPrice &&
product.price <= maxPrice &&
product.category in allowedCategories &&
product.stock > 0
3. Controlling Access
You can define access control rules for your application. For instance, you could check if a user has the necessary permissions:
// Access control check
user.isAuthenticated &&
("admin" in user.roles || resource.ownerId == user.id)
Best Practices for Writing CEL Rules
// Bad example
x > 5 && y == "test"
// Good example
user.age > 5 && user.status == "active"
When you write more advanced rules, it’s helpful to include comments for clarity:
// Discount rule:
// - Order total must be greater than $500
// - User has placed more than 3 orders
// - It’s December
order.total > 500 &&
user.orders_count > 3 &&
current_month == 12
Debugging and Testing CEL
Conclusion
CEL is an effective and simple tool for handling conditions and rules in your applications. Its major benefits include:
Start with simple expressions and gradually add more complexity. Over time, you’ll appreciate how CEL can simplify your code and improve your workflow.
You can explore CEL more by trying it out on the interactive platform: playcel.undistro.io. It’s a great way to get familiar with the syntax and capabilities in a safe environment.
Remember, CEL is designed to simplify development, not make it more complicated. Start small and scale as needed!
ReactJS Developer | JavaScript ES6 | Bootstrap | Tailwind CSS | Express | Redux | RTK Query | RESTful API | Progressing to MERN Stack
3 个月Useful tips, valuable reading ??
Python developer, 6+ years | B2B contract
3 个月was pretty interesting
Frontend Developer @TechWings | React, TypeScript, JavaScript | Improving UX Through Scalable Solutions
3 个月Interesting! CEL seems like a great tool for flexibility and security. Can't wait to check out the article!
Data Engineer | 5+ years | PepsiCo | Databricks, Apache Spark, Microsoft Azure
3 个月Pleased to read another fascinating article from you!
Full stack developer | 7 years+ | React, RxJs, Typescript, Nest.js, Node.js, .Net, SQL
3 个月It was nice to read. Never heard about this before. Thanks!