Hi All,
As AL developers, we often start with a quick solution by putting all the logic in one big procedure, get the feature working, and ship it. But over time, that "quick solution" becomes a massive block of code that's hard to read, harder to change, and nearly impossible to test. Sound familiar?
Today, let's talk about refactoring your AL code and writing it in a way that's actually testable. These two things go hand in hand.
What Is Refactoring?
Refactoring means restructuring your existing code without changing what it does. You're not adding features, and you're making the code cleaner, more focused, and easier to work with over time.
In Business Central AL development, this matters because requirements change, bugs need fixing, and code written today will be touched again. The easier it is to understand, the safer it is to change.
The Problem: Doing Too Much in One Place
Here's a pattern we've all written at some point:
This one procedure is doing three completely different things: validating the customer, calculating totals, and sending an email. If you want to test just the validation, you can't — it'll trigger the email too. If the email logic breaks, the whole procedure fails.
This is where refactoring helps.
Refactored: Split by What Each Part Does
The idea is simple - procedure or codeunit should do one focused thing. Let's split the above into separate codeunits:
Your main procedure now just orchestrates the flow:
Much cleaner. Each codeunit has a clear job, and if something breaks, you know exactly where to look.
Now, Writing Tests Becomes Easy
Once your code is split up, testing each part in isolation is straightforward. You don't need to worry about side effects from unrelated logic:
Because ValidateCustomer only does one thing, the test is clean, fast, and reliable. No emails fire, no calculations run — just the logic you care about.
Quick Tips to Get Started
- If a procedure is more than 40–50 lines, it's probably doing too much. Break it up.
- Name your procedures clearly — ValidateCustomer is better than DoCheck.
- Refactor gradually — you don't have to rewrite everything at once. Start with the most painful procedure in your codebase.
- Write tests as you refactor, not after. It keeps you honest and gives you confidence.
- Use AL interfaces when you want to swap implementations
Reach out to me if you have any questions or suggestions.
Check out other blogs, if you haven't already.
No comments:
Post a Comment