Wednesday, November 16, 2022

Escape the Button-Click development. Part I

Over decades one major selling point for Delphi was the easy development pattern of...
Place a button on the form, click it, and put the source inside the auto-created onClick procedure.

If you have never programmed like this throw the first stone.

Is it bad?

Who am I to criticize generations of developers who have created countless products and built their businesses this way?

If you do not want to create unit tests - this way of development is probably not a problem. Perhaps your project was growing over time, I bet there was a point in time when you recognized that your source code reaches a state where it was barely maintainable. You're afraid to change something because there's a big possibility that something else will break with that change. Am I right?

I also bet you have heard about unit testing, but you were unable to adapt these simple unit test examples to your project and that's why you don't "believe" in unit testing at all...

Still not interested in unit testing?
You don't want to refactor a single line of code in your project?

ok, in this case, you can stop reading... Have a nice day.

Since you're still reading on...

Part I


Let's talk about:

- Dependency Injection
- Composition (Root)

I do not talk about MVVM  - this time -, because converting a legacy project to MVVM is not an easy task by changing a few lines of code.

So what can we do to make a first and easy step? Perhaps your First idea is to separate code from your forms... Also not so easy, because the code is full of links into form components and I bet you hold all your data in visual components. Especially if you don't use DB or other data-aware components on your form.

So lets start simple:

Take one form and create a new unit with a comparing name... Like customers.pas/dfm -> customers.handler.pas. You can call it customers.controller.pas or even customers.viewmodel.pas.

For every onClick, onDBLClick and so on you create a procedure in the new unit. As we are not in the strict MVVM envirement this time you can reference the form instance in the new unit. After some copy and paste you can delete some uses in your form unit. (This was the stupid part)

Your application should work the same ways as before.

Next step is to create a class in your new unit an put all your procedures into this class. (of course you can skip the first step an create the class directly). Now we need "somebody" to create and hold this class.

Your form could do this job or you create a Unit Compositon.pas where you put all your form and viewmodel creation.

The you only need to link this unit to create every other unit.
Like TCompositon.CustomerView.ShowModal.

Type
  TComposition = Class abstract
    public
      Class function CustomerView : TForm;
  end;

Class function TComposition.CustomerView : TForm;
begin
  Result := TCustomerView.Create(Application);
  Result.ViewModel := TCustomerViewModel.Create;
end;

If you need any business logic in your Customer.ViewModel you could also use a dependency injection for this or you use a global service-locator...

But this part we will see in part two.

Have a nice day.









Sunday, May 22, 2022

How to format your Delphi-Sourcecode!

At first:

Formatting your source code the Embarcadero way is not a mistake or to make it clear, probably the best way to format your code. Especially if you want to share your code with other developers.

But...This is not my way...

So I'm doing it wrong? No... I have good reasons to format my source code in a different way!



I have implemented some of my formatting rules many many years ago and some of them in the last 5 years. Some rules I developed at a time when nobody talked about that a procedure should have only 75 lines or "must" always fit completely on the screen. Therefore it was necessary to guess from the formatting what is "hidden" in the invisible part.

There are four kinds of rules:

  1. Formatting and Indenting
  2. Formatting on Syntax
  3. Naming
  4. Empty lines or other "small things"

All rules are "just" to make the code more readable or in some cases better maintainable.

One drawback of my rules: No formatter is able to format Delphi source code 100% according to my rules.

Therefore I started the development of my own code formatter some time ago. My formatter is using a different approach to format code. First, a tokenizer creates the syntax tree, and then a procedure is called for each part.

E.g. to format the uses list, a procedure "format_Uses" with all the necessary sources is called. By default, the code just formats it the Embarcadero way or you could implement your own method for this. So beyond some settings, you can do everything!

I'm very busy with my main "job" for some time and that's the reason this project is in the WIP folder.

So enough talk, here are my rules.

Let's start with a simple one... And don't expect a complete list here it would be out of scope for a little blog post. If you like my style of formatting or my rules, please write a comment. If enough developers would like to see more, perhaps I consider writing a complete rule book.

case Whatever of
  whNone : ;
end; // of case

