How to Move Business Logic Out of C# Code

Most business logic starts in the code because that's where it's easiest to write. A discount here, a shipping hold there, one if at a time. Years later it's still there, it changes every month, and every change is a ticket, a code review, a test run and a deployment, for what's often a one-number edit that someone outside the development team asked for.

This article moves a small piece of real-looking business logic out of C# and into business rules, step by step: first with the free Code Effects Rule Editor and Rule Engine, then with the Rule Repository, which hands the rules to the people who own the policy, with versions, tests and approvals. Every code sample here was compiled against the Code Effects 7 libraries, and the rules were built in the real editor.

The Problem

Here is the logic. An online store gives discounts by customer tier and holds large orders shipped abroad until the sales team looks at them:

public static class OrderPolicy
{
	public static void Apply(Order order)
	{
		if (order.Tier == CustomerTier.Gold && order.Total >= 500)
			order.DiscountPercent = 10;
		else if (order.Tier == CustomerTier.Silver && order.Total >= 1000)
			order.DiscountPercent = 5;

		if (order.Country != "US" && order.Total > 10000)
		{
			order.OnHold = true;
			order.NotifySales();
		}
	}
}

There's nothing wrong with this code as code. The problem is who owns it. The thresholds (500, 1000, 10000), the tiers that qualify and the countries that count as "abroad" are business decisions, made by people who can't read C#. They change on a business schedule, not a release schedule. And the only record of why a number changed is a commit message.

What to Move, and What to Keep

Not everything should leave the code. A useful line to draw:

  • Move the decisions. Conditions, thresholds, which customers qualify, what value to set. These are what change, and what the business wants to own.
  • Keep the mechanics. Loading the data, saving it, sending the email, calling the payment API. These stay in C#, where they're tested, typed and reviewed like any other code.

The boundary between the two is one class, the source object: the data the rules can read and set, plus the methods they can call. Rules decide; your code still does the work.

Step 1: Describe the Data the Rules Work On

The source object is often a class you already have. A few attributes turn its members into the vocabulary of the rules:

using CodeEffects.Rule.Common.Attributes;

public enum CustomerTier { Standard, Silver, Gold }

public class Order
{
	[Field(DisplayName = "Order total", Min = 0)]
	public decimal Total { get; set; }

	[Field(DisplayName = "Customer tier")]
	public CustomerTier Tier { get; set; }

	[Field(DisplayName = "Shipping country", Max = 2)]
	public string Country { get; set; } = "US";

	[Field(DisplayName = "Discount, %", Min = 0, Max = 50)]
	public int DiscountPercent { get; set; }

	[Field(DisplayName = "On hold")]
	public bool OnHold { get; set; }

	[Action(DisplayName = "Notify the sales team")]
	public void NotifySales() { /* your code: an email, a queue message, a webhook */ }
}

DisplayName is what rule authors see. Min and Max bound what they can enter: a 90% discount typed into a rule is saved as 50, the field's maximum. NotifySales is an action: a rule can call it, but what it does stays your code.

Step 2: Let People Write the Rules

The Rule Editor is a web component. For personal, community, development and research use it's free: reference CodeEffects.Rule.Editor.Personal from NuGet and the browser files from the @codeeffects/editor npm package. Commercial use needs a Code Effects package from the Code Effects Portal.

The server describes the source object to the editor:

using CodeEffects.Rule.Common.Models;
using CodeEffects.Rule.Editor;

app.MapGet("/api/settings", () =>
{
	var editor = new Control("divEditor")
	{
		EvaluationMode = EvaluationMode.Execution,
		SourceType = typeof(Order)
	};

	return Results.Ok(new Settings
	{
		GlobalData = editor.GetGlobalData(),
		EditorData = editor.GetEditorData()
	});
});

public class Settings
{
	public string? GlobalData { get; set; }
	public string? EditorData { get; set; }
}

EvaluationMode.Execution allows rules that set values and call actions, not only rules that answer true or false. The page loads those settings and starts the editor:

const settings = await (await fetch('/api/settings', { headers: { 'Accept': 'application/json' } })).json();

const editor = $rule.init({
	id: "divEditor",
	globalData: settings.globalData,
	editorData: settings.editorData,
	showToolBar: true,
	saveRuleCallback: saveRule   // your function: posts the rule to /api/rules (Step 3)
});

The toolbar holds the rule's name, which every stored rule needs.

From there, a product owner writes the policy by picking from menus built from your class. Here are the two rules from the code above, exactly as the editor reads them back:

If Customer tier is Gold and Order total is greater than or equal to 500 then set Discount, % to 10 else if Customer tier is Silver and Order total is greater than or equal to 1000 then set Discount, % to 5

If Shipping country is not US and Order total is greater than 10000 then set On hold to True and Notify the sales team

The menus only offer what makes sense at each point: numeric operators for Order total, the three tiers for Customer tier, only the settable fields after "set". A rule can't name a field that doesn't exist or compare a tier with a number, so most of the mistakes a hand-typed rule language invites can't happen.

Step 3: Save the Rules

The editor never saves anything itself. Its save callback hands the rule to your server, which checks it against the same source object and turns it into Rule XML:

app.MapPost("/api/rules", async (HttpRequest request) =>
{
	using var reader = new StreamReader(request.Body);

	var editor = new Control("divEditor")
	{
		EvaluationMode = EvaluationMode.Execution,
		SourceType = typeof(Order)
	};
	editor.LoadRuleData(await reader.ReadToEndAsync());

	if (editor.IsEmpty) return Results.BadRequest();
	if (!editor.IsValid) return Results.Content(editor.GetInvalidData(), "application/json");

	ruleStore.Save(editor.Rule.ID, editor.GetRuleXml());   // your storage
	return Results.Ok();
});

Validation runs on the server, so a rule that's incomplete or doesn't fit the class is never stored. An invalid rule goes back to the editor, which marks the elements at fault. The rule's ID comes from the editor; use it as the key in your storage.

Step 4: Replace the if/else

Now the policy class becomes a thin wrapper around the rule engine:

using CodeEffects.Rule.Engine;

public static class OrderPolicy
{
	private static Evaluator<Order>[] evaluators = Array.Empty<Evaluator<Order>>();

	// Call at startup, and again whenever the stored rules change
	public static void Load(IEnumerable<string> ruleXmls) =>
		evaluators = ruleXmls.Select(xml => new Evaluator<Order>(xml)).ToArray();

	public static void Apply(Order order)
	{
		foreach (var evaluator in evaluators) evaluator.Evaluate(order);
	}
}

Apply keeps its signature, so nothing that calls it changes. An Evaluator compiles its rule once, in its constructor, and can be shared between threads, so create it when the rules load, not on every call. Give each thread its own Order, because execution rules change the object they're given.

Step 5: Prove It Before You Switch

Moving logic is a refactoring, and a refactoring needs proof that nothing changed. Run the old code and the new rules on the same data before you delete anything. For this article, both versions ran on 48 orders: every tier, totals on both sides of every threshold (499.99, 500, 999.99, 1000, 10000, 10000.01 and more), shipped to the US and abroad. All 48 came out identical: the same discount, the same hold, the same notification.

Then the comparison found a difference that no test case had planned for. An order shipped to "us", in lowercase, was put on hold by the C# code, because != compares strings exactly, and was not held by the rule, because string fields compare case-insensitively by default. The rule's behavior is arguably the right one, but it's still a change, and the old code would never have told you. If you need the exact comparison, say so on the field:

[Field(DisplayName = "Shipping country", Max = 2, StringComparison = StringComparison.Ordinal)]
public string Country { get; set; } = "US";

Real data is the best test set. Run yesterday's orders through both versions and compare.

The Part Teams Underestimate

At this point the logic is out of the code. But look at what Step 3 says: your storage. Once business users own the rules, your application owns everything around them:

  • Versions. Which rule was live last Tuesday, when an order was held by mistake?
  • Review. Who checks a rule before it reaches production, and how does a rule wait for that check?
  • Testing. How does a product owner try a rule on realistic data without touching production?
  • History. Who changed the threshold from 500 to 400, and when?

Code Effects' own estimate is that building this around the editor and engine typically takes a team of two or three developers three to six months. That's the job the Rule Repository does.

Step 6: Hand Ownership Over with the Rule Repository

The Rule Repository is a library and a browser UI that run inside your application, against your database. It stores your source objects and rules, and manages their versions, tests and approvals. It's part of the Business, Enterprise and Ultimate packages.

Your application tells the repository about the source object once, at startup:

using CodeEffects.Rule.Repository;

var db = new CodeEffects.Rule.Connection.SqlServer.DbProvider(
	builder.Configuration.GetConnectionString("Rules"));

var sources = new SourceSettings();
sources.SourceTypes.Add(typeof(Order));
Context.SyncSources(db, sources);

One endpoint answers the repository's UI, with your authentication deciding who may do what:

using CodeEffects.Rule.Common.Models;

app.MapPost("/api/rules", async (HttpContext http) =>
{
	using var reader = new StreamReader(http.Request.Body);

	var config = new Configuration { CurrentUserId = http.User.Identity?.Name };

	if (http.User.IsInRole("RuleManager"))
	{
		// Everything: write, test, approve, go live
		config.AccessMode = ActionPermissionMode.AllowAllExcept;
		config.ActionList = new HashSet<ActionPermissionType>();
	}
	else config.AccessMode = ActionPermissionMode.ViewOnly;

	return Results.Content(Context.GetResponse(config, db, await reader.ReadToEndAsync()), "application/json");
}).RequireAuthorization();

A real application maps each of its roles to the permissions it should have, and sends each request through its anti-forgery and size checks, as the endpoint guide shows. On the page, one call mounts the whole UI:

const repository = CodeEffects.Rule.Repository.init({
	id: "rules",
	requestCallback: async (requestJson) => {
		const response = await fetch("/api/rules", {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			credentials: "same-origin",
			body: requestJson
		});
		return await response.text();
	}
});

And production evaluates whatever is live:

using CodeEffects.Rule.Engine;
using CodeEffects.Rule.Repository;

LoadedRuleset live = Context.GetRules(db, RuleQuery.BySource("Shop.Order"));
var evaluator = new Evaluator<Order>(live.Xml);

foreach (var rule in live.Rules) evaluator.Evaluate(order, rule.Id);

The query returns every rule of the source object that has a live version, as one ruleset compiled once. Run each rule by its ID: Evaluate(order) with no ID runs only the first rule of a ruleset.

What the people who own the policy get:

  • Versions that never change. Editing a rule creates a new version, and each rule has at most one live version. Going back means making an older version live again.
  • Approvals. A change can require someone else's approval before it goes live, and making a version live is a step of its own.
  • Tests on your real classes. Authors save test cases with expected results and run them before asking for approval. A test runs on your actual Order class; an action like NotifySales is recorded instead of run, unless you declare a test version of it.
  • History. Every change is recorded: who, what and when. With the Audit library, every production decision also records the rule version that made it and the values it read.

The threshold changes from 500 to 400 now without a ticket or a deployment, and with a record of who approved it.

Summary

Moving business logic out of C# isn't about deleting code. It's about drawing a line: your classes keep the data and the mechanics, and the rules take the decisions. The steps:

  1. Describe the data with a source object.
  2. Let the people who own the policy write rules in the editor.
  3. Validate and store the rules on the server.
  4. Replace the if/else with the engine.
  5. Prove the two versions agree before you switch, on real data.
  6. When the rules need versions, reviews and tests, put them in the Rule Repository.

To start, reference the free CodeEffects.Rule.Editor.Personal and CodeEffects.Rule.Engine.Personal packages from NuGet and follow the implementation guide, or try the Rule Repository demo.

Also published on Hashnode
Date: November 13, 2026

Ask on Stack Overflow - Yes, it's still active
Ask in GitHub Discussions

p102

l097 --

l102

p101

×