Why logic leaves the form

A form is a class, but it is a class the runtime owns: it is created after the runtime exists, it lives inside a message loop, and most of its interesting methods are private handlers that only a click can reach. A discount rule written in a Click handler cannot be called by anything except that click. This part of the course takes the logic out of the form, and this lesson says why it is worth the extra files.

The rule inside the form

Here is a checkout form with one rule: an order of 1000 or more gets ten percent off, and an order of 10000 or more is free. The rule is a switch expression in the middle of a handler, next to a label assignment and a message box:

using System; using System.Drawing; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new Form1()); } } internal sealed class Form1 : Form { private readonly NumericUpDown _total = new() { Location = new Point(120, 20), Maximum = 100000, DecimalPlaces = 2, }; private readonly Label _result = new() { Location = new Point(16, 64), AutoSize = true }; public Form1() { Text = "Checkout"; ClientSize = new Size(380, 120); var pay = new Button { Text = "&Pay", Location = new Point(256, 18), Size = new Size(100, 27) }; pay.Click += OnPay; Controls.Add(new Label { Text = "Total:", AutoSize = true, Location = new Point(16, 22) }); Controls.Add(_total); Controls.Add(pay); Controls.Add(_result); } private void OnPay(object? sender, EventArgs e) { var total = _total.Value; var discount = total switch { >= 10000m => total, >= 1000m => Math.Round(total * 0.10m, 2), _ => 0m, }; var due = total - discount; _result.Text = $"discount {discount:0.00}, due {due:0.00}"; if (due <= 0m) { MessageBox.Show("Nothing to pay.", "Checkout", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run: there is no desktop here, and WinForms needs Windows. What is wrong with it is not that it fails. It compiles, and on Windows it draws a working form. What is wrong is that the rule has no name and no caller. OnPay is private, it takes an EventArgs it ignores, it writes to a label and it may open a modal dialog. The only way to ask what the discount is, is to start a desktop session, type a number and press a button.

Three smaller problems follow from the same place. The rule cannot be reused for a report or a batch import, because it is entangled with the controls. The message box is a decision made in the middle of the calculation, so an order that can be paid without a dialog has nowhere to say so. And every future rule arrives in the same method, until the handler is the application.

The same rule in a class

The same rule as a plain class, plus a table of totals. This one was built and run in the container:

using System; Console.WriteLine("total, discount, due and free for five orders"); var cases = new[] { 0m, 999.99m, 1000m, 2500m, 20000m }; foreach (var total in cases) { var quote = Checkout.Quote(total); Console.WriteLine($"{total,9:0.00} -> discount {quote.Discount,7:0.00}, due {quote.Due,9:0.00}, free {quote.IsFree}"); } try { Checkout.Quote(-1m); } catch (ArgumentOutOfRangeException error) { Console.WriteLine($"negative total: {error.ParamName}"); } internal readonly record struct Quote(decimal Total, decimal Discount, decimal Due) { public bool IsFree => Due == 0m; } internal static class Checkout { public static Quote Quote(decimal total) { ArgumentOutOfRangeException.ThrowIfNegative(total); var discount = total switch { >= 10000m => total, >= 1000m => Math.Round(total * 0.10m, 2), _ => 0m, }; return new Quote(total, discount, total - discount); } }

dotnet run

total, discount, due and free for five orders
     0.00 -> discount    0.00, due      0.00, free True
   999.99 -> discount    0.00, due    999.99, free False
  1000.00 -> discount  100.00, due    900.00, free False
  2500.00 -> discount  250.00, due   2250.00, free False
20000.00 -> discount 20000.00, due      0.00, free True
negative total: total

The output is the real run. Nothing here knows what a form is, so the whole rule is exercised by five lines of code: the boundary at 1000, the free order at 10000, the rounding of the discount, and the rejection of a negative total. The catch prints total because ThrowIfNegative fills ParamName from the parameter it was given; a test asserts on that name, and no message box can interfere.

A record struct is the return value because a quote is a small immutable value: the compiler writes the constructor, the properties, equality and a readable ToString. The form keeps its own job, which is to show the numbers and to decide what a free order looks like on screen.

What the split buys

The three layers

The rest of the course uses three names, and they are the same three in every lesson of this part:

model the data and the rules: Quote, Checkout, an invoice, a document view the form: controls, layout, and the values the user sees presenter the decisions between them: what a click means, what happens next

The dependency points one way: the presenter knows the model and talks to the view through an interface, and the view knows neither the model nor the presenter. System.Windows.Forms appears in the view alone, which is exactly why the two other layers can be built and run on Linux. Lesson 052 writes the interface and the presenter.

Exercises

  1. Add a rule to Checkout.Quote: an order below 10 is refused with an ArgumentException. Extend the table of cases and run it.
  2. Change the return type of Quote to a class with a constructor and compare the two programs. Which lines does the compiler make you write?
  3. List everything in the first listing that cannot be tested without a desktop, and say which layer each item belongs to.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why is a rule inside a Click handler hard to test?

    Answer

    The handler is private and only the message loop can call it

    Reaching the code needs a form, a loop and a click, none of which exist in a test.

  2. What does the plain class version of the rule need to run?

    Answer

    Nothing beyond the runtime: no form, no loop and no display

    That is why the course runs it headless here.

  3. What does ArgumentOutOfRangeException.ThrowIfNegative do with its parameter?

    Answer

    Fills ParamName with the name of the argument it was given

    The run printed total, which is the parameter name.

  4. What was the discount for a total of 2500?

    Answer

    250.00

    The 1000 arm applies ten percent, and the run printed 250.00.

  5. Why is 20000 free in the second program?

    Answer

    The first switch arm covers 10000 and more with a full discount

    The arms are tried in order, and the first is >= 10000m.

  6. Which layer owns System.Windows.Forms?

    Answer

    The view

    Keeping the namespace in the view is what lets the other layers run on Linux.

  7. What does the presenter depend on?

    Answer

    The model, and an interface the view implements

    The interface is the seam that a fake view implements in a test.

  8. What happens to the message box when the rule moves out of the form?

    Answer

    It moves to the view, after the rule returns its result

    A calculation cannot show a dialog, so the decision belongs to the view.

  9. Which of these is the real cost of the split?

    Answer

    More files, an interface and a wiring step

    The lesson names the cost instead of pretending the split is free.

  10. Why does the course keep the return value a record struct?

    Answer

    A quote is a small immutable value, and the compiler writes equality and ToString

    The type carries the total, the discount and the due amount without hand-written members.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev

Banner image