Code Review – What You Can Learn From a Single Line of Code

codereview

(image credit – a good article)

My first article of 2018 has been posted on Code Project!

It never fails to surprise me what can be gleaned from a single line of code. Gone are the days of BASIC where each line did one thing, a print statement, a gosub or goto, if-then-elseif-end if. Nowadays, a single line of code can be a chain of method calls, LINQ expressions, and operators like ?: (ternary if-else), ?. (null continuation), ?? (null coalescing) and even if-then-else implemented as extension methods.

What we’ll look at here is what can be gleaned about the implementation from just one line of code.

Read more here.

Advertisements

Higher Order Programming on the Web is Alive

tademo1

A hard to read screenshot of HOPE (aka Semantic Computing) is now working on the web under the code name “Temporal Agency” (I love that name!), using:

  • Docker to isolate user projects and sessions
  • C# (Yay!)
  • DotNet Core 2.0 (Yay!)

Features:

  • IDE-style programming.
  • Syntax highlighting editor (courtesy of Ace).
  • Layout of results declared in XML.

This is very snazzy, in my humble opinion.  I have a couple demos working:

  • Weather forecast, tying in to UndergroundWeather, with summary (as shown above) and full forecast layouts.
  • Address verification using the USPS API’s.

More to come!

HOPE Semantic Rendering of Microservice Data on the Browser

In a previous blog post, I described the high level architecture of microservices
running in a Docker container.  This blog post describes (again at a high level) the behind-the-scenes implementation of how a we render the output of a microservice back to the client’s browser. We’ll use the Weather Underground API for acquiring our current weather conditions.

First, let’s start with a semantic address:

public class ST_Address : ISemanticType
{
  public string Address1 { get; set; }
  public string Address2 { get; set; }
  public ST_City City { get; set; }
  public ST_State State { get; set; }
  public ST_Zip Zip { get; set; }

  public ST_Address()
  {
    City = new ST_City();
    State = new ST_State();
    Zip = new ST_Zip();
}

Note that there are other semantics involved here (ST_City, ST_State, and ST_Zip) which we won’t go into here.  We’ll populate the ST_Address with the two pieces that Weather Underground requires, city and state, and then publish this type to the docker container:

http://192.168.99.100:5001/publishSemanticType?
  semanticTypeName=ST_Address&instanceJson=
  {
    "City":
      {"City":"Hudson"},
    "State":
      {"State":"NY"}
  }

The microservice, in HOPE terminology, is a “receptor” that is interested in
the type ST_Address.  As implemented in C# (fragment):

public class WeatherForecast : IReceptor
{
  public void Process(ISemanticProcessor proc, IMembrane membrane, ST_Address address)
  {
    string json = Http.Get("http://api.wunderground.com/api/[yourapikey]/forecast/q/" + 
      address.State.State + "/" + 
      address.City.City + 
      ".json");

    var data = WeatherUnderground.FromJson(json);

    var statForecast = data.Forecast.Simpleforecast.Forecastday.Select(d =>
      new
        {
          Month = d.Date.Monthname,
          Day = d.Date.Day,
          Weekday = d.Date.Weekday,
          High = d.High.Fahrenheit,
          Low = d.Low.Fahrenheit,
          Conditions = d.Conditions,
          IconUrl = d.IconUrl,
          MaxWind = d.Maxwind.Mph,
        }).ToList();

    // ...
    // Building the day and night detail forecast is not shown.
    // ...

    Response result = new Response()
    {
      HopeResultWrapper = new WeatherResult()
      {
        StatForecast = statForecast,
        DayForecast = daySummaryForecast,
        NightForecast = nightSummaryForecast,
      }
    };

    // Call back to the host with the result.
    RestCall.Post("http://192.168.0.2/hope/result", result);
  }
}

The response is associated with an XML file that determines the rendering.
Here’s a fragment showing just the first to rows (the day and the icon) of
rendering definition:

hope-5

HOPE renders this into HTML and sends the HTML over an HTML5 websocket to the browser where the page defines this tag:

hope-6

and on receiving the message from host, executes this Javascript:

 ws.onmessage = function (wsevt)
 {
   var msg = wsevt.data;
   $("#appContent").empty();
   $("#appContent").append(msg);
 };

The result is rendered on the browser like this:

hope-2

By changing the rendering to a VerticalGrid we instead get:

hope-3

By changing the rendering XML definition again (not shown, it’s quite long) we can show the results from all three collections — stat, day, and night — to render a more detailed forecast.

hope-4

Of course, in real life, you’ll want to render the results of many microservices.  We’ll look at how that works soon!

HOPE for the Web

hope-1

The above diagram is a high level view of what I’ve implemented with .NET Core 2.0 and Docker.  The idea is to take the work I’ve done with semantic types and allow users to create public or private repos of semantic types and microservices that operate on those types whenever they are “published” in the user’s environment.

With .NET Core 2.0, all the core pieces that I need (reflection, NewtonsoftJson, HttpListener, to name a few) are all fully usable with C# 7.  And while I’ll eventually return to supporting Python, it is a pleasure work with this concept in a strongly-typed language, as that’s a really key component to semantic processing (yes, of course it can be done in a dynamically-typed language with Python as well, as I’ve demonstrated in previous posts and an article.)

And the beauty of doing this with .NET Core is that it can run in a Linux container, which is so much faster than using Docker for Windows!

I’ll be posting more about the implementation details and writing some articles on Code Project on the subject.

How to Conduct Code Reviews

codereviews

A good post to start with is here: https://css-tricks.com/code-review-etiquette/

I thought I’d share my own “wisdom” on the subject, regarding what I do:

1) I conduct the code review to cover the good, the bad, and the ugly.
2) I ask myself the question “if I had to maintain this code, what would I want to know?”
3) I ask others to speak up if they see anything in my algorithms or structure that I’m doing wrong.
4) I often present alternate implementations with pros and cons (for example, using metadata and reflection vs. imperative code, using LINQ vs. “old style” coding.)
5) And most importantly, I don’t lead code reviews of other people’s code, I ask them to lead a code review of their own code.

The result is a learning experience for everyone (including me) and particularly the discovery of algorithm deficiencies or where comments would really be helpful.

Class-less Coding – Minimalist C# and Why F# and Function Programming Has Some Advantages

Summary

Can we use just the native .NET classes for developing code, rather than immediately writing an application specific class that often is little more than a container?  Can we do this using aliases, a fluent style, and extension methods?  If we’re going to just use .NET classes, we’re going to end up using generic dictionaries, tuples, and lists, which gets unwieldy very quickly.  We can alias these types with using statements, but this means copying these using statements into every .cs file where we want to use the alias.  A fluent (“dot-style”) notation reduces code lines by representing code in a “workflow-style” notation.  In C#, if we don’t write classes with member methods, then we have to implement behaviors as extensions methods.  Using aliases improves semantic readability at one level at the cost of confusing generic type nesting in the alias definition.  Extension methods can be taken too far, resulting in two  rules: write lower level functions for semantic expressiveness, and avoid nested parens that require the programmer to maintain a mental “stack” of the workflow.  In contrast to C#’s using aliases, F# type definitions are not aliases, they are concrete types.  New type definitions can be created from existing types.  Type definitions can also be used to specify a function’s parameters and return value.  The forward pipe operator |> is similar to the fluent “dot” notation in C#, but the value on the left of the |> operator “populates” the last parameter in the function’s parameter list.  When functions are written that return something, the last function must be piped to the ignore function, which is slightly awkward.  F# type dependencies are based on the order of the files in the project, so a type must be defined before you use it.  In C#, creating more complex aliases get messy real fast — this is an experiment, not a recommendation for coding practices!  In F#, we don’t need an Action or Func class for passing functions because F# inherently supports type definitions that declare a function’s parameters and return value — in other words, everything in functional programming is actually a function.  Tuples are a class in C# but native to functional programming, though C# 6.0 makes using tuples very similar to F#.  While C# allows function parameters to be null, in F#, you have to pass in an actual function, even if the function does nothing.  F# uses a nominal (“by name”) as opposed to structural inference engine, Giving types semantically meaningful names is very important so that the type inference engine can infer the correct type.  In C#, changing the members of class doesn’t affect the class type.  Not so with F# (at least with vanilla records) — changing the structure of a record changes the record’s type.  Changing the members of a C# class can, among other things, lead to incorrect initialization and usage.   Inheritance, particularly in conjunction with mutable fields, can result in behaviors with implicit understanding like “this will never happen” to suddenly break.  Extension methods and overloading creates semantic ambiguity.  Overloading is actually not supported in F# – functions must have semantically different names, not just different types or parameters lists.  Object oriented programming and functional programming both have their pros and cons, with some hopefully concrete discussion presented here.

Full article on Code Project here.

Luna – Visual and textual functional programming language with a focus on productivity, collaboration and development ergonomics.

Take a look at what these folks are doing.   Very cool stuff!!!

Software design always starts with a whiteboard. We sketch all necessary components and connect them to visualize dependencies. Such component diagram is an exceptionally efficient foundation for collaboration, while providing clear view over the system architecture and effectively bridging the gap between technical and non-technical team members.

However:

Unfortunately, it is impossible to execute the diagram itself, therefore the logic has to be implemented as a code.

Now that’s the part I disagree with, in the sense that, once the code-behind is written, and written in a modular and semantic way, you should be able to visually build the workflows, reduce/map/filter operations from “primitive” blocks, which then become bigger blocks from which you build from, etc.