📜 ⬆️ ⬇️

Fluent interface and Delphi

Fluent interface (Fluent interface) is a very young method, even more like a design pattern, which has gained popularity and wide distribution among Java, C #, and PHP coders.
In most of the “good code” techniques, the text of the code (discharging lines, spaces, indents, etc) lies, and this is very cool, but sometimes it turns into hell. Scrolling through the code, memorizing the method call chain, the eternal dilemma between the long method and readability, etc.
But the solution is - Fluid interface! Now on Delphi!

So what is a fluid interface?

In short, it is the simplification of multiple calls to methods of a single object, using a chain of methods that return the object that called it (that is, itself). It sounds difficult, but it looks very easy and simple:
CreateFluentBinaryWriter(Stream) .WriteString('active') .WriteByte(130); 

Implementation

The interface looks elementary - like this:
 IFluentBinaryWriter = interface function WriteByte(Value: Byte): IFluentBinaryWriter; function WriteString(Value: string): IFluentBinaryWriter; end; 

The auxiliary function of creating a class that implements an interface looks very simple - like this:
 function CreateFluentBinaryWriter(AStream: TStream): IFluentBinaryWriter; begin Result := TFluentBinaryWriter.Create(AStream); end; 

Further, all functions of the flowing interface must return an instance of the class that called this function.

As for example, the WriteString function writes a string to a stream (TBytesStream), and returns an instance of the class that called this function.
 function TFluentBinaryWriter.WriteString(Value: string): IFluentBinaryWriter; begin fBinaryWriter.Write(Value); // TBinaryWriter Result := Self; end; 

That's all! Actually, this could have been completed, but there is one very interesting implementation!

Option two - more difficult

 CreateFluentStringWriter(Stream) [' '] [''] ['!']; 

Here we will go for a little trick. Declare Attrib Property
 property Attrib[Value: string]: IFluentStringWriter read AddString; default; 

and in the AddString function, we write the requested string to the stream and return, as a result, an instance of the class that called this function.
 function TFluentValueWriter.AddString(Value: string): IFluentValueWriter; begin fBinaryWriter.Write(Value); // TBinaryWriter Result := Self; end; 

PS

Using a fluid interface is quite extensive, and along with anonymous procedures you can achieve very compact and self-documenting code!

')

Source: https://habr.com/ru/post/191170/


All Articles