Sunday, December 23, 2018

Could you do me a SOLID mate?

Wow, it’s been a while! Nearly nine years since my last blog post. A lot has changed since then – some for the better, some for the worse. I’d like to think it’s been the former for me, and what it means to be a professional software engineer nowadays. And as I embark on the next chapter in my career, I thought it apt to write a little about something that has had such a profound impact on me and the way I now look at the structure of computer source code.

So - clean code. Why does it matter, and why am I blogging about it? Well, as Martin Fowler once said, “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” More on Mr. Fowler in a future blog…

Many programmers are under the impression that if it compiles, it’s good to go, and on to the next feature. Who cares if code is not separated into logical units, or that the functions are small, or the proper boundaries have been implemented, or that the names are clear and reveal intent? As a result, the software inevitably loses its “softness” – it’s ability to change. It becomes rigid, and it takes longer and longer to implement new features due to the tangled mess.

I too was guilty of this many times. It’s not that I didn’t care about the code, I simply just didn’t know better, until, that is, I was introduced to SOLID. I was just as keen as the next developer to finish the feature and move onto the next thing. For example, a number of years ago I had a very popular iOS app on the app store that was a pretty good MVP (minimum viable product) that had enjoyed around seven thousand downloads! Pretty impressive, if I say so myself! Then came the time to add the next feature. To cut a long story short, this new feature (although nothing major) ultimately required way too much effort because the structure of the existing code did not allow for the new code to be written, and the app never got its new feature implemented, and ultimately disappeared off the app store as it had lost its market value without that new feature.

So, what is SOLID? According to the Wikipedia definition, “in object-oriented computer programming, SOLID is a mnemonic acronym for five design principles intended to make software designs more understandable, flexible and maintainable. The principles are a subset of many principles promoted by Robert C. Martin. Though they apply to any object-oriented design, the SOLID principles can also form a core philosophy for methodologies such as agile development or adaptive software development.”

I am thankful that I got the opportunity to learn about the SOLID principles, having experienced the benefits first-hand working on an iOS application for one of the leading banks in South Africa. Our codebase has become clean, and changes are implemented with relatively little effort due to the “soft” nature of the code.

But it took time. There was no smooth road to grasping all the principles. All too often others would look at some code and go “this is a clear SRP violation”, or “this violates ISP”, or “this code violates the Open / Closed principle”, and so on and so forth. But in the bigger context of the application it was sometimes hard to spot these violations, let alone find solutions to implement the code to remedy the violations. It was a bumpy ride. At the time it would have been useful to have a few concrete, bite-sized SOLID examples that I could refer to when I got stuck or was in doubt.

And so the idea for this article was born.  

I have put together a very basic collection of Swift Playgrounds in a workspace (SOLID-Swift-Demo.xcworkspace) that can be found on GitHub. The playgrounds have been written in Swift 4.2.1 and XCode 10. The playgrounds are sorted according to the SOLID acronym in the workspace (01 Single Responsibility Principle, 02 Open/Closed Principle, etc.). Each principle has an associated playground page giving a brief explanation of the principle, how to recognize it in code, and the benefits of implementing it. In most instances there are two playgrounds per principle: an example of a violation of the principle, and in some cases an example of how one could fix the violation.

Maybe you’ve seen this type of thing on the web before. There are certainly no shortage of blogs and information on the web talking about SOLID, but the one I have posted on GitHub is the kind of thing I wish I’d had when I was first introduced to the principles.

For more on clean code, check out Robert C. Martin (affectionately known as Uncle Bob)’s blog.

Wednesday, March 31, 2010

Introducing F#

Introduction

The purpose of this article is to introduce you to the F# language - what it is, it's origins, and how it fits into Visual Studio 2010 RC. In the process, I hope to highlight the following:
  • What exactly is F#?
  • What is functional programming?
  • What are the benefits of functional programming?
  • How to install F#
  • What is F# Interactive?
  • The F# Powerpack
  • and where you can download the required F# tools and libraries from
In the Downloads section of this article you will find links to a presentation I gave on the F# language, as well as a Visual Studio 2010 solution containing sample F# projects and scripts you can run to further clarify what the language is and what it can do.

What is F#?

F# is a multi-paradigm programming language, targeting the .NET Framework, that encompasses functional programming as well as imperative object-oriented programming disciplines. It is a variant of ML and is largely compatible with the OCaml implementation. F# was initially developed by Don Syme at Microsoft Research but is now being developed at Microsoft Developer Division and will be distributed as a fully supported language in the .NET framework and Visual Studio as part of Visual Studio 2010.

F# is a strongly typed language that uses type inference. As a result, data types need not be explicitly declared by the programmer; they will be deduced by the compiler during compilation. However, F# also allows explicit data type declaration. Being a .NET language, F# supports .NET types and objects. But itextends the type system and categorizes types as immutable types or mutable types. .NET objects classify as mutable types (which can be edited in-place), and are used to provide an object-oriented programming model. Immutable types (editing such a type creates a new instance without overwriting the older one) are primarily used for functional programming.

Before we can fully understand what F# is and how it fits into the bigger programming picture, we need to know a little more about functional programming.

What is Functional Programming?

Functional programming means that programs are executed by evaluating expressions. This contrasts with imperative programming where programs are composed of statements which change global state when executed. Functional programming, on the other hand, avoids using state and mutable data.

Functional programming requires that functions are first-class, which means that they are treated like any other values and can be passed as arguments to other functions or be returned as a result of a function. Being first-class also means that it is possible to define and manipulate functions nested in code blocks. Special attention needs to be given to nested functions, called closures, that reference local variables from their scope. If such a function escapes their block after being returned from it, the local variables must be retained in memory, as they might be needed later when the function is called. Usually it is not possible to determine statically the moment of release, which means that an automatic memory management technique has to be used.

Functional programming is based on the simplest of models, namely that of finding the value of an expression. This we meet in our first years at school, when we learn to work out expressions like 8+(3-2) by evaluating the two halves, 8 and (3-2), and adding the results together. Functional programming consists of our defining for ourselves functions like + which we can then use to form expressions.

We define these functions by means of equations, like

addD a b = 2*(a+b)

which we use to calculate the value of an expression like addD 2 (addD 3 4). We evaluate this using (1) to replace occurrences of addD with their values, so that we can write down a calculation of its value
addD 2 (addD 3 4)
=
2*(2 + (addD 3 4))
= 2*(2 + 2*(3 + 4))
= 32

As well as using (1) to calculate, we can read it as a logical description of how the function addD
behaves on any values a and b; on the basis of this we can reason about how it behaves. For instance, for any values a and b,

addD a b = 2*(a+b) =
2*(b+a) = addD b a
This equation holds for all possible input values, in contrast to the information we gain from testing a function at a selection of inputs.

On top of this simple model we can build a variety of facilities, which give the functional approach its distinctive flavour. These include higher-order functions, whose arguments and results are themselves functions; polymorphism, which allows a single definition to apply simultaneously to a collection of types; and infinite data structures which are used to model a variety of data objects.

The Miranda language also has support for larger-scale programming, including user-defined algebraic types, such as lists, trees and so on; abstract data types and modules. These contribute to separating complex tasks into smaller sub-tasks, making the components of systems independent of each other, as well as supporting software re-use.

Benefits of functional programming

Functional programming is known to provide better support for structured programming than imperative programming. To make a program structured it is necessary to develop abstractions and split it into components which interface each other with those abstractions. Functional languages aid this by making it easy to create clean and simple abstractions. It is easy, for instance, to abstract out a recurring piece of code by creating a higher-order function which will make the resulting code more declarative and comprehensible.

Functional programs are often shorter and easier to understand than their imperative
counterparts. Since various studies have shown that the average programmer's productivity in terms of lines of code is more or less the same for any programming language, this translates also to higher productivity.

F# Installation

F# is included as part of Visual Studio 2010. It comes with a Microsoft Visual Studio language service that integrates it with the IDE. With the language service installed, Visual Studio can be used to create F# projects and the Visual Studio debugger used to debug F# code. In addition, it comes with a Visual Studio-hosted interactive console that executes F# code as it is being written.

F# can also be downloaded as a seperate installation package for Visual Studio 2010 and 2010, or as a standalone compiler available in the F# CTP release. In addition to this, F# compiler binaries are also available for Mono, Mac, and Linux.

Furthermore, a collection of libraries and tools for use with the F# language is available in the form of the F# Powerpack from CodePlex.

What is F# Interactive

F# Interactive is a command line tool you can use to execute fragments of F# code interactively, making it a convenient way to explore the language.

You can start F# Interactive in Visual Studio by selecting Tools ➤ Add-in Manager and then selecting F# Interactive for Visual Studio in the Add-in Manager dialog box. A tool window will then appear, and you can send text to F# Interactive by selecting the text and pressing Alt+Return.

It is installed by default into %PROGRAMFILES%\Microsoft F#\v4.0 if Visual Studio 2010 is installed.

F# Powerpack

The F# PowerPack is a collection of libraries and tools for use with the F# programming language provided by the F# team at Microsoft.

This is functionality which is not part of the core F# release, but enables some development scenarios with F#. The PowerPack include features such as a basic Matrix library and supporting math types, FsLex and FsYacc tools for lexing and parsing, support for using F# with LINQ-based libraries, and a tool for generating HTML documentation from F# libraries. This functionality, which has previously been available in the F# CTP releases, is now available on CodePlex.

The PowerPack consists of several assemblies and tools which provide functionality in wide range of areas related to F#:

FsLex and FsYacc

PowerPack includes F# versions of these popular lexer and parser generation tools, along with MSBuild tasks to incorporate them in the build process.

F# Documentation generator

FsHtmlDoc.exe, included in PowerPack, can be used to generate HTML documentation from the XMLDoc comments in F# source files.

F# LINQ and Quotations to Expression Tree Bridge

FSharp.PowerPack.Linq.dll connects F# with features introduced in .NET 3.5. It provides converters from quotations to .NET expression trees, and introduces a query operator that allows F# programs to execute queries via LINQ mechanisms.

F# CodeDOM Implementation

FSharp.Compiler.CodeDom.dll contains implementations of System.CodeDom.Compiler.CodeDomProvider for F#. This allows F# to be used with CodeDom consumers, and most importantly to author ASP.NET pages code-behind classes in F#. Not all ASP.NET features work with this CodeDom, and you don't get strongly typed access to page elements, Some sample ASP.NET applications are in the test suite in the source tree.

F# Parallel LINQ Integration

FSharp.PowerPack.Parallel.dll provides F#-style API for parallel operations on sequences that are part in .NET 4.0 as System.Linq.ParallelEnumerable class. The API is akin to F# operations on sequences.

F# Metadata Reader

FSharp.PowerPack.Metadata.dll allows to introspect F#-authored assemblies and analyze F#-specific metadata.

F# Compatibility Helpers

FSharp.PowerPack.Compatibility.dll provides various helper functions for compatibility with OCaml and previous releases of F#.

Downloads

Also be sure to visit the Microsoft F# Research site.

Using the Code

Extract the source archive to your local hard drive.

The enclosed solution was created using Visual Studio 2010 RC, and contains six F# projects, and two F# script files (with an .fsx extension). To run a project, select a project of choice from the solution, right-click the project, select Set as StartUp Project, and hit F5!

To run the F# scripts, open the script file in Visual Studio 2010 RC, select all the code in the source file, and then either send the code to F# Interactive inside Visual Studio, or copy and paste the code into the F# Interactive command line tool.

Tuesday, October 20, 2009

Passing dates in XAML

Recently I had the need for an encapsulated, reusable 'About Box' control that I could use throughout a number of Silverlight applications. I then wrote a user control that would serve this purpose. The AboutBox displays application releases that are grouped by the application version, and a list of changes/updates included in that version. An example of this can be seen below:


Although the use and implementation of the AboutBox user control is beyond the scope of this article, one of the features of the AboutBox was to enable the developer to specify a date for a product release item. I made provision for this by creating a DateTime property called Date in the VersionInformation class. However, I encountered a problem when trying to specify a value for this property in the XAML of the page consuming the AboutBox user control

I realized that XAML natively does not know how to convert a string to a DateTime value, and setting the Date property as Date="12 January 2009" would result in an AG_E_UNKNOWN_ERROR XAML parser error when running the application.

Thankfully, there is a way to resolve this. The answer lies in TypeConverter, and the full article can be found at CodeProject

Monday, October 19, 2009

Microsoft announce Visual Studio 2010 dates

Microsoft have announced that Visual Studio 2010 will officially launch on the 22nd of March 2010, and is promised to be "the most significant release" Microsoft's had of the tools suite and framework "in a number of years."

New features include Windows 7 and SharePoint 2010 tools, drag-and-drop bindings with Silverlight and Windows Presentation Foundation, the inclusion of the Dynamic Language Runtime (DLR) for programming with scripting languages, and support for parallel programming.

Read the full article here.

Tuesday, October 13, 2009

Apple versus Microsoft: The top 20 stolen ideas

Both Windows 7 and Mac OS X 10.6 Snow Leopard contain features that originated in the other Operating System. Some features were stolen so long ago that they've become part of the computing landscape, and it's difficult to remember who invented what.

Full article available at InfoWorld.

Monday, October 12, 2009

Silverlight ported to Linux

Intel and Microsoft have announced a new port of Silverlight to Linux, specifically for the Intel-sponsored Moblin operating system running on Atom-powered devices such as netbooks. The port enables Intel to include Silverlight as a supported runtime in the Atom Developer Program, which will feed an iPhone-like App Store.

Microsoft has already provided Intel with Silverlight source code and test suites. Intel will build an optimized Moblin version of Silverlight, which Microsoft will supply to OEMs.

Read the full article here.

.NET development on the iPhone

A kit for developers to build Apple iPhone and iPod Touch business applications using Microsoft's .Net Framework instead of the Apple-designated C or Objective-C languages is available from Novell.

Read the full article here.

The kit is available from the MonoTouch site.

Could you do me a SOLID mate?

Wow, it’s been a while! Nearly nine years since my last blog post . A lot has changed since then – some for the better, some for the worse....