All case ends gets this comment because this end is the only end without a begin.

TFoo = class   
  private
   
fWhatever : String;
   
fCount    : Integer; 

    function 
GetWhatever : String;
    procedure
SetWhatever( Const aValue : String );
    function  GetCount : Integer;
    procedure SetCount( aValue : Integer );
  public
    Constructor Create;
    Destructor  Destroy;override;

    Property Whatever : String  read GetWhatever write SetWhatever;
    Property Count    : Integer read GetCount    write SetCount;
end;

OK, this end has also not a begin, but the is not inside the source code where you have multiple levels of begin ends. For many years I've written FWhatever, but a lower f is more readable in many cases, like FField or fField. The lower "f" is easier to ignore while reading. Also, every function gets an extra space so that the method names are in the same column. the sane for the destructor. There is an empty line after the vars... And the properties got formatted by length for better readability.

Please compare this with:

TFoo = class   
private
  
FWhatever:string;
  
FCount:Integer; 
  function
 GetWhatever:String;
  procedure 
SetWhatever(const AValue:string);
  function GetCount:Integer;
  procedure SetCount(AValue:Integer);
public
  Constructor Create;
  Destructor Destroy;override;
  Property Whatever:String read GetWhatever write setWhatever;
  Property Count:integer read GetCount write SetCount;
end;

Well-formatted source code becomes more and more important for me the older I get.

Naming

Again field values get a lower "f", params get a lower "a", local vars in methods get a lower "l", and const values get a lower "c". I know the small l is not so easy to distinguish from the upper "I", for Interfaces.

But you would never write IFoo := NIL... 

User   
 
System.SysUtils
, System.Classes
, FMX.Graphics
, Web.HTTPApp
, FireDAC.Phys
, FireDAC.Phys.MySQL
// , FireDAC.Phys.SQLite
, Delphiprofi.FDK.FireDAC
, Delphiprofi.FDK.QRCode
, Delphiprofi.FDK.Server.ISAPIHandler
{$IFDEF DEBUG}
, Delphiprofi.FDK.Logging
{$ENDIF}
, Settings
, HTMLHandler
;

By formatting the uses with a leading "," and only one unit for each line, you can easily comment out some units and excluded unis by IFDEF is much better readable. After that, I like to sort my units..

  1. System
  2. Plattform
  3. Other RTL
  4. Frameworks like my FDK
  5. Units from the project. 

Please compare this with:

User   
  
Settings, Web.HTTPApp, System.SysUtils, Delphiprofi.FDK.FireDAC,
FMX.Graphics, {FireDAC.Phys.SQLite}, Delphiprofi.FDK.Server.ISAPIHandler, FireDAC.Phys, FireDAC.Phys.MySQL, System.Classes, Delphiprofi.FDK.FireDAC, Delphiprofi.FDK.QRCode, Delphiprofi.FDK.Server.ISAPIHandler{$IFDEF DEBUG}, Delphiprofi.FDK.Logging{$ENDIF}, HTMLHandler;

Formatter on Syntax

Do you remember these days, when your source looked like this:?



These days I created a simple rule...

Do you know, if the "if FileExists ..." has an else part? No, not from this point in the source code. Then you have to scroll down and if the procedure is very long, you have to scroll way too far down for this information.
If the "if" has an else part, the "then" is in the next line, if not the then is in the same line as the "if".

So simple, this if has an else:

if FileExists(fLogFilename) 
  then begin
         FS := TFileStream.Create(fLogFileName, fmOpenReadWrite);
...

This if has no else:

if FileExists(lLogFilename) then
  begin

    FS := TFileStream.Create(lLogFileName, fmOpenReadWrite);
...

Of course, never format it this way, because the lines from begin to end do not work:

if FileExists(LogFilename) then begin
  FS := TFileStream.Create(LogFileName, fmOpenReadWrite);
...

So it look like this if you have only one line:

if 
FileExists(aLogFilename)
  then FS := TFileStream.Create(aLogFileName, fmOpenReadWrite)
  else FS := TFileStream.Create(aLogFileName, fmCreate);

In any other cases, it looks like this:

if FileExists(cLogFilename)
  then begin
         FS := TFileStream.Create(cLogFileName, fmOpenReadWrite);
         Whatever := 'XX';
       end
  else begin
         FS := TFileStream.Create(cLogFileName, fmCreate);
         Whatever := 'YY';
       end;


and by the way... cLogFilename a const not a var anymore. And if you look up you can recognize one var is a (l) local, one is part of an object (f), and of is a param to this method (a) containing this code... If you just write LogFilename like in the bad example - you have no clue where the var is defined.

Empty lines and CR's


Where to put an empty line an where not, is the most overseen method to make your code more readable. Let's take a look at this bad example (stupid code):

Procedure TMainModel.LogVars(LogFilename:string);
var i:Integer;FS:TFilestream;
begin
 
LogFilename:=TPath.Combine(Path,Logfilename);startconvert:=true;
  if FileExists(LogFilename) then begin
    FS := TFileStream.Create(LogFileName, fmOpenReadWrite);
  end else FS := TFileStream.Create(cLogFileName, fmCreate);
  for i:=0 to varlist.count.1 do begin
    for var k:=0 to varlist.count-1 do varlist[k] := prepare(varlist[k]);
    
fStartConvert := true;
    if varlist[i].MustConvert then convert(varlist[i]);
    Case varlist[i].Kind of
      tkStrLog(FS,varlist[i].ForLog);
      tkInt : 
Log(FS,varlist[i].AsString);
    end;
    if varlist[i].MustConvert then reconvert(varlist[i]);
  end;
  startconvert:=false;
end;


{ -------------------------------------------------------------------------
  (c) by Peter Parker
  1998 Version 1.0 of Whatever...
  Procedure to display a message 
  ------------------------------------------------------------------------- }

Procedure TMainModel.Whatever(Display:string);
begin
  if Display.trim<>'' then MyMessage(Display) else
    raise Exception.Create('no Text to Display')
  if Display='-' then Memo1.Lines.Clear;
end;

Ok, now use my rules... before every "for" there is an empty line, also after the "for". The same rule applies to "if" and case, but not if before is a "begin" or "try" or after is an end ( of course ). Only one empty line between methods. Never write code behind an "elseless" then. (if you read the Display trim stuff... at the first millisecond it looks like this "if" raises the exception.  Here is my code (and simple i is kept, and no stupid comments) :


Procedure TMainModel.LogVars( Const aLogFilename : String );
Var 
  i            : Integer;
  lFS          : TFilestream;
  lLogFilename : String;
begin
  
lLogFilename  := TPath.Combine(cPath, aLogfilename);

  if FileExists(lLogFilename) 
    then lFS := TFileStream.Create(cLogFileName, fmOpenReadWrite)
    else lFS := TFileStream.Create(cLogFileName, fmCreate);

  try
    for var k := 0 to varlist.count - 1 do
      
varlist[k] := prepare(varlist[k]);
    
    for
 i := 0 to varlist.count - 1 do
      begin
        fStartConvert := true;

        if varlist[i].MustConvert then 
          convert(varlist[i]);

        Case varlist[i].Kind of
          tkStr : Log(FS,varlist[i].ForLog);
          tkInt : 
Log(FS,varlist[i].AsString);
          
{$IFDEF DEBUG}
          else raise DeveloperException.Create('you forgot a case entry for .Kind');
          {$ENDIF}
        end; // of case
  
        if varlist[i].MustConvert then 
          reconvert(varlist[i]);
      end;
  finally
    lFS.Free;
  end;

  if fStartConvert then
    fStartConvert := false;
end;

Procedure TMainModel.Whatever(Display:String);
begin
  if Display.trim = '' then
    raise Exception.Create('no Text to Display'); 

  MyMessage(Display);
end;

Every case that has a limited set will raise an exception so you "never" forget to update your cases. If possible Early exit a procedure - this rule for (exit and exceptions). Strings as params get a "Const"... Sometimes you need a local var because of "const", but better if you copy it to a local instance at the very end than passing strings around without a "const". (Consider the string has passed around more than one method.

Now I hope you have an idea why I do it my way. If you consider that my rules are something you would like to use in your code... Be my guest and please leave a comment.

Monday, March 21, 2022

What is the easiest way to create a dynamic web page?

Before I will talk about the topic: Yes, my #DMVVM project is still on hold. I was just too busy to find the time to do the last steps.



I do not talk about the HTML part... From my point of view, it has to be Bootstrap or something similar, so that every target device could be used.

Of course, I'm not talking about static HTML pages, and if you know me just a little bit, you know that I hate PHP and wouldn't use it.

I haven't tested the cross-compiler for Pascal to javascript yet, so even though I've seen it before, I can't really make a judgment on it
.
Of course, I have been using the Webbroker functionality for my WEB projects for years. This technology is ideal for dynamic websites. 
In the past, I had also set up projects with ASP.NET - actually the absolute best way to execute server-side code. Unfortunately, the last compiler (except Prism) was Delphi 2007 and nowadays I would like to use features of the current Delphi versions and compile my ISAPI.DLL to 64 bit.

One really good feature of the Webbroker is, that you can also create it for Linux, but in my case, I always use a Windows-Server. So while the ISAPI.DLL is loaded only once into the memory space of the IIS. The execution performance is the best you can get. Native code running directly on the CPU to deliver the content. 

So why not use it and be happy?

You can upload an HTML file to the Server, you can change tokens to any value you like, you can use a table-producer to show a complete database table inside your content...

But there is one drawback: For every change, you have to recompile your DLL and upload it to the server.
This is of course the same or even more painful if you're not the web designer.

While searching the internet for ideas I found a Razor implementation from Marco Cant√Ļ. A nice little piece of code to integrate some functionalities to HTML. But after one day of rewriting, I stop the development and forgot about this idea.

One year later I was working on a new idea to upgrade my TWebbrowser interface to a new level. In our main application, we are using the TWebbrowser component to autofill forms of many different websites. 

(Sad story, which would lead too far here, why the various websites are not able to provide a simple REST web interface)

Some of these websites are disabling the IE so I must upgrade to EDGE. 

With this interface I have reached the same point as with the web design: For every change, I have to recompile the main program.

End of the story? 

Of course not. I had worked briefly on a project where I wrote a UI test framework for our software. For this, I had to use the Pascal script from RemObjects. A small IDE was quickly put together with these components. Unfortunately, the component is somewhat "unwieldy" and I hate to install packages into my IDE. On top, I do not like to click invisible components on a form.

Therefore I wrote - as always - an interface wrapper for these components...

An IDE interface with compiler and runtime and of course separate compiler and runtime.

To do it right from the start, I created the wrapper directly in Fluentdesign and included it in my FDK right away.

Using this Wrapper for webform autofill was done in minutes and now I'm able to load the right methods to do the autofill from our website, without installing a software update of our main application.

Maybe you already have an idea what this is all about.

Of course, now I use this interface for my web design.

Using Pascalscript for web pages is not new, but I have different requirements.
  1. A web designer must be able to modify the code.
  2. I want the bootstrap layout of the whole website to be visible in the editor so that you don't lose the WYSIWYG view.
  3. I want to have a template system, so i don't have to copy header, footer, navigation, etc. in every HTML file.
  4. I want to be able to write inline Delphi (PascalScript).
  5. I don't want to have to parse the Delphi part over and over again.
And already the solution was obvious:

I parse the HTML page, find includes, find the Delphi parts and find tokens that have to be replaced.

So when a new or changed web page is uploaded to the server, I compare the creation date of the file with the compiled version. If the date differs, the page is compiled and written to disk as a new file, with a replacement table and the appropriate compiled Delphi parts.

If the date ~ is the same, the file is loaded and a new response stream is created from the static parts, the replacements, and by executing the Delphi parts. Vola.

Even though in my tests the analysis and compilation of a "normal" index.html take less than one millisecond, the execution is of course only a stream copy and the runtime of the Delphi scripts.

Usually also faster than one millisecond. (Of course not, if you read 10 million data sets from a database) Here the execution duration is naturally still affected by the Delphi parts.

At the moment I have no time for a demonstration, but a Webinar is on my to-do list.

So stay tuned...