.NET Strategies to Reduce Code Branching with Declarative C# Techniques

We can see a big difference between declarative and imperative programming as we explore different styles of programming:Declarative programming is about “what” you want to do, andImperative code is more about “how” you want to do it.If you are followi…


This content originally appeared on Level Up Coding - Medium and was authored by Florian Boehmak

We can see a big difference between declarative and imperative programming as we explore different styles of programming:

  • Declarative programming is about “what” you want to do, and
  • Imperative code is more about “how” you want to do it.

If you are following along this series of articles, you may find Middlewares, AOP, and Data Annotations interesting as well.

Let’s get started by examining how declarative methods can streamline complex and heavily branched code, a typical occurrence in imperative programming. We’ll begin with a negative example and then delve into alternative solutions.

Deeply Nested Code Example (Negative Example)

Consider a hypothetical e-commerce application where you need to present different prices based on user type and product category. An imperative and deeply nested approach might look like this:

public decimal CalculatePrice(User user, Product product)
{
decimal price = product.BasePrice;

if (user.Type == UserType.Regular)
{
if (product.Category == ProductCategory.Electronics)
{
if (product.InStock)
{
price -= product.BasePrice * 0.05m; // 5% discount
}
else
{
price += product.BasePrice * 0.1m; // 10% markup
}
}
else if (product.Category == ProductCategory.Clothing)
{
price -= product.BasePrice * 0.1m; // 10% discount
}
// ... More nested conditions
}
else if (user.Type == UserType.Premium)
{
if (product.Category == ProductCategory.Electronics)
{
price -= product.BasePrice * 0.1m; // 10% discount
}
else if (product.Category == ProductCategory.Clothing)
{
price -= product.BasePrice * 0.2m; // 20% discount
}
// ... More nested conditions
}
// ... More nested conditions

return price;
}

Here is an example of how the calculated price is different for “John” and “Jayne”, based on their User Type (Regular or Premium):

Now let’s see how we could refactor this using declarative programming techniques to improve the code structure. All code examples can be found at: fnbk/branching-strategies-domain-specific-language

1. Using SQL Statements

Assuming users and products are stored in a database, you could write a SQL statement that performs the price calculation directly within the query using CASE statements, thus offloading all the logic to the database:

SELECT
u.Id AS UserId,
u.Name AS UserName,
p.Id AS ProductId,
p.Name AS ProductName,
CASE
WHEN u.Type = 'Regular' AND p.Category = 'Electronics' THEN
CASE
WHEN p.InStock = 1 THEN
p.BasePrice * 0.95
ELSE p.BasePrice * 1.10
END
WHEN u.Type = 'Regular' AND p.Category = 'Clothing' THEN
p.BasePrice * 0.90
WHEN u.Type = 'Premium' AND p.Category = 'Electronics' THEN
p.BasePrice * 0.90
WHEN u.Type = 'Premium' AND p.Category = 'Clothing' THEN
p.BasePrice * 0.80
ELSE p.BasePrice
END AS CalculatedPrice
FROM Users u
CROSS JOIN Products p

This SQL query is a declarative way to define how the prices should be adjusted without specifying the iterative logic to do so.

2. Using Fluent Interface DSL

You can abstract away complex pricing logic by defining a DSL for pricing rules. Let’s say we have a DSL where we can declaratively specify pricing rules as follows:

pricingService
.ForUser(UserType.Regular)
.ForCategory(ProductCategory.Electronics).InStock().ApplyDiscount(0.05m)
.ForCategory(ProductCategory.Electronics).OutOfStock().ApplyMarkup(0.1m)
.ForCategory(ProductCategory.Clothing).ApplyDiscount(0.1m)
.ForUser(UserType.Premium)
.ForCategory(ProductCategory.Electronics).ApplyDiscount(0.1m)
.ForCategory(ProductCategory.Clothing).ApplyDiscount(0.2m);

This Fluent Interface technique lets you express complex pricing structures as a DSL in a readable and maintainable way, without any nesting.

3. Using JSON DSL

The application could read a JSON file and use that as a DSL to dynamically adjust item prices based on these rules without hardcoding the logic into the application, thereby separating the business rules from the codebase.

{
"pricingRules": [
{
"userType": "Regular",
"rules": [
{
"productCategory": "Electronics",
"inStock": true,
"adjustment": {
"type": "Discount",
"value": 0.05
}
},
{
"productCategory": "Electronics",
"inStock": false,
"adjustment": {
"type": "Markup",
"value": 0.1
}
},
{
"productCategory": "Clothing",
"adjustment": {
"type": "Discount",
"value": 0.1
}
}
]
},
{
"userType": "Premium",
"rules": [
{
"productCategory": "Electronics",
"adjustment": {
"type": "Discount",
"value": 0.1
}
},
{
"productCategory": "Clothing",
"adjustment": {
"type": "Discount",
"value": 0.2
}
}
]
}
]
}

This DSL uses a JSON structure to represent the rules clearly and concisely.

4. Using HTML/CSS

Although HTML/CSS doesn’t apply directly to this backend logic, let’s say we wanted to display the price differently depending on the discount (green for discounted price and bold for premium user clothes).

We could use CSS classes to declaratively control the display:

<!-- HTML -->
<div class="product {{ elem.ProductCategory | lowercase }} {{ elem.UserType | lowercase }}">
<span class="price">{{ elem.Price | currency }}</span >
</div>
/* CSS */
.product.electronics.regular .price {
color: #008000; /* Green for discounted price */
}

.product.clothing.premium .price {
font-weight: bold; /* Bold for premium clothes */
}

The CSS classes are applied based on the category and user type, deciding the display of the price without needing explicit logic in your HTML or JavaScript.

Conclusion

By transitioning from nested imperative code to a declarative style (e.g. using SQL, DSLs and HTML/CSS), you can create cleaner, more understandable, and maintainable code.

This approach follows the DRY principle, which means you don’t repeat yourself and write the same things over and over.

It separates concerns (SoC) by using the right abstraction level and tooling, allowing you to focus on what the system should do, not how to do it.

Find the full code examples on GitHub.

Happy Coding!


.NET Strategies to Reduce Code Branching with Declarative C# Techniques was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Florian Boehmak


Print Share Comment Cite Upload Translate Updates
APA

Florian Boehmak | Sciencx (2025-01-15T16:49:44+00:00) .NET Strategies to Reduce Code Branching with Declarative C# Techniques. Retrieved from https://www.scien.cx/2025/01/15/net-strategies-to-reduce-code-branching-with-declarative-c-techniques/

MLA
" » .NET Strategies to Reduce Code Branching with Declarative C# Techniques." Florian Boehmak | Sciencx - Wednesday January 15, 2025, https://www.scien.cx/2025/01/15/net-strategies-to-reduce-code-branching-with-declarative-c-techniques/
HARVARD
Florian Boehmak | Sciencx Wednesday January 15, 2025 » .NET Strategies to Reduce Code Branching with Declarative C# Techniques., viewed ,<https://www.scien.cx/2025/01/15/net-strategies-to-reduce-code-branching-with-declarative-c-techniques/>
VANCOUVER
Florian Boehmak | Sciencx - » .NET Strategies to Reduce Code Branching with Declarative C# Techniques. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2025/01/15/net-strategies-to-reduce-code-branching-with-declarative-c-techniques/
CHICAGO
" » .NET Strategies to Reduce Code Branching with Declarative C# Techniques." Florian Boehmak | Sciencx - Accessed . https://www.scien.cx/2025/01/15/net-strategies-to-reduce-code-branching-with-declarative-c-techniques/
IEEE
" » .NET Strategies to Reduce Code Branching with Declarative C# Techniques." Florian Boehmak | Sciencx [Online]. Available: https://www.scien.cx/2025/01/15/net-strategies-to-reduce-code-branching-with-declarative-c-techniques/. [Accessed: ]
rf:citation
» .NET Strategies to Reduce Code Branching with Declarative C# Techniques | Florian Boehmak | Sciencx | https://www.scien.cx/2025/01/15/net-strategies-to-reduce-code-branching-with-declarative-c-techniques/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.