MSBA-340 · Lesson 4 of 12 · 21 min
Classes and methods
▶ Video coming soon A video version of this lesson is on the way.
For the fourth clinic Desmond brought a printout of a standard class with more than three thousand lines of code. He put it on the table without comment and waited. Prudence leafed through it and asked whether all X++ classes looked like that. They do not, he said, and the point of the session was to make sure Cobalt Ridge's never would.
Classes in X++
A class in X++ is declared with the class keyword, a name and a body in braces. Inside the body are member variables and methods. A class can extend one other class, implement any number of interfaces, and carry modifiers that control its visibility and how it can be used. Each class is an element in the AOT, stored in its own file, and appears in Application Explorer under Code, Classes.
/// <summary>
/// Calculates warranty dates and status for Cobalt Ridge pumps.
/// </summary>
public class CRPumpWarrantyCalculator
{
CRWarrantyMonths warrantyMonths;
TransDate installDate;
public void new(TransDate _installDate, CRWarrantyMonths _warrantyMonths)
{
installDate = _installDate;
warrantyMonths = _warrantyMonths;
}
public TransDate endDate()
{
return dateMthFwd(installDate, warrantyMonths) - 1;
}
public boolean isActive(TransDate _onDate)
{
return _onDate >= installDate && _onDate <= this.endDate();
}
}Member variables are declared at the top of the class body. By default they are protected, which means they are visible in the class and in classes that extend it but not outside. X++ has no public member variables in the C# sense; other code reaches an object's state only through methods. The new method is the constructor, called when code writes new CRPumpWarrantyCalculator(date, months). The this keyword refers to the current object, and methods are called on an object with a dot.
Access modifiers
Classes and methods carry modifiers that control who can use them. Desmond asked Prudence to treat the choice as a design decision rather than an afterthought, because in finance and operations apps the modifiers also decide what other models can extend.
| Modifier | On a class | On a method |
|---|---|---|
| public | Usable from any model that references the package | Callable from anywhere |
| internal | Usable only inside the same package | Callable only inside the same package |
| protected | Not used on classes | Callable from the class and its subclasses (the default for methods without a modifier in many styles; set it explicitly) |
| private | Not used on classes | Callable only inside the class |
| final | Cannot be extended by inheritance | Cannot be overridden |
| abstract | Cannot be instantiated; must be extended | Has no body; subclasses must implement it |
| static | Not used on classes | Belongs to the class, not to an object |
The internal modifier is particularly useful for Cobalt Ridge. A helper class that only the warranty module uses can be internal, which tells every future developer, and the compiler, that no other package depends on it. Public classes and methods are a promise: once other code uses them, changing their signature is a breaking change. Desmond's default for new classes was internal final unless there was a reason to open them.
Modifiers also matter for extension. Chain of command, taught in MSBA-341, can wrap public and protected methods of a class from another model, but not private ones, and some methods are marked to prevent wrapping. Microsoft uses these markers deliberately to say which parts of its code are safe extension points. When Cobalt Ridge writes its own classes, the same thinking applies in reverse: a method other teams may need to extend should be protected or public and small enough that wrapping it makes sense.
Static methods and the construct pattern
A static method belongs to the class rather than to an object and is called with a double colon, such as CRPumpWarrantyCalculator::newFromWarranty(warranty). Static methods are used for utilities and, most importantly, for constructing objects. The standard application rarely lets code call new directly. Instead, a class has a static construct method, or a set of static newFrom methods, that create and initialize the object. The constructor itself is often protected, so construct is the only way in.
public class CRPumpWarrantyCalculator
{
// ... members as before ...
protected void new()
{
}
public static CRPumpWarrantyCalculator construct()
{
return new CRPumpWarrantyCalculator();
}
public static CRPumpWarrantyCalculator newFromWarranty(CRPumpWarrantyTable _warranty)
{
CRPumpWarrantyCalculator calculator = CRPumpWarrantyCalculator::construct();
calculator.parmInstallDate(_warranty.InstallDate);
calculator.parmWarrantyMonths(_warranty.WarrantyMonths);
return calculator;
}
public TransDate parmInstallDate(TransDate _installDate = installDate)
{
installDate = _installDate;
return installDate;
}
public CRWarrantyMonths parmWarrantyMonths(CRWarrantyMonths _warrantyMonths = warrantyMonths)
{
warrantyMonths = _warrantyMonths;
return warrantyMonths;
}
}The pattern has two advantages. First, construct gives one place where the class is created, so an extension can change which subclass is returned for a particular situation without every caller changing. Second, named factory methods such as newFromWarranty make the calling code read clearly and keep initialization logic in one place.
Parm methods
The second half of the example shows parm methods, a convention used throughout the application. A parm method is a combined getter and setter: it takes an optional parameter whose default value is the current member value, assigns it and returns it. Calling calculator.parmInstallDate() reads the value; calling calculator.parmInstallDate(today()) sets it. Optional parameters with default values are a general X++ feature, and the prmIsDefault function, mentioned in lesson 3, tells a method whether the caller supplied a value. Parm methods are also how the SysOperation framework, in MSBA-341, exposes the fields of a data contract to dialogs and batch jobs.
Inheritance and abstract classes
A class extends another with the extends keyword and inherits its public and protected members. A subclass can override a method by declaring one with the same signature, and can call the base version with super(). Classes are single-inheritance, as in C#. An abstract class cannot be created with new and exists to be extended; an abstract method has no body and every non-abstract subclass must implement it.
The warranty module gave Desmond a clean example. Cobalt Ridge sells pumps with two kinds of warranty terms: a standard term in months from installation, and a mining term that ends at a number of operating hours or a number of months, whichever comes first. Both answer the same questions, so they share an abstract base class.
public abstract class CRWarrantyTerm
{
protected TransDate installDate;
protected CRWarrantyMonths months;
public TransDate endDate()
{
return dateMthFwd(installDate, months) - 1;
}
public boolean isActive(TransDate _onDate)
{
return _onDate >= installDate && _onDate <= this.endDate();
}
abstract public str description()
{
}
}
public final class CRWarrantyTermMining extends CRWarrantyTerm
{
CRWarrantyHours hours;
public boolean isActive(TransDate _onDate)
{
return super(_onDate) && CRPumpRunHours::hoursUsed(serialNumber) < hours;
}
public str description()
{
return strFmt('%1 months or %2 operating hours', months, hours);
}
}Prudence noticed that the mining subclass calls super(_onDate) and then adds its own condition. That pattern, doing the base behavior and adding to it, is exactly what chain of command does for standard classes from another model. Learning it with ordinary inheritance first makes the extension mechanics in MSBA-341 much easier.
Interfaces
An interface declares methods without bodies, and a class that implements it must provide them. Interfaces let code depend on a capability rather than a particular class. In the warranty module, any class that can notify someone about an expiring warranty implements CRIWarrantyNotifier, so the expiry job can call notify without knowing whether the notice goes by email, by a Teams message through a business event, or into a work list. Standard X++ code uses interfaces widely, such as SysPackable for objects that can pack their state into a container.
Delegates and events, briefly
Classes can also declare delegates: methods with no body, marked with the delegate keyword, that the class calls at a meaningful moment so that other code can subscribe and react. Standard classes use delegates as extension points, and tables and forms raise built-in events such as onInserted or onValidatedWrite. Subscribers are static methods with an attribute that names the event. Prudence asked whether the warranty service should raise a delegate when a warranty is registered. Desmond said yes, because the mining division had already asked to be told about every mining pump warranty, and a delegate would let that code live in its own class without touching the service. The mechanics of delegates and event handlers belong to MSBA-341, but the design habit starts here: when you write a class, think about where other developers will want to hook in, and offer them a clean place to do it.
Attributes
Attributes are classes that carry metadata about other code, applied in square brackets above a class or method. X++ uses them for many framework features. The SysOperation framework reads DataContractAttribute and DataMemberAttribute on contract classes. Chain of command classes carry ExtensionOf. Event handlers carry attributes that say which event they subscribe to. Unit test methods are found by the test framework through SysTestMethodAttribute. Developers can create their own attribute classes by extending SysAttribute, and the MB-500 outline asks candidates to implement attribute classes; MSBA-341 uses them with the extension framework.
[DataContractAttribute]
public final class CRWarrantyExpiryContract
{
CRWarrantyDaysAhead daysAhead;
[DataMemberAttribute]
public CRWarrantyDaysAhead parmDaysAhead(CRWarrantyDaysAhead _daysAhead = daysAhead)
{
daysAhead = _daysAhead;
return daysAhead;
}
}Methods on tables and forms
Classes are not the only place X++ lives. Tables have methods, such as insert, update, delete, validateWrite and initValue, and can have custom methods of their own; forms have methods on the form, its data sources and its controls. Lessons 5 and 7 cover those. The general rule Desmond gave was to keep business logic in classes and keep table and form methods thin, calling into classes. Logic in a form method runs only when that form is used; the same logic in a class can be called from the form, from a batch job, from a data entity and from a service.
Variable scope in classes
The MB-500 outline asks candidates to implement variable scoping, and in X++ the rules come in three levels. Member variables, declared at the top of the class, live as long as the object does and are visible in every instance method of the class and, unless private, of its subclasses. Parameters are visible throughout the method that declares them. Local variables are visible from their declaration to the end of the block that contains them. A local variable with the same name as a member variable hides the member inside that block, which is legal but confusing; Desmond's convention was to prefix parameters with an underscore, as standard code does, so that _installDate is clearly the parameter and installDate the member.
Static methods have no object, so they cannot use member variables or this. If a static method needs state, it creates an object and works through it, which is another reason the construct pattern is so common. Static member variables, shared by every instance, exist in X++ but are rarely the right tool in server code, because many users share the same application server process; values that must survive between calls in a session are better kept in a table, in the global cache described in MSBA-343, or passed explicitly.
Runnable classes and the Args object
A runnable class is any class with a public static main method that takes an Args parameter. It can be started from a browser address, from a menu item of type action, or from Visual Studio during development, which lesson 10 demonstrates. The Args object carries context from whoever started the class: the record the user had selected, the menu item that was used, the calling form, and optional parameters. A class started from a button on the warranty form can read the selected warranty record from args.record() and act on it.
internal final class CRPumpWarrantyVoidAction
{
public static void main(Args _args)
{
CRPumpWarrantyTable warranty = _args.record() as CRPumpWarrantyTable;
if (!warranty)
{
throw error('Select a warranty first.');
}
CRPumpWarrantyService::construct().voidWarranty(warranty);
info(strFmt('Warranty for %1 is void.', warranty.SerialNumber));
}
}Runnable classes are useful for small utilities and one-off data fixes in a developer environment, but Desmond was strict about where they went next. A runnable class that changes data in a shared environment must be reviewed, must be idempotent so that running it twice does no harm, and should usually become a proper batch job or a data project instead. In production, data changes go through supported, auditable processes, not through scripts.
Calling .NET from X++
Because X++ compiles to .NET, X++ code can use .NET classes directly, with their full namespace, such as System.Text.RegularExpressions.Regex for pattern matching or System.IO for streams. Types are converted between X++ and .NET where they correspond, such as str and System.String or int and System.Int32. Teams can also write C# class libraries, reference them from an X++ project and call them, which is a good choice for algorithms that already exist in .NET or are easier to write there. Desmond's caution was that .NET code still runs inside the application server, so it must be thread-safe, must not hold resources open and must respect the same security rules as X++.
Designing for tests
Lesson 11 introduces the SysTest framework for unit tests. Classes are much easier to test when their dependencies can be replaced: a calculator that takes its install date and months as parameters can be tested with any values, while one that reads the date from the system and the months from a table on its own can only be tested against real data. The construct pattern, small methods and interfaces all help. Prudence's calculator was testable from the start, which is why it became the first class with tests in the project.
How big should a class be?
Desmond returned to the three-thousand-line printout at the end. Large standard classes exist for historical reasons, and Microsoft has broken many of them up over time to provide better extension points. For Cobalt Ridge's own code he set three guidelines: a class should have one responsibility that can be described in a sentence; a method should fit on one screen; and a method that other code may need to change should be small and protected or public, so that it can be extended without copying. The calculator, the term classes and the notifier each did one job. The expiry job that used them, written in lesson 12, was under fifty lines.
Worked problem
Choosing modifiers
Prudence is writing CRPumpWarrantyService, which registers warranties when pumps are sold. It has a method register called by the sales invoice extension, a helper defaultMonths that reads the module's parameters, and a method validateSerial that Cobalt Ridge's mining division may later want to change. Which modifiers should she use?
Show solution
- The class is used only by Cobalt Ridge's own package, so internal is a safe start; if another package ever needs it, it can be made public then.
- register is the entry point called from another class, so it is public within the class.
- defaultMonths is an implementation detail, so it is private.
- validateSerial may need extending, so it is protected and kept small.
Answer: An internal class with a public register method, a private defaultMonths helper and a protected validateSerial method.
Common mistakes
MistakeCalling new directly everywhere a class is used.
InsteadProvide a static construct or newFrom method so creation and initialization live in one place.
MistakeMaking every class and method public.
InsteadChoose internal, private or protected unless other code genuinely needs access; public members are a contract.
MistakePutting business logic in form methods.
InsteadPut logic in classes and call them from forms, batch jobs and services.
MistakeWriting one long method that does everything.
InsteadKeep methods short and focused so they can be read, tested and extended.
Summary and key terms
- X++ classes have member variables, methods, a constructor named new, single inheritance and interfaces.
- Modifiers such as public, internal, protected, private, final, abstract and static control visibility, inheritance and what other models can extend.
- The construct pattern and newFrom factory methods centralize object creation; parm methods combine getters and setters.
- Abstract classes and interfaces let code depend on capabilities; super() calls the base behavior from an override.
- Attributes such as DataContractAttribute and ExtensionOf carry metadata used by the frameworks.
- Construct method
- A static method that creates an instance of a class, used instead of calling new directly.
- Parm method
- A method that both sets and returns a member value, with an optional parameter defaulting to the current value.
- Abstract class
- A class that cannot be instantiated and is meant to be extended.
- Interface
- A declaration of methods that implementing classes must provide.
- Attribute
- A class applied in square brackets to add metadata to code.
- internal
- A modifier limiting use of a class or method to its own package.
Practice problems
Work each problem on paper first, then reveal the answer to check.
How do you call the base version of an overridden method?
Show answer
With super(), passing the same parameters.
What does calling parmInstallDate() with no argument do?
Show answer
It returns the current value without changing it, because the parameter defaults to the current member value.
Why are business rules better in classes than in form methods?
Show answer
Classes can be called from forms, batch jobs, entities and services; form methods run only in that form.
Lesson quiz · 5 questions
Score 60% or more to complete this lesson.
Create a free account to save your progress, take quizzes and earn a certificate.