Record helpers can do wonders for code clarity.

Record helpers can do wonders for code clarity.

// Never mind the silly example

TResult = (CompletedOK, PartiallyPerformed, NothingHappened, HorriblyWrong);

function DoSomething:TResult;

begin

Result := PartiallyPerformed;

end;

How do we determine failure vs success?

if not DoSomething = CompletedOK then …?

What about Partially performed and nothing happened?

Enter the helper:

TResultHelper = record helper for TResult

function Failed:Boolean;

function Success:Boolean;

end;

function TResultHelper.Failed: Boolean;

begin

Result := (Self = HorriblyWrong);

end;

function TResultHelper.Success:Boolean;

begin

Result := not Failed;

end;

Now we can write

if DoSomething.Failed then …

Note that you also can enter the murky waters of obfuscation through helpers, but at least the murkiness will be consistent 😛

13 thoughts on “Record helpers can do wonders for code clarity.


  1. In plain pascal, I will define in the same unit than TResult:


    const RESULT_FAILED = [HorriblyWrong];


    and write a clean


    if DoSomething in RESULT_FAILED then …


    Sounds MUCH cleaner to me than using a record helper.

    Like


  2. or


    TResultSet = Set of TResult;


    const


    RESULT_FAILED = [HorriblyWrong];


    RESULT_SUCCESS = [CompletedOK, PartiallyPerformed, NothingHappened];


    type


    TResultHelper = record helper for TResult


    function Success(const SuccessStates:TResultSet = RESULT_SUCCESS):Boolean;


    function Failed(const FailStates: TResultSet = RESULT_FAILED):Boolean; //




    function TResultHelper.Success(const SuccessStates:TResultSet): Boolean;


    begin


    Result := (Self in SuccessStates);


    end;


    function TResultHelper.Failed(const FailStates: TResultSet): Boolean;


    begin


    Result := (Self in FailStates);


    end;


    to allow you to deviate from the defaults on need.

    Like

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.