Einzelnen Beitrag anzeigen

Blup

Registriert seit: 7. Aug 2008
Ort: Brandenburg
1.429 Beiträge
 
Delphi 10.4 Sydney
 
#6

AW: Globale Variablen richtig nutzen

  Alt 16. Jan 2017, 09:04
Den Anwendungskern solltest du immer so realisieren, dass nicht direkt auf globale Variablen zugegriffen wird. Nur so kann dieser unabhängig von der Anwendung getestet werden. Dafür bietet sich z.B. eine Schnittstelle an, die nur die Aufgabe hat solche Umgebungsvariablen bereitzustellen.
Beispiel:
Delphi-Quellcode:
interface
  IAnwendungsfall1Config = Interface(IInterface)
    [GUID]
    function GetSetting1: Integer;
    procedure SetSetting1(AValue: Integer);
    function GetSetting2: string;
    property Setting1: Integer read GetSetting1 write SetSetting1;
    property Setting2: string read GetSetting2;
  end;

  TAnwendungsfall1Config = class(IAnwendungsfallConfig)
    constructor Create(var ASetting1: Integer; const ASetting2: string);
  private
    FSetting1: PInteger;
    FSetting2: string;
  public
    function GetSetting1: Integer;
    procedure SetSetting1(AValue: Integer);
    function GetSetting2: string;
  end;

  TAnwendungsFall1 = class()
    constructor Create(const AConfig: IAnwendungsfallConfig; const AFileApi: IFileApi; const ADbFramwork: IDbFramwork);
  private
    FConfig: IAnwendungsfallConfig;
    FFileApi: IFileApi;
    FDbFramwork: IDbFramwork;
  public
    procedure TuWas;
  end;

implementation

constructor TAnwendungsfall1Config.Create(var ASetting1: Integer; const ASetting2: string);
begin
  FSetting1 := @ASetting1;
  FSetting2 := ASetting2;
end;

function TAnwendungsfall1Config.GetSetting1: Integer;
begin
  Result := FSetting1^;
end;

procedure TAnwendungsfall1Config.SetSetting1(AValue: Integer);
begin
  FSetting1^ := AValue;
end;

function TAnwendungsfall1Config.GetSetting2: string;
begin
  Result := FSetting2;
end;

constructor TAnwendungsFall1.Create(const AConfig: IAnwendungsfallConfig; const AFileApi: IFileApi; const ADbFramwork: IDbFramwork);
begin
  inherited Create;
  FConfig := AConfig;
  FFileApi := AFileApi;
  FDbFramwork := ADbFramwork;
end;

procedure TAnwendungsFall1.TuWas;
begin
  FConfig.Setting1 := FFileApi.TuWas(FConfig.Setting1);
  FDbFramwork.TuWas(FConfig.Setting2);
end;
Erzeugen des Anwendungsfalls in der Anwendung:
Delphi-Quellcode:
   Config := TAnwendungsfall1Config.Create(GlobaleVariable1, GlobaleVariable2);
   AnwendungsFall1 := TAnwendungsFall1.Create(Config, GlobalFileApi, GlobalDbFramwork);
Im Testprojekt würde man beim Erzeugen für jeden Testfall eigene Variablen nutzen und die API simulieren.
  Mit Zitat antworten Zitat