Just for fun lets look at a more practical example:-
The above is typical code for opening a "Open File" dialog. Now there is nothing wrong with that code. It's a perfectly acceptable way of writing code. This is the way us "old-schoolers" would write it. That doesn't mean it couldn't be better. You could make that far more readable while not giving up anything:-Code:Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim dlg As New OpenFileDialog dlg.Filter = "Text files|*.txt|All files|*.*" dlg.Multiselect = False dlg.CheckFileExists = False If dlg.ShowDialog = DialogResult.OK Then Try TextBox1.Text = IO.File.ReadAllText(dlg.FileName) Catch ex As Exception MessageBox.Show("Error opening file : " & ex.Message) End Try End If End Sub
The above is the same code written in the fluent style. It does the same thing while being more compact and readable. I find languages that allow you to write code like this very attractive. That doesn't mean I won't use a language without it but it certainly helps in making the language more attractive.Code:Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click FluentOpenDialog.Create(). AddFilter("Text files", "*.txt"). AddAllFilesFilter(). FileAction(Sub(fn) TextBox1.Text = IO.File.ReadAllText(fn)). ErrorAction(Sub(ex) MessageBox.Show("Error opening file : " & ex.Message)). Open() End Sub
By the way, for the curious mind, this is what the FluentOpenDialog class looks like:-
Code:Public Class FluentOpenDialog Public Shared Function Create() As FluentOpenDialog Return New FluentOpenDialog() End Function Private _filters As New List(Of (String, String)) Private _fileAction As Action(Of String) Private _errorAction As Action(Of Exception) 'Prevent this class from being created 'by anything other than the Create method Private Sub New() End Sub Public Function AddFilter(ByVal fltName As String, ByVal filter As String) As FluentOpenDialog _filters.Add((fltName, filter)) Return Me End Function Public Function AddAllFilesFilter() As FluentOpenDialog Me.AddFilter("All files", "*.*") Return Me End Function Public Function FileAction(ByVal act As Action(Of String)) As FluentOpenDialog _fileAction = act Return Me End Function Public Function ErrorAction(ByVal act As Action(Of Exception)) As FluentOpenDialog _errorAction = act Return Me End Function Public Sub Open() Dim dlg As New OpenFileDialog dlg.Multiselect = False dlg.CheckFileExists = False dlg.Filter = String.Join("|", From v In _filters Select $"{v.Item1}|{v.Item2}") If dlg.ShowDialog = DialogResult.OK Then Try _fileAction.Invoke(dlg.FileName) Catch ex As Exception _errorAction.Invoke(ex) End Try End If End Sub End Class




Reply With Quote
