MSBA-348 · Lesson 8 of 12 · 20 min

Code-reading questions

▶ Video coming soon A video version of this lesson is on the way.

Close to half of MB-500 asks you to understand code, and much of it shows code on the screen. You might be shown a class and asked what it returns, given a wrapper with blanks to fill, asked to put statements in order, or asked whether a proposed listing meets a goal. You are never asked to type a program from memory. The skill is reading: quickly, accurately and with an eye for the one detail that changes the answer.

Desmond ran this clinic differently. He printed ten short listings, each about the Cobalt Ridge code Prudence had written or reviewed during the autumn, with one or two deliberate faults. He gave her ninety seconds per listing and asked one question about each. Her first pass got six right. By the end of the clinic, with the method below, she was getting nine.

A five-step reading method

Five steps in a row: read the question first; identify the element and its kind; find the decisive lines such as attributes, next, tts statements and join keywords; trace one concrete value through the code; check the answer against the constraint words.
The reading method. Step four, tracing one concrete value, is the one candidates skip.

Step 1: read the question first. "What is displayed?" needs a trace. "Will this compile?" needs a rule check. "Which line should be changed?" needs a search for the fault. Each question sends you to different lines.

Step 2: identify the element and its kind. Is this a Chain of Command class, an event handler, a runnable class, a table method, an RDP class, a test? The attribute at the top usually tells you. ExtensionOf means a wrapper; DataEventHandler means a data event; SRSReportParameterAttribute means a report data provider; SysTestMethod means a test. Knowing the kind tells you which rules apply.

Step 3: find the decisive lines. In X++ these are usually attributes, the next call, transaction statements, join keywords, forupdate, firstonly, set-based keywords, skip methods and return statements. Most distractors differ from the right answer in one of these.

Step 4: trace one concrete value. Pick a real input, such as an installation on February 29, 2024, and follow it line by line. This catches off-by-one errors, end-of-month behavior and conditions that are never true.

Step 5: check against the constraint words. If the goal says "without modifying standard code", any answer that edits a standard element is out, however correct the code.

The listings below are original examples in the style of the exam, each followed by the reasoning. Work through them before reading the explanations.

Listing 1: what does the wrapper return?

Listing 1. The standard method returns 12 for item MC-150.
[ExtensionOf(classStr(CRPumpWarrantyCalculator))]
final class CRPumpWarrantyCalculator_CRMX_Extension
{
    public CRWarrantyMonths warrantyMonths(ItemId _itemId)
    {
        CRWarrantyMonths months = next warrantyMonths(_itemId);

        if (curExt() == 'CRMX')
        {
            months = max(months, 18);
        }
        return months;
    }
}

Question: in company CRMX, what does warrantyMonths('MC-150') return? In CRCA?

Identify the kind: a Chain of Command wrapper. The decisive lines are the call to next, which runs first and returns 12, and the condition on curExt, the current company. Trace: in CRMX, months becomes max(12, 18), which is 18. In CRCA, the condition is false and the wrapper returns 12. A distractor might say 18 everywhere, by reading the max line without its condition, or 12 everywhere, by assuming the wrapper's change is lost because next ran first. Code after next can change the result; that is the whole point of a post-next change.

Listing 2: will it compile, and is it allowed?

Listing 2. A wrapper intended to record who changed a warranty's status.
[ExtensionOf(tableStr(CRPumpWarrantyTable))]
final class CRPumpWarrantyTable_Audit_Extension
{
    public void update()
    {
        if (this.Status != this.orig().Status)
        {
            this.CRStatusChangedBy = curUserId();
            next update();
        }
    }
}

Question: what is wrong with this wrapper?

The decisive line is next update(), which sits inside an if. Chain of Command requires next to be called unconditionally at the first level of the method unless the target is marked Replaceable, and table update methods are not. As written, the wrapper would also skip the standard update whenever the status did not change, so ordinary edits would never be saved. The fix is to set the field inside the if and call next after it, outside the condition. A distractor might say the class must not be final; in fact extension classes must be final.

Listing 3: what does the select return?

Listing 3. Three Mining customers: one with two active warranties, one with one, one with none.
CustTable           cust;
CRPumpWarrantyTable w;
int                 n;

while select cust
    where cust.CustGroup == 'MINING'
    outer join w
        where w.CustAccount == cust.AccountNum
           && w.Status      == CRWarrantyStatus::Active
{
    n++;
}
info(int2Str(n));

Question: what number is displayed?

The decisive keyword is outer join. An outer join returns every record from the first table, combined with each matching joined record, and once with empty joined fields when there is no match. Trace: the first customer contributes two rows (one per active warranty), the second one row and the third one row with an empty warranty buffer. The loop runs four times and displays 4. If the join were exists join, each customer with at least one match would appear once: 2. If it were notexists join, only the third customer: 1. If it were a plain inner join: 3. A single changed keyword produces four different answers, which is why examiners like this pattern.

Listing 4: what happens to the transaction?

Listing 4. Nested transactions with an error thrown in the inner block.
ttsbegin;
warrantyA.selectForUpdate(true);
warrantyA.Status = CRWarrantyStatus::Void;
warrantyA.update();

try
{
    ttsbegin;
    warrantyB.selectForUpdate(true);
    warrantyB.Status = CRWarrantyStatus::Void;
    warrantyB.update();
    throw error('Void rejected');
    ttscommit;
}
catch (Exception::Error)
{
    info('Handled');
}
ttscommit;

Question: which warranties are void afterwards, and is "Handled" displayed?

The decisive facts are the transaction rules from lesson 4. An exception other than UpdateConflict or DuplicateKeyException thrown inside a transaction aborts the whole transaction to the outermost level, and catch blocks inside the transaction are not entered. The try block here is inside the outer transaction, so the catch is skipped, both updates are rolled back and the exception travels to whatever catch exists outside the outer ttsbegin. Neither warranty is void, and "Handled" is not displayed. The Infolog shows "Void rejected". Candidates who read the try and catch as they would in C# pick "warranty A void, Handled displayed", which is the distractor.

Listing 5: is it set-based?

Listing 5. The alert queue table has an overridden update method that writes a log line, and database logging is switched on for updates.
CRInspAlertQueue queue;

queue.skipDataMethods(true);
update_recordset queue
    setting Processed = NoYes::Yes
    where queue.Processed == NoYes::No
       && queue.CreatedDateTime < cutoff;

Question: does this run as one SQL statement?

Two reasons for fallback are present: an overridden update method and database logging. skipDataMethods(true) removes the first reason but not the second. The statement falls back to row-by-row. To run set-based, the code would also need skipDatabaseLog(true), and the team would have to agree that skipping the log is acceptable. In the hardening clinics the answer was to switch off the accidental database log, with Thandeka's agreement, rather than skip it in code. The exam likes listings in which one fallback reason is handled and another is not.

Listing 6: what is the event, and when does it run?

Listing 6. A data event handler on a custom table.
class CRInspCertEventHandlers
{
    [DataEventHandler(tableStr(CRInspectionCertTable), DataEventType::ValidatedWrite)]
    public static void CRInspectionCertTable_onValidatedWrite(Common _sender, DataEventArgs _e)
    {
        CRInspectionCertTable cert = _sender as CRInspectionCertTable;
        ValidateEventArgs     args = _e as ValidateEventArgs;

        if (!cert.CertificateDate)
        {
            args.parmValidateResult(checkFailed("@CRCustom:CertDateRequired"));
        }
    }
}

Question: does this handler stop a certificate without a date from being saved through the form?

The decisive line is the attribute: a ValidatedWrite data event, which fires after validateWrite has run. The handler can change the validation result through ValidateEventArgs, and the form uses that result to decide whether to save. So yes: a certificate without a date is rejected with the label's message. Two distractors are common. One says data event handlers cannot affect validation; they can, through the event arguments. The other says the handler runs after the insert; that is the Inserted event, not ValidatedWrite. Note also that because the table is Cobalt Ridge's own, putting the rule directly in its validateWrite method would be simpler; handlers and wrappers are for tables you do not own.

Listing 7: which test fails?

Listing 7. endDate returns dateMthFwd(installDate, months).
class CRPumpWarrantyCalculatorTest extends SysTestCase
{
    [SysTestMethod]
    public void endDate_LeapDay()
    {
        CRPumpWarrantyCalculator calc = CRPumpWarrantyCalculator::construct();
        this.assertEquals(mkDate(28, 2, 2025), calc.endDate(mkDate(29, 2, 2024), 12));
    }

    [SysTestMethod]
    public void endDate_Ordinary()
    {
        CRPumpWarrantyCalculator calc = CRPumpWarrantyCalculator::construct();
        this.assertEquals(mkDate(14, 10, 2027), calc.endDate(mkDate(14, 10, 2026), 12));
    }
}

Question: which test fails?

Trace each. mkDate takes day, month and year in that order. The leap-day test expects February 28, 2025: dateMthFwd of February 29, 2024 by 12 months gives February 28, 2025, so it passes. The ordinary test expects October 14, 2027 for an installation on October 14, 2026 with 12 months, and dateMthFwd moves October 14, 2026 forward 12 months to exactly that date. It passes too. Neither fails. Questions sometimes ask which of several tests fails when none does, or two do; read every assertion rather than assuming one is wrong. If you misread mkDate's argument order as month, day, year, you would pick the wrong answer, which is the trap here.

Common traps in listings

The traps that recur in code-reading questions.
TrapWhat to look forWhere it was reviewed
next inside a conditionA wrapper that calls next in an if or loopLesson 5
Join keyword swappedouter, exists, notexists and inner joins return different rowsLesson 4
Missing forupdateAn update of a record not selected for updateLesson 4
Catch inside a transactionA try and catch nested inside ttsbeginLesson 4
Silent fallbackA set-based statement on a table with overrides, logging or handlersLesson 7
Wrong eventInserted versus Inserting, ValidatedWrite versus ValidatingLesson 5
Argument ordermkDate(day, month, year); strFmt placeholders numbered from 1Lesson 4
Wrong menu item kindOutput for reports, action for classes, display for formsLesson 5

Hot area listings

Some questions show a listing with gaps, each with a drop-down list. The method still applies, but read the whole listing before choosing any value, because a later line often constrains an earlier gap. For example, if a later line calls update on a buffer, the select gap must include forupdate; if a later line reads fields from a joined table, the join cannot be an exists join, because exists joins return no fields.

Worked problem

Filling a hot area

A listing selects a purchase line into a buffer, then on a later line reads the joined certificate's heat number and finally updates the line's inspection status. The gaps are: the select keyword (options: firstonly, forupdate, firstonly forupdate) and the join (options: exists join, outer join, join). Which values complete it correctly?

Show solution
  1. The update at the end needs the line selected forupdate.
  2. Only one line is needed, so firstonly is sensible; the combined option firstonly forupdate covers both.
  3. The heat number is read from the joined certificate, so the join must return fields: join or outer join, not exists join.
  4. If the line might have no certificate and must still be updated, choose outer join; if a certificate must exist, choose join.

Answer: firstonly forupdate, and join or outer join depending on whether a missing certificate is allowed; the question's constraint words decide.

Practicing the skill

Prudence kept practicing by reading rather than writing. Each evening she opened one standard class in Application Explorer, such as a posting class or a data provider, and read one method end to end, writing in her notes what it did and which hooks it offered. She also reread her own pull requests from the autumn, deliberately looking for the faults reviewers had found. Desmond added one rule: for every listing, say the answer out loud before looking at the options, because options are designed to make wrong answers look familiar.

Reading listings about frameworks

Framework listings are longer, and the trick is to recognize the shape quickly. A class with DataContract on the class and DataMember on parm methods is a data contract. A class that extends SysOperationServiceController and sets a class name and method name in its constructor is a controller. A class with a method that takes the contract as its only parameter is the service. A class that extends SrsReportDataProviderBase or its preprocessing variant and has processReport is a report data provider. A class with the SysTestMethod attribute on its methods is a test. Once you have named the shape, the question usually asks about one detail: which attribute is missing, which method the controller calls, which execution mode runs the job in the background, or which temporary table type the data provider should use.

Prudence practiced by covering the class name in a listing and naming its shape from the attributes alone. It took a week to get fast at it. Desmond's comparison was reading a building plan: you do not read every line; you find the walls first, then the doors.

When the listing is wrong on purpose

Some questions show code with a fault and ask which change fixes it. The faults are almost always one of a small set: a missing forupdate before update; next inside a condition; a catch inside a transaction expected to handle an error; a set-based statement that will fall back; an InMemory table joined in SQL; an unbalanced ttsbegin without its ttscommit; a select inside a loop that should be a join; or a display method without caching on a busy grid. When you see a fault question, run through this list before reading the options. More often than not, the fault is on it.

A second kind of deliberate fault is a correct listing in the wrong place: a Chain of Command wrapper on a private method, a handler that subscribes to the wrong event for the timing the scenario requires, or test code placed in the production model. The code itself may look fine, but the answer is wrong because the scenario's constraint is not met. Step five of the method, checking the constraint words, catches these.

Common mistakes

  • MistakeReading try and catch in X++ as if it were C#.

    InsteadInside a transaction, most exceptions skip local catch blocks and abort to the outermost level.

  • MistakeAssuming code after next cannot change the result.

    InsteadCode after next can read and replace the return value.

  • MistakeChoosing values in a hot area from top to bottom.

    InsteadRead the whole listing first; later lines constrain earlier gaps.

  • MistakeAssuming one test must fail.

    InsteadTrace every assertion; none, one or several may fail.

Summary and key terms

  • Use a five-step method: question first, element kind, decisive lines, one concrete trace, constraint check.
  • Attributes identify the kind of code and the rules that apply.
  • One keyword (a join type, forupdate, firstonly) often separates the right answer from the distractors.
  • Transactions abort to the outermost level and skip local catches, except for UpdateConflict and DuplicateKeyException.
  • Set-based statements fall back when any one of several reasons remains.
Decisive line
The line in a listing whose detail determines the answer, such as an attribute, a join keyword or a next call.
Trace
Following one concrete input line by line through code.
Outer join
A join that returns every record from the first table, with joined fields when a match exists.
ValidatedWrite
The data event raised after validateWrite, which can change the validation result.
Fallback
A set-based statement that silently runs row by row.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. In listing 3, what would an exists join display?

    Show answer

    2, one row per customer with at least one active warranty.

  2. Why is "Handled" not displayed in listing 4?

    Show answer

    The catch is inside a transaction, so it is skipped and the whole transaction aborts.

  3. Which two calls make listing 5 set-based?

    Show answer

    skipDataMethods(true) and skipDatabaseLog(true), if skipping is acceptable.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz