0

It's good to code with interface, but does it's a good practice to have method that return interface ?

function CallWebService; IWebServiceReturn;

With that I don't need to free the result of the method and guard from memory leak.

Some people say it's useless, need to be keep for service, and generate more code (a unit for interface, a unit for implementation) than just have a class (or a record) :

function CallWebService; TWebServiceReturn;

For exemple I can have this interface, use to all my result method :

IReturn = interface
  procedure GetResult : boolean;
  function SetResult(aResult: boolean);
  property Result: boolean read GetResult write SetResult;
end;

That I use like that :

var
  Return: IReturn;
begin
  Result := ProcessMessage(CurrentMessage);
  // ...

And in a special call I may need to have more data in the result, so I will create a new interface :

IWebServiceReturn = interface(IReturn)
  procedure GetJson : string;
  function SetJson(aJson: string);
  property Json: string read GetJson write SetJson;
end;

That I will use like that :

var
  Return: IWebServiceReturn;
begin
  Result := CallWebService(Path);
  // ...

And if later, a new call need to get something else I will too create an interface and the class implementation.

That's on this point that we don't have the same opinion on the team. Some developer see that like a waste of time which will complicate the code.

Apparently they prefer to do something like that :

function CallWebService(Path: string; var Json: string): boolean;

And if you want more data you need to change the method signature..

Too less couple the code I think it's better that always use record or class, this abstraction is necessary if we want to create SOLID code.

Bosshoss
  • 783
  • 6
  • 24
  • https://stackoverflow.com/questions/1992384/program-to-an-interface-what-does-it-mean Have a look at this it might help – Jabir Oct 22 '20 at 08:10
  • https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface This has some more details – Jabir Oct 22 '20 at 08:10
  • 1
    There's no point having the interface if you don't use it. – khelwood Oct 22 '20 at 08:11
  • You made a nice mess out of your question. Are you interested in Java or Delphi? General OOP principles are the same but interfaces in Delphi are more complex topic and there are different reasons beyond OOP why you would want to use them or why they would be bad choice. If you could a elaborate your use case a bit more it could help. In particular what lifetime your objects have, how often you need to create new instance, is is shared object or not... – Dalija Prasnikar Oct 22 '20 at 20:01
  • I'm interessed in Delphi, I updated the question with some use case – Bosshoss Oct 23 '20 at 06:05

1 Answers1

0

I think it's the correct approach when a method can return different implementations, like in the factory design pattern.

MauroB
  • 510
  • 4
  • 12