Monday, August 31, 2020

Accessing Config Data in Azure Functions with F#

I've been building an application using Azure Functions with F# as the API backend. The Azure Functions access data in Azure Storage to return to a single page web application. For development purposes, I've had the connection string hard-coded in the F# files that needed it. I'm at a point where I need to start deploying this app in a production manner, so I need to get the connection strings out of my code. The documentation for Azure Functions recommends using environment variables in production, and the local.settings.json file for development. Reading these values should have been trivial, but wasn't. This post documents how I was finally able to read data from environment variables.

Most of the documentation that I was able to find online pointed to using the Environment.GetEnvironmentVariable("myData") syntax. I was absolutely unable to get this call to work for me in my F# function. Fortunately I'm a member of the F# Slack community. I reached out for help on this issue, and Zaid Ajaj gave me a few things to try. This experimentation led to the solution below:

In the function above, I create a new ConfigurationBuilder instance and configure it for my app. To properly configure it, I needed to include another parameter for the function call, (context: ExecutionContext). This parameter gives me access to the runtime directory with the property context.FunctionAppDirectory. This allows me to then inject the local.settings.json file. (Note the boolean value true in the call to AddJsonFile. This true indicates that this file is optional, which is necessary in a production setting when this file will not exist.). Once I build the ConfigurationBuilder, I'm able to access local settings and environment variables using the array accessor syntax, config.["BoogyMan"].

I'm not sure if this is the "approved" Microsoft way or the best way to read environment values in an F# Azure Function, but it does work. If there is a better way to to this, I would love to see it.

Friday, August 28, 2020

Spot the Bug - Using Statement Part 1

Several months ago, I was reviewing some C# code of one of my teammates when I realized there was a subtle bug in the program. The bug was not easy to see right away. I realized that C# had certain constructs in place to make it difficult to create bugs like this. These constructs are great, but they mask certain design principles and make it possible to learn programming without learning the underlying design principles. I reviewed the bug in question with my team during a code review and made it kind of a game to find the bug and talk about the underlying design principles.

I did a talk titled "Spot the Bug" for the Code PaLOUsa conference last week. The talk was geared for two primary audiences. The first audience is developers that are earlier in their career. This audience benefited from this talk in seeing common coding mistakes and learning some common design principles. The other audience for this talk was developers later in their career or developers in positions to mentor others. This audience was shown an approach for highlighting some of these common mistakes and seeing ways to address them with their creators.

This is the first topic that I covered in the talk.

Below is a class to access a database. It has methods to open and close the database connection as well as a method to work with the data. Can you spot the bug?

Most C# developers are looking at the code above and thinking to themselves, "Why didn't he do this with a using statement?" These developers are absolutely right. The bug in the code above is that the DataGatherer class separates the responsibility of managing the database connection between two different methods, effectively forcing the developer that uses this class to be responsible for doing things correctly.

The using block in C# forces a developer to keep the responsibility of opening and closing database connections in the same code block, mostly ensuring that the right things are done in regards to the database connection. (It is still possible for a developer to forget to close the database connection within a using block, but the using block will force the connection closed and dispose of the connection. It just may take the garbage collector longer to get to it.)

The better code is below:

You'll notice in the better code that there is a lot less code! Keeping the opening and closing responsibilities together inside the using block, reduces the amount of code in the class and creates a much better program.

This subtle bug is easy to overlook if you learned to work with a database after the creation of the using construct. The using construct is a way to talk to new developers about class and method responsibilities and the need to keep similarly oriented responsibilities together.

Tuesday, August 11, 2020

Moving to Functional Thinking

I've been working on an educational-based site to help teachers evaluate students. I'm using F# for the backend API, and the regular use of a functional programming language has me thinking differently about how I code.

I recently needed to test a value to see if it is a GUID. If the value is a GUID, I want to use it. If the value isn't a valid GUID, I want to create a new GUID. In C#, this would be done like this:

if(Guid.TryParse(maybeGuidValue, out validGuidValue)
{
 myObject.ID = validGuidValue;
}
else
{
 myObject.ID = Guid.NewGuid();
}

This code is fairly straightforward, but a little problematic. First, the TryParse() method takes a string to test, maybeGuidValue, and an out parameter. If the method succeeds, meaning, the value is a valid GUID, the method returns true and the value validGuidValue is populated with the value in a GUID data type. If the value passed in is not a GUID, the method returns false and the out parameter should be ignored.

This code is tried and true in the C# world, but it isn't great. First, I'm not a fan of out parameters. This code construct is not pure or immutable since the method is returning one value as part of the method call and mutating another value by sending back an out parameter. Code like this requires special attention and is difficult to wrap in good unit tests.

In contrast, F# handles the same concept in a more intuitive manner. The code to TryParse a GUID looks like this:

let didParse, validGuidValue = Guid.TryParse maybeGuidValue
let ID = if didParse then validGuidValue else Guid.NewGuid()

This code calls the same TryParse method that is used in the C# code (F# shares the .NET libraries). Instead of having a single return value and an out parameter, this function returns a tuple with the boolean result of the parse operation along with the possibly populated GUID value. This construct is easier to see and much easier to unit test! The other obvious difference in the F# code is that it is only two lines! One line parses the value and the other line makes the assignment.

The F# code seems easier and much more intuitive, but it requires a change in thinking. The first change in thinking is embracing the power of tuples. Since tuples are relatively new in C#, it takes a mental effort to remember they are critical to F# and truly powerful. The second change in thinking is that if statements are expressions in F# as opposed to blocks in C#. An expression results in a value, allowing the assignment of ID, no matter how it is generated, to be made in a single line of code. The block construct in C# allows for branching, but the assignment code needs to be implemented in each logic branch. The block approach results in more code that can lead to ambiguity in how a value is assigned.

As I get more practice using F#, I am really enjoying the simplicity of code and the power the language has for me.