I was wondering if there is a way to simplify something I use very very often. 2 examples:

I was wondering if there is a way to simplify something I use very very often. 2 examples:

Counting records in array, based on some value:

Cnt := 0;
for i := 0 to High(Array) do
If Array[i].Selected do // Selected = boolean
Inc(Cnt);

Is it possible something like:

Cnt := 0;
for i := 0 to High(Array) do
Inc(Cnt, Array[i].Selected);

So, extending Inc to increment only if condition is true.


Another example, for Exit method - I regularly check for conditions when function needs to exit:

if Not Condition then
begin
ShowMessage('Condition not met');
Exit;
end;

Is it possible to do something that would be Message and Exit in 1 line:

If Not Condition then
Exit('Condition not met');

or

If Not Condition then
myExit('Condition not met');

in this case my custom myExit method would do ShowMessage and then return Exit command back to the method.

I know these 2 examples are not possible, but maybe somebody found similar solutions.

Comments

  1. try property below code for EXIT procedure;

    unit myUnit;
    ......
    Type
    TCondition=(false,true);
    const
    MsgCondition: Array[TCondition] of String=('Msg 1','Msg 2');
    ......

    unit Unit1;
    ......
    Type
    ......
    private
    FCondition: TCondition;
    procedure setCondition(Value: TCondition);
    public
    property condition: TCondition read FCondition write setCondition;
    ......
    procedure setCondition(Value: TCondition)
    begin
    FCondition := Value;
    ShowMessage(MsgCondition[Value]);

    case Value of
    true: ...
    false: ...;
    end;
    end;
    ......

    condition := true;

    ReplyDelete
  2. This thread has been a huge disappointment to me

    ReplyDelete
  3. 方念渝 Thank you, but your example seems a bit too much for me. Quite creative, though!

    ReplyDelete

Post a Comment