Einzelnen Beitrag anzeigen

Benutzerbild von Sir Rufo
Sir Rufo

Registriert seit: 5. Jan 2005
Ort: Stadthagen
9.454 Beiträge
 
Delphi 10 Seattle Enterprise
 
#10

AW: Globale Variablen/Abhängigkeiten = Böse... Und nu?

  Alt 19. Mai 2014, 10:55
Abhängigkeit und schwer testbar
Delphi-Quellcode:
unit FooUnit;

interface

type
  TFoo = class
    property Value : string;
  end;

function Foo : TFoo;

implementation

var
  _Foo : TFoo;

function Foo : TFoo;
begin
  if not Assigned( _Foo ) then
    _Foo := TFoo.Create;
  Result := _Foo;
end;

end.
Delphi-Quellcode:
unit BarUnit;

interface

uses
  FooUnit;

type
  TBar = class
    function GetValue : string;
  end;

implementation

function TBar.GetValue : string;
begin
  Result := Foo.Value;
end;

end.
Das sollte man besser so machen:
Delphi-Quellcode:
unit BarUnit;

interface

uses
  FooUnit;

type
  TBar = class
  private
    FFoo : TFoo;
  public
    constructor Create( AFoo : TFoo );
    function GetValue : string;
  end;

implementation

constructor TBar.Create( AFoo : TFoo );
begin
  inherited;
  FFoo := AFoo;
end;

function TBar.GetValue : string;
begin
  Result := FFoo.Value;
end;

end.
Jetzt kann TBar auch mit unterschiedlichen TFoo -Instanzen getestet werden.
Kaum macht man's richtig - schon funktioniert's
Zertifikat: Sir Rufo (Fingerprint: ‎ea 0a 4c 14 0d b6 3a a4 c1 c5 b9 dc 90 9d f0 e9 de 13 da 60)
  Mit Zitat antworten Zitat