Search code examples
delphifiremonkeydelphi-10-seattle

Generate compiler error if property is not set


I want to be able to create a compiler error/warning if a certain property in my object is not set. Let's say I have the following class:

interface

type
  TBarkevent = procedure (Bark : String) of object;

  TDog = class
  private
    FOnBark : TBarkevent;
    procedure SetBark(const Value: TBarkevent);
    function GetBark: TBarkEvent;
  public
    procedure Bark;
    property OnBark : TBarkEvent read GetBark write SetBark;
    constructor Create;
  end;

implementation

{ TDog }

procedure TDog.Bark;
begin
  if Assigned(OnBark) then
    OnBark('Woof!')
end;

constructor TDog.Create;
begin
end;

function TDog.GetBark: TBarkEvent;
begin
  Result := FOnBark;
end;

procedure TDog.SetBark(const Value: TBarkevent);
begin
  FOnBark := Value;
end;

I make use of the TDog class in another unit like this:

var
  Dog : TDog;
begin
  Dog := TDog.Create;
  Dog.OnBark := DogBark;
  Dog.Bark;

Now, once the Bark() procedure is called, the OnBark event is triggered.

My Question:

Is it possible for me to make it mandatory to specify the OnBark property, so that a compiler error/warning is emitted if the event is not set?


Solution

  • Define your class as:

    TDog = class
    private
      FOnBark : TBarkevent;
      procedure SetBark(const Value: TBarkevent);
      function GetBark: TBarkEvent;
    public
      procedure Bark;
      property OnBark : TBarkEvent read GetBark write SetBark;
      constructor Create(Bark : TBarkEvent);
    end;
    

    That way, you can't instantiate a TDog object without specifying an event. If you try, you'll get a compiler error.