From magazine topic to project implementation
Relevant service and technical pages for this post
The typical moment when Delphi RTTI for mapping without magic suddenly becomes inteRESTing is not an architecture workshop — but an operational error message: „Since the view update, amounts are 0 for some customers, and nobody knows why.“ In the database it was only an alias change (sum_total instead of total_sum), in the code there was a convention („field name = property name“) and the mapper silently set nothing. No crash, no log entry, just incorrect domain states. Exactly this kind of error is more costly than a clean, explicit mapper.
RTTI (Run-Time Type Information, type information at runtime) is a useful tool for that — but only if you make the rules visible, centralize conversions and build in debuggability. The REST of this post is a decision map: what you gain, what it costs, and what a mapping plan looks like that does not immediately fail in legacy situations.
Trade-off map: RTTI mapping without magic vs. alternatives
| Approach | Strengths | Typical failure points | When I use it |
|---|---|---|---|
| Handwritten mapping | Maximally controllable, fast, easy to profile | Lots of boilerplate, drift with many DTOs | Hot paths, critical ETL stretches, small models |
| Conventions (Name=Name) | Quick to start, little code | Alias/join/refactoring breaks silently; debugging difficult | Only for prototypes or tightly controlled schemas |
| ORM (fully automatic) | Convenience, change tracking, query abstraction | Magic, side effects, hard to contain | When an ORM is deliberately adopted and operated |
| RTTI + Attributes (Opt-in) + Mapping-Plan | Explicit rules, less boilerplate, good diagnostics | Conversion rules must be clear; RTTI caching required | Mature business software, interface boundaries, modernization |
The guiding decision is: a mapper must never „appear silently correct.“ If it cannot map, it must either fail clearly or at least log explainably. Otherwise you produce data errors that only surface weeks later.
Delphi RTTI for mapping without magic: principles that survive operation
1) Opt-in via attribute instead of implicit convention
„Magic“ usually arises from implicit rules. The core trick is simple: only properties with an attribute are mapped. That makes it visible in review what is part of the mapping at all, and renames won’t hit you by accident.
2) Build a mapping plan, then execute (instead of RTTI per record)
RTTI is not inherently slow, but repeated metadata evaluation costs. Delphi itself documents that RTTI via System.Rtti provides metadata at runtime; use that as a build phase and cache the result per class. (Context: RTTI in Delphi is the standard reflection API via TRttiContext, TRttiType, TRttiProperty.) See Delphi docs on RTTI in Delphi.
3) Conversion is infrastructure, not „just VarAsType“
Variant conversion seems convenient, but it obscures null semantics, locale issues and divergent Boolean-/Enum encodings. Therefore: a central converter that intentionally accepts only supported types and otherwise aborts with a clear error message. That’s less ‚flexible‘, but significantly easier to debug.
Source snippet: Mapping plan with RTTI, cache, reader adapter and debug
The following snippet is intentionally low-key: an attribute, a reader interface, a mapper with a type cache. More important than the raw mapping is the error reporting: if something does not match, the error text states which property, which source name and which target type were affected.
unit NbRttiMap;
interface
uses
System.SysUtils, System.Rtti, System.TypInfo, System.Generics.Collections,
System.Variants;
type
MapFromAttribute = class(TCustomAttribute)
private
FName: string;
public
constructor Create(const AName: string);
property Name: string read FName;
end;
IValueReader = interface
['{E7A76C4E-5E3E-4F2D-8F7B-5F92C2F6A6D3}']
function HasValue(const AName: string): Boolean; // Field present?
function IsNull(const AName: string): Boolean; // Field is NULL?
function GetValue(const AName: string): Variant; // Value (Variant)
end;
TRttiMapOptions = set of (moDebug, moIgnoreMissing, moFailOnNull);
ERttiMapError = class(Exception);
TRttiMapper = class
private
type
TPropMap = record
Prop: TRttiProperty;
SourceName: string;
end;
TTypeCache = class
public
Props: TArray<TPropMap>;
end;
private
class var FCache: TObjectDictionary<PTypeInfo, TTypeCache>;
class var FLock: TObject;
class function BuildCache(ATypeInfo: PTypeInfo): TTypeCache; static;
class function GetCache(ATypeInfo: PTypeInfo): TTypeCache; static;
class function MapNameOf(const P: TRttiProperty): string; static;
class function VariantToBoolean(const V: Variant): Boolean; static;
class function VariantToEnumOrdinal(AEnumType: TRttiType; const V: Variant): Integer; static;
class procedure SetPropValue(const Target: TObject; const P: TRttiProperty; const V: Variant); static;
public
class constructor Create;
class destructor Destroy;
class procedure MapToObject(const Reader: IValueReader; const Target: TObject;
const Options: TRttiMapOptions = [moIgnoreMissing]); static;
end;
implementation
constructor MapFromAttribute.Create(const AName: string);
begin
inherited Create;
FName := AName;
end;
class constructor TRttiMapper.Create;
begin
FCache := TObjectDictionary<PTypeInfo, TTypeCache>.Create([doOwnsValues]);
FLock := TObject.Create;
end;
class destructor TRttiMapper.Destroy;
begin
FCache.Free;
FLock.Free;
end;
class function TRttiMapper.MapNameOf(const P: TRttiProperty): string;
var
A: TCustomAttribute;
begin
Result := '';
for A in P.GetAttributes do
if A is MapFromAttribute then
Exit(MapFromAttribute(A).Name);
end;
class function TRttiMapper.BuildCache(ATypeInfo: PTypeInfo): TTypeCache;
var
Ctx: TRttiContext;
T: TRttiType;
P: TRttiProperty;
L: TList<TPropMap>;
M: TPropMap;
Src: string;
begin
Result := TTypeCache.Create;
Ctx := TRttiContext.Create;
T := Ctx.GetType(ATypeInfo);
L := TList<TPropMap>.Create;
try
for P in T.GetProperties do
begin
if not P.IsWritable then
Continue;
Src := MapNameOf(P);
if Src = '' then
Continue; // Opt-in
M.Prop := P;
M.SourceName := Src;
L.Add(M);
end;
Result.Props := L.ToArray;
finally
L.Free;
end;
end;
class function TRttiMapper.GetCache(ATypeInfo: PTypeInfo): TTypeCache;
begin
TMonitor.Enter(FLock);
try
if not FCache.TryGetValue(ATypeInfo, Result) then
begin
Result := BuildCache(ATypeInfo);
FCache.Add(ATypeInfo, Result);
end;
finally
TMonitor.Exit(FLock);
end;
end;
class function TRttiMapper.VariantToBoolean(const V: Variant): Boolean;
var
S: string;
begin
if VarIsBool(V) then
Exit(Boolean(V));
if VarIsNumeric(V) then
Exit(V <> 0);
S := Trim(VarToStr(V)).ToLower;
if (S = '1') or (S = 'true') or (S = 't') or (S = 'y') or (S = 'yes') then Exit(True);
if (S = '0') or (S = 'false') or (S = 'f') or (S = 'n') or (S = 'no') then Exit(False);
raise ERttiMapError.CreateFmt('Boolean conversion failed: "%s"', [VarToStr(V)]);
end;
class function TRttiMapper.VariantToEnumOrdinal(AEnumType: TRttiType; const V: Variant): Integer;
var
OrdV: Integer;
Name: string;
TD: PTypeData;
begin
TD := GetTypeData(AEnumType.Handle);
if VarIsNumeric(V) then
begin
OrdV := Integer(V);
if (OrdV < TD^.MinValue) or (OrdV > TD^.MaxValue) then
raise ERttiMapError.CreateFmt('Enum ordinal out of range: %d', [OrdV]);
Exit(OrdV);
end;
Name := VarToStr(V);
OrdV := GetEnumValue(AEnumType.Handle, Name);
if OrdV < 0 then
raise ERttiMapError.CreateFmt('Enum name unknown: "%s"', [Name]);
Result := OrdV;
end;
class procedure TRttiMapper.SetPropValue(const Target: TObject; const P: TRttiProperty; const V: Variant);
var
T: TRttiType;
TV: TValue;
OrdV: Integer;
begin
T := P.PropertyType;
case T.TypeKind of
tkUString, tkString, tkLString, tkWString:
TV := TValue.From<string>(VarToStr(V));
tkInteger:
TV := TValue.From<Integer>(VarAsType(V, varInteger));
tkInt64:
TV := TValue.From<Int64>(VarAsType(V, varInt64));
tkFloat:
TV := TValue.From<Double>(VarAsType(V, varDouble));
tkEnumeration:
begin
if T.Handle = TypeInfo(Boolean) then
TV := TValue.From<Boolean>(VariantToBoolean(V))
else
begin
OrdV := VariantToEnumOrdinal(T, V);
TV := TValue.FromOrdinal(T.Handle, OrdV);
end;
end;
else
raise ERttiMapError.CreateFmt('Unsupported target type (%s) for Property %s',
[GetEnumName(TypeInfo(TTypeKind), Ord(T.TypeKind)), P.Name]);
end;
P.SetValue(Target, TV);
end;
class procedure TRttiMapper.MapToObject(const Reader: IValueReader; const Target: TObject;
const Options: TRttiMapOptions);
var
C: TTypeCache;
M: TPropMap;
V: Variant;
Info: string;
begin
if (Reader = nil) or (Target = nil) then
raise ERttiMapError.Create('MapToObject: Reader or Target is nil');
C := GetCache(Target.ClassInfo);
for M in C.Props do
begin
if not Reader.HasValue(M.SourceName) then
begin
if not (moIgnoreMissing in Options) then
raise ERttiMapError.CreateFmt('Source missing: "%s" for Property %s', [M.SourceName, M.Prop.Name]);
Continue;
end;
if Reader.IsNull(M.SourceName) then
begin
if moFailOnNull in Options then
raise ERttiMapError.CreateFmt('Source is NULL: "%s" for Property %s', [M.SourceName, M.Prop.Name]);
Continue;
end;
V := Reader.GetValue(M.SourceName);
try
SetPropValue(Target, M.Prop, V);
if moDebug in Options then
begin
Info := Format('Mapped %s <- %s (VariantType=%d)', [M.Prop.Name, M.SourceName, VarType(V)]);
OutputDebugString(PChar(Info));
end;
except
on E: Exception do
raise ERttiMapError.CreateFmt('Mapping error %s <- %s: %s', [M.Prop.Name, M.SourceName, E.Message]);
end;
end;
end;
end.
Purpose and constraints
- Explicit: Without
[MapFrom('...')]nothing is set. - Cache: A mapping plan is built per class and reused. Without a cache RTTI quickly becomes a hotspot.
- Error messages: The exception reports source and target so that you have a chance to diagnose issues in production.
Pitfalls (deliberately not „abstracted away“)
- NULL semantics: The snippet skips NULL by default. If NULL is an important state, you must reflect that in the model (Nullable/Optional or flags).
- Locale:
VarAsType(..., varDouble)is robust for true numeric Variants, but not for culture-dependent number strings. If your sources provide strings, define a parser with a fixed culture. - Complex types: Class properties, records, sets, collections are intentionally not mapped automatically. In those areas „automation“ tends to fail first in practice.
Adapter for Dataset/FireDAC: decouple rather than marry
In VCL and service code the source is often TDataSet (BDE-replacement with native binding or classic). Instead of making the mapper directly dependent on TField, write a reader adapter. That way you can later use the same mapper for JSON/CSV. (Context: BDE-Ablosung mit nativer Anbindung is the data access library of RAD Studio; TDataSet is the base class of the dataset model in Delphi.)
unit NbDataSetReader;
interface
uses
Data.DB, System.Variants, NbRttiMap;
type
TDataSetValueReader = class(TInterfacedObject, IValueReader)
private
FDS: TDataSet;
public
constructor Create(ADS: TDataSet);
function HasValue(const AName: string): Boolean;
function IsNull(const AName: string): Boolean;
function GetValue(const AName: string): Variant;
end;
implementation
constructor TDataSetValueReader.Create(ADS: TDataSet);
begin
inherited Create;
FDS := ADS;
end;
function TDataSetValueReader.HasValue(const AName: string): Boolean;
begin
Result := (FDS <> nil) and (FDS.FindField(AName) <> nil);
end;
function TDataSetValueReader.IsNull(const AName: string): Boolean;
var
F: TField;
begin
F := FDS.FindField(AName);
Result := (F = nil) or F.IsNull;
end;
function TDataSetValueReader.GetValue(const AName: string): Variant;
begin
Result := FDS.FieldByName(AName).Value;
end;
end.
How it is used
type
TOrderState = (osOpen, osClosed);
TOrderRow = class
private
FId: Int64;
FCustomerNo: string;
FIsClosed: Boolean;
FState: TOrderState;
public
[MapFrom('order_id')]
property Id: Int64 read FId write FId;
[MapFrom('customer_no')]
property CustomerNo: string read FCustomerNo write FCustomerNo;
[MapFrom('is_closed')]
property IsClosed: Boolean read FIsClosed write FIsClosed;
[MapFrom('state')]
property State: TOrderState read FState write FState; // e.g. 'osClosed' or 1
end;
var
Row: TOrderRow;
Reader: IValueReader;
begin
Row := TOrderRow.Create;
try
Reader := TDataSetValueReader.Create(MyQuery);
TRttiMapper.MapToObject(Reader, Row, [moIgnoreMissing, moDebug]);
finally
Row.Free;
end;
end;
Four operating modes as a decision path (to prevent failures)
- Development:
moDebugon,moIgnoreMissingoff. Objective: let schema problems fail early. - Test/Staging: selectively enable Debug, Missing/NULL per contract. Objective: make drifting data sources visible.
- Production (stable): Debug off, Missing according to contract. Objective: no log flood, but clear exceptions on real contract violations.
- Production (diagnostic window): temporarily enable Debug (feature flag), limited to a single operation/Correlation-ID. Objective: reproducible chain of evidence without remote debugging.
A practical anchor: If you are already working on mapping edges, it is often worth looking at robust dataset-to-object strategies that handle legacy edge cases, e.g. alias columns and optional column lists. Related content: Dataset-to-object mapping for unusual legacy structures.
One editorial assessment
If I have to choose between “quick mapping by convention” and “RTTI with opt-in and diagnostics”, in mature codebases I almost always prefer the second approach — not for elegance, but because silent non-mapping in production is one of the most problematic error classes: semantically incorrect data without a technical alert.
Limits, risks and variants
Performance and lock contention
The cache is protected by a Monitor. In highly concurrent services this can cause short contention on the first access per type. Variant: build the cache „warm“ at startup (touch all relevant types once) or synchronize cache construction separately.
Thread safety of TRttiContext
Here TRttiContext is only used locally in BuildCache. That reduces risk and keeps the context out of hot paths. As a rule: RTTI objects should not be passed around „wildly“ across threads; design strategies and work with stable references.
Model nullable/optional cleanly
If you need to distinguish between „NULL“ and „default“ (e.g. 0 is semantically relevant), skipping NULL is not sufficient. You then need a domain model that expresses absence (Nullable/Option) or separate fields/flags. The mapper should not hide this decision.
Extension: custom converter per property
A commonly useful extension is an additional attribute like [MapWith(TMyConverter)] to explicitly handle individual edge cases (e.g. date as an ISO string, amount as „1,23“) without diluting the global conversion. Important: Converters must be deterministic and provide clear error messages.
Conclusion: RTTI is not the problem – implicit rules are
Delphi RTTI for mapping without magic is worthwhile when you treat mapping as a contract between data source and domain model: opt-in via attributes, a cached mapping plan, controlled conversion and a debug path that actually helps in operation. It is not a substitute for clean domain modeling and it is not a free pass for complex object graphs. But as a robust bridge in legacy modernization and at integration boundaries the approach is often precisely the kind of „little magic“ that makes you faster in the long run.
If you adapt such a mapping pattern into a grown Delphi application, including null semantics, a diagnostic path and architectural boundaries, you can discuss that with us concretely: .
For this topic, Attribute Mapping Delphi and Dataset To Object Mapping Delphi are also important. The article places these aspects in a clear context and shows what matters in everyday practice.
Discuss a project or modernization initiative with Net-Base.
Next step
When the topic becomes an actual project, architecture, existing systems and operations should be considered together from the outset.
We support not only with individual issues, but also when source snippets, legacy topics, or portal ideas are to be turned into a robust enterprise project.
- Current state, target state and technical risks are assessed jointly.
- REST, data access, portals and rollout are not deferred to a later stage as secondary consequences.
- You can see early on which path is economically and operationally viable.