Removing Magic Strings With Source Generators
Stringly typed UI code usually feels harmless until the first real refactor.
An element ID changes. A partial is renamed. An event key gets copied into three places. Nothing looks obviously dangerous in code review, and then the interaction quietly stops working.
That is why source generators are more than a convenience feature in Swap.Htmx. They make the coordination layer safer.
What magic strings cost
Raw strings hide important contracts:
- which view is being updated,
- which element ID is being targeted,
- which event name a region is listening for.
When those contracts stay as loose strings, your editor and compiler cannot help much. Refactoring becomes slower and more defensive.
What generated constants improve
Generated members turn those contracts into things your tooling can see.
That means:
- rename support gets better,
- discoverability improves,
- code review becomes clearer,
- accidental typos stop making it all the way to runtime.
This matters most in projects where the number of views, partials, and event names keeps growing over time.
A real example from this site
The generators feature page shows the shape of the generated constants directly. Instead of relying on string literals, the project can use generated members such as these:
public static class SwapViews
{
public static class Products
{
public const string List = "List";
public const string _Card = "_Card";
}
}
return SwapView(SwapViews.Products.List);
The same page also shows generated element constants such as SwapElements.ProductGrid and SwapElements.CartCount. That is the practical payoff: refactors stop depending on careful string matching alone.
The real benefit is confidence
The win is not simply fewer strings in code. The win is being able to change the system with less fear.
If a refactor affects a generated view constant or event symbol, you find out earlier. That shortens the feedback loop and makes the codebase easier to evolve.
When it matters most
Small prototypes can live with raw strings longer. Growing systems pay the cost sooner.
If your project has:
- many partials,
- repeated multi-target updates,
- event-driven UI reactions,
- multiple developers changing the same workflows,
then generated constants stop being a nice-to-have and start feeling like basic hygiene.