The point of regular expression character classes is to simplify your expressions, but they can introduce subtle bugs or efficiency issues.

Let's check out this StackOverflow answer to question \d less efficient than [0-9]

\d checks all Unicode digits, while [0-9] is limited to these 10 characters. For example, Persian digits, ۱۲۳۴۵۶۷۸۹, are an example of Unicode digits which are matched with \d, but not [0-9].

This makes sense, only it has never occurred to me until this very moment. I would never use a [0-9] notation and I would replace it with a \d if found in code.

What does that mean?

One simple consequence of such a class would be performance: searching for a large list of characters is less efficient. Another would be introducing the possibility for bugs or even malicious attacks. Let's see the code for a calculator that adds two numbers. It's a silly piece of code, but imagine that a more complex one would take the user content and save it into a database, try to process it or display it.

static void Main(string[] args)
{
    Console.InputEncoding = Encoding.Unicode;
    var firstNumber = GetNumberString();
    var secondNumber = GetNumberString();
    Console.WriteLine("Sum = "+(int.Parse(firstNumber) + int.Parse(secondNumber)));
}

private static string GetNumberString()
{
    string result=null;
    var isNumber = false;
    while (!isNumber)
    {
        Console.Write("Enter a number: ");
        result = Console.ReadLine();
        isNumber = Regex.IsMatch(result, @"^\d+$");
        if (!isNumber)
        {
            Console.WriteLine($"{result} is not a number! Try again.");
        }
    }
    return result;
}

This will try to get numbers as a string and test it using the regular expression ^\d+$, which means the string has to consist of one or more digits. Note that I had to set the console input encoding to Unicode in order to be able to paste Persian numbers. This code works fine until I use Arabic or Persian digits, where it breaks in the int.Parse method. Using ^[0-9]$ as the regular expression pattern would solve this issue.

Same issue will occur with \w (warning: \w is letters AND digits) and [a-zA-Z] (or just [a-z] and using RegexOptions.IgnoreCase).

If one uses code to determine the number of matches for each regular expression pattern

var regexPattern = @"\d";
var nr = 0;
for (int i = 0; i < ushort.MaxValue; i++)
{
    string str = Convert.ToChar(i).ToString();
    if (Regex.IsMatch(str, regexPattern))
        nr++;
}
Console.WriteLine(nr);

we get this:

  • for \d : 370
    • ALL digits
  • for \w : 50320
    • ALL word characters (including digits) 
  • for [^\W\d] : 49950
    • ALL word characters, but not the digits 
  • for \p{L} : 48909
    • ALL letters
  • for [A-Za-z] : 52
    • letters from a to z
  • for [0-9] : 10
    • digits from 0 to 9

I hope this helps.

Let's start with a simple requirement and the obvious first draft of the code. The requirement is "build a method that receives a string and writes to the console a URL using that string as a parameter".

The obvious first attempt and working in every version of C# would be:

private static void ShowUrl(string something)
{
    var url = "https://siderite.dev/blog/search/formattablestring?param1="+something;
    Console.WriteLine(url);
}

But then you get some problems. You want to use a parameter that has strange characters in it, like an email, another URL, arithmetic symbols, etc. So you realize that you need to use an URL encode class. Next version is:

private static void ShowUrl(string something)
{
    var url = "https://siderite.dev/blog/search/formattablestring?param1="+Uri.EscapeDataString(something);
    Console.WriteLine(url);
}

Now that works for a second. One might argue about the difference between System.Web.HttpUtility.UrlEncode, System.Net.WebUtility.UrlEncode and System.Net.Uri.EscapeDataString. Yet, his is not the post to do that. Follow the above links for more information.

Then someone decides to use a null for the parameter and you get a ArgumentNullException and you rage in frustration "This is complicated and ugly! The first version looked much better and handled nulls, too. And now I have to add this long Uri.EscapeDataString to every URL parameter in every URL building code I write and also check for null!".

But... what if you could write the method just like the first version and get rid of every problem?

First of all, let's get rid of that plus sign and use interpolated strings. They've been around for awhile:

private static void ShowUrl(string something)
{
    var url = $"https://siderite.dev/blog/search/formattablestring?param1={something}";
    Console.WriteLine(url);
}

Now, this has the same problem of the first version: no URL encoding. And you don't want to add an escape function to every parameter (imagine there would be 10 parameters in this URL). How about we use the fact that the URL is an interpolated string?

Check out this code:

private static void ShowUrl(string something)
{
    var url = UrlHelper.Url($"https://siderite.dev/blog/search/formattablestring?param1={something}");
    Console.WriteLine(url);
}

It uses an UrlHelper class to fix the problems with the URL in the string we generate. Or is it a string? I was writing a long time ago a post about FormattableString and how I didn't see a real use scenario for it. Well, this is it! Let's see what UrlHelper looks like:

public static class UrlHelper
{
    public static string Url(FormattableString url)
    {
        return string.Format(
            url.Format, 
            url.GetArguments()
                .Select(a => Uri.EscapeDataString(a?.ToString()??""))
                .ToArray());
    }
}

The Url method receives not a string, but a FormattableString. When an interpolated string is used as a FormattableString, it gives the developer access to a Format string and a list of arguments in GetArguments. In order to convert it to a string, one must only do String.Format(s.Format,url.GetArguments()).  In our case, the Format property will have the value "https://siderite.dev/blog/search/formattablestring?param1={0}" and the arguments list will contain one value: the value of the something parameter.

Therefore, the Url method will be able to format the string, but first URL encode every single parameter in it.

I admit, this might not be the most readable code in the world, which is my pet peeve with FormattableString. Reading the ShowUrl method you have no clue that UrlHelper.Url receives a FormattableString as parameter. One might even look at that string and say "Hey, wait a minute! That's a bug waiting to happen!" and then proceed to fix it. Perhaps the name of the method could be made more intuitive like EncodeUrlParameters.

But wait! We can do better. I don't know how it might help in the future, but perhaps someone might want to process the parameters of the URL further. By returning a string we eliminate some of the information of the incoming parameter and we don't want to do that.

Also, careful people will notice that using String.Format introduces a subtle bug (or feature): we format the string without specifying a culture. This might be fine, using the current one by default, but it might also cause some issues. The FormattableString class does provide the static CurrentCulture and Invariant methods and, of course, the ToString method would work just fine as well, but then we lose the ability to process the parameters.

So here is the final version of the UrlHelper class:

public static class UrlHelper
{
    public static FormattableString EncodeUrlParameters(FormattableString url)
    {
        return FormattableStringFactory.Create(
            url.Format,
            url.GetArguments()
                .Select(a => Uri.EscapeDataString(a?.ToString() ?? ""))
                .ToArray());
    }
}

By using FormattableStringFactory from System.Runtime.CompilerServices we get a FormattableString as an argument and we return one, with parameters URL encoded. Now, if the result of the method is used as a string, it will be automatically handled by ToString and if it will be used as a FormattableString it will contain all the information provided by the original parameters.

Hope that helps!

Bonus time! There's more!

What if you could make this behavior built in by introducing a new type? Methods from, let's say, a REST client class could use FormattableStrings as URL parameters. But what if we could specify the type of the parameters and get the implicit (hint, hint!) result already URL encoded?

public class UrlString
{
    private FormattableString _formattableString;

    public UrlString(FormattableString formattableString)
    {
        _formattableString = formattableString;
    }

    public static implicit operator FormattableString(UrlString urlString)
    {
        if (urlString == null) return null;
        return UrlHelper.EncodeUrlParameters(urlString.ToFormattableString());
    }

    public static implicit operator string(UrlString urlString)
    {
        if (urlString == null) return null;
        return ((FormattableString)urlString).ToString();
    }

    public static implicit operator UrlString(FormattableString formattableString)
    {
        return new UrlString(formattableString);
    }

    private FormattableString ToFormattableString()
    {
        return _formattableString;
    }
}

This UrlString class will implicitly be converted into a FormattableString or a string and a FormattableString will be converted into a UrlString. So now your code might look like this:

// used like this
RestClient.Get($"https://test.com?x={something}");

// this method does not URL encode anything
public RestResponse Get(string url) {
  ...
}

// this method does URL encode everything, just by changing the type
public RestResponse Get(UrlString url) {
  ...
}

Intro

Dependency injection is baked in the ASP.Net Core projects (yes, I still call it Core), but it's missing from console app templates. And while it is easy to add, it's not that clear cut on how to do it. I present here three ways to do it:

  1. The fast one: use the Worker Service template and tweak it to act like a console application
  2. The simple one: use the Console Application template and add dependency injection to it
  3. The hybrid: use the Console Application template and use the same system as in the Worker Service template

Tweak the Worker Service template

It makes sense that if you want a console application you would select the Console Application template when creating a new project, but as mentioned above, it's just the default template, as old as console apps are. Yet there is another default template, called Worker Service, which almost does the same thing, only it has all the dependency injection goodness baked in, just like an ASP.Net Core Web App template.

So start your Visual Studio, add a new project and choose Worker Service:

It will create a project containing a Program.cs, a Worker.cs and an appsettings.json file. Program.cs holds the setup and Worker.cs holds the code to be executed.

Worker.cs has an ExecuteAsync method that logs some stuff every second, but even if we remove the while loop and add our own code, the application doesn't stop. This might be a good thing, as sometimes we just want stuff to work until we press Ctrl-C, but it's not a console app per se.

In order to transform it into something that works just like a console application you need to follow these steps:

  1. inject an IHost instance into your worker
  2. specifically instruct the host to stop whenever your code has finished

So, you go from:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;

    public Worker(ILogger<Worker> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(1000, stoppingToken);
        }
    }
}

to:

public class Worker : BackgroundService
{
    private readonly ILogger<Worker> _logger;
    private readonly IHost _host;

    public Worker(ILogger<Worker> logger, IHost host)
    {
        _logger = logger;
        _host = host;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        Console.WriteLine("Hello world!");
        _host.StopAsync();
    }
}

Note that I did not "await" the StopAsync method because I don't actually need to. You are telling the host to stop and it will do it whenever it will see fit.

If we look into the Program.cs code we will see this:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((hostContext, services) =>
            {
                services.AddHostedService<Worker>();
            });
}

I don't know why they bothered with creating a new method and then writing it as an expression body, but that's the template. You see that there is a lambda adding dependencies (by default just the Worker class), but everything starts with Host.CreateDefaultBuilder. In .NET source code, this leads to HostingHostBuilderExtensions.ConfigureDefaults, which adds a lot of stuff:

  • environment variables to config
  • command line arguments to config (via CommandLineConfigurationSource)
  • support for appsettings.json configuration
  • logging based on operating system

That is why, if you want these things by default, your best bet is to tweak the Worker Service template

Add Dependency Injection to an existing console application

Some people want to have total control over what their code is doing. Or maybe you already have a console application doing stuff and you just want to add Dependency Injection. In that case, these are the steps you want to follow:

  1. create a ServiceCollection instance (needs a dependency to Microsoft.Extensions.DependencyInjection)
  2. register all dependencies you want to use to it
  3. create a starting class that will execute stuff (just like Worker above)
  4. register starting class in the service collection
  5. build a service provider from the collection
  6. get an instance of the starting class and execute its one method

Here is an example:

class Program
{
    static void Main(string[] args)
    {
        var services = new ServiceCollection();
        ConfigureServices(services);
        services
            .AddSingleton<Executor,Executor>()
            .BuildServiceProvider()
            .GetService<Executor>()
            .Execute();
    }

    private static void ConfigureServices(IServiceCollection services)
    {
        services
            .AddSingleton<ITest, Test>();
    }
}

public class Executor
{
    private readonly ITest _test;

    public Executor(ITest test)
    {
        _test = test;
    }

    public void Execute()
    {
        _test.DoSomething();
    }
}

The only reason we register the Executor class is in order to get an instance of it later, complete with constructor injection support. You can even make Execute an async method, so you can get full async/await support. Of course, for this example appsettings.json configuration or logging won't work until you add them.

Mix them up

Of course, one could try to get the best of both worlds. This would work kind of like this:

  1. use Host.CreateDefaultBuilder() anyway (needs a dependency to Microsoft.Extensions.Hosting), but in a normal console app
  2. use the resulting service provider to instantiate a starting class
  3. start it

Here is an example:

class Program
{
    static void Main(string[] args)
    {
        Host.CreateDefaultBuilder()
            .ConfigureServices(ConfigureServices)
            .ConfigureServices(services => services.AddSingleton<Executor>())
            .Build()
            .Services
            .GetService<Executor>()
            .Execute();
    }

    private static void ConfigureServices(HostBuilderContext hostContext, IServiceCollection services)
    {
        services.AddSingleton<ITest,Test>();
    }
}

The Executor class would be just like in the section above, but now you get all the default logging and configuration options from the Worker Service section.

Conclusion

What the quickest and best solution is depends on your situation. One could just as well start with a Worker Service template, then tweak it to never Run the builder and instead configure it as above. One can create a Startup class, complete with Configure and ConfigureServices as in an ASP.Net Core Web App template or even start with such a template, then tweak it to work as a console app/web hybrid. In .NET Core everything is a console app anyway, it's just depends on which packages you load and how you configure them.

  Mirage is inspired by the "Years of Lead" in Morocco's 1960s history and its underlying message about the terrors of colonialism is quite important. At first I thought it was inspired by the plight of Arabs in Palestine, so it's also very timely. That is why it pains me to say that I couldn't go more than several chapters in. The writing is amateurish, the lead teen character inconsistent and annoying and this is clearly a YA book written by a woman for other women.

  That may sound misogynistic, but everyone who has ever hunted for a good book to read knows what I mean: you get to something that has rave recommendations, raised to the level of masterpiece by a few articles, but then when you start reading and you look closer at those reviews you see that they are mostly from women writing those five star animated GIF capital letter emoji filled things. And all the men give two stars and wonder how did they get to read the book in the first place, just like you.

  I don't want to be unfair to Somaiya Daud - this is her debut novel and I am sure her writing will get better with time - but for me reading through the rest of the book and knowing that it's yet another trilogy in the making, so having to wait even more to even get to the end of the story, was too much. It also addresses issues of personal helplessness, which is probably my Achilles' heel. If I ever want to get to those good books that I want to find, I have to fail fast and cut my losses early.

  Bottom line: I couldn't even begin to start reading the book. A combination of subject, debut writing style and aggressive and misleading advertising made me abandon it immediately.

  Half a year ago I was writing a piece about how the system is stacked against you, no matter where on the ladder you are. Nobody cares about you! was part depression and part experience, because I have worked in corporations most of my career and that's exactly what happens in real life. This post will not be in the "What's Siderite going to say to make us hate life and kill ourselves" category, though. Quite the opposite. I am going to tell you what the logical consequence of that dreary article is - and it's good!

  Think about it! Are there nice things in the world? And I am not talking about love, sunrises and cute kittens, but about human acts and artefacts. The answer is yes, or you are a lot more depressed than I've ever been. So, if the world is configured to not care about you or about anyone, if the logical best strategy is to do just as much as it is absolutely required and fake the rest, why is there human beauty out there?

  The answer is: every good and beautiful man made thing that you see in the world is by someone doing more than they were asked to do. It's a simple sentence, but a powerful reality. Every day people, like and unlike you and me, are defying the boring order of the universe to create beauty and to better the world. Let's say you play a game made by a big game company and you are enjoying it. - maybe not the entire game either, just some portion of it - I can assure you that is not the consequence of the money poured in it, but of some person who did a little more than the bare minimum. If you use a program, a boring one, like Office something, and you find a feature that blows your mind, be convinced that no one asked for it specifically and someone actually made an extra effort to put it there. If you like the way the handle of the knife feels in your hand when you're slicing bread, same.

  And yes, there is the theory that every act of altruism comes from selfishness, and you can abstract everything to mean anything when it involves humans, but I am not talking about people who want to make the world better or selfless angels who want to make others happy. I am talking here of the simple fact of doing more than necessary just because you want to. And I am not talking about some kind of artsy philosophical method of improving everything and sparking joy, but about at least one, just one act that is invested with a bit of a human person. They do what they were asked to, paid to, coerced to, bullied to, begged to, then they make another step. Maybe it's inertia, maybe it's not knowing when to stop or not knowing what's good for them, but they did it and in the act imbued something with a piece of their soul.

  OK, I know that this is more of a "diamond in the mud" category rather than a positive message, but have you ever considered that even the smallest joys in life may come from the acts of rebellion of others? Maybe it's not a diamond, maybe it's a shitty opal, but knowing that you found it in the mud gives it immense relative value. Finding the ugliness, the stupid, the petty, the outrageous is easy. Seeing something beautiful and knowing it grew out of this is rare and valuable.

  We have been told again and again that our code should be split into smaller code blocks that are easy to understand and read. The usual example is a linear large method that can easily be split into smaller methods that just execute one after the other. But in real life just selecting a logical bit of our method and applying an Extract Method refactoring doesn't often work because code rarely has a linear flow.

  Let's take a classic example of "exiting early", another software pattern that I personally enjoy. It says that you extract the functionality of retrieving some data into a method and, inside it, return from the method as soon as you fail a necessary condition for extracting that data. Something like this:

public Order OrderCakeForClient(int clientId) {
  var client = _clientRepo.GetClient(clientId);
  if (client == null) {
    _logger.Log("Client doesn't exist");
    return null;
  }
  var preferences = _clientRepo.GetPreferences(client);
  if (preferences == null) {
    _logger.Log("Client has not submitted preferences");
    return null;
  }
  var existingOrder = _orderRepo.GetOrder(client, preferences);
  if (existingOrder != null) {
    _logger.Log("Client has already ordered their cake");
    return existingOrder;
  }
  var cake = _inventoryRepo.GetCakeByPreferences(preferences);
  if (cake == null) {
    cake = MakeNewCake(preferences);
  }
  if (cake == null) {
    _logger.Log("Cannot make cake as requested by client");
    return null;
  }
  var order = _orderRepo.GenerateOrder(client, cake);
  if (order == null) {
    _logger.Log("Generating order failed");
    throw new OrderFailedException();
  }
  return order;
}

This is a long method that appears to be linear, but in fact it is not. At every step there is the opportunity to exit the method therefore this is like a very thin tree, not a line. And it is a contrived example. A real life flow would have multiple decision points, branching and then merging back, with asynchronous logic and so on and so on.

If you want to split it into smaller methods you will have some issues:

  • the most of the code is not actual logic code, but logging code - one could make a method called getPreferences(client), but it would just proxy the _clientRepo method and gain nothing
  • one could try to extract a method that gets the preferences, logs and decides to exit - one cannot do that directly, because you cannot make an exit decision in a child method

Here is a way that this could work. I personally like it, but as you will see later on, it's not sufficient. Let's encode the exit decision as a boolean and get the information we want as out parameters. Then the code would look like this:

public Order OrderCakeForClient(int clientId) {
  if clientExists(clientId, out Client client)
    && clientSubmittedPreferences(client, out Preferences preferences)
    && orderDoesntExist(client, preferences, out Order existingOrder)
    && getACake(preferences, out Cake cake) {
    return generateOrder(client,cake);
  }
  return existingOrder;
}

private bool clientExists(clientId, out Client client) {
  client = _clientRepo.GetClient(clientId);
  if (client == null) {
    _logger.Log("Client doesn't exist");
    return false;
  }
  return true; 
}

private bool clientSubmittedPreferences(Client client, out Preferences preferences) {
  preferences = _clientRepo.GetPreferences(client);
  if (preferences == null) {
    _logger.Log("Client has not submitted preferences");
    return false;
  }
  return true;
}

private bool orderDoesntExist(Client client, Preferences preferences,
                               out Order existingOrder) {
  existingOrder = _orderRepo.GetOrder(client, preferences);
  if (existingOrder != null) {
    _logger.Log("Client has already ordered their cake");
    return false;
  }
  return true;
}

private bool getACake(Preferences preferences, out Cake cake)
  cake = _inventoryRepo.GetCakeByPreferences(preferences);
  if (cake == null) {
    cake = MakeNewCake(preferences);
  }
  if (cake == null) {
    _logger.Log("Cannot make cake as requested by client");
    return false;
  }
  return true;
}

private Order generateOrder(Client client, Cake cake)
  var order = _orderRepo.GenerateOrder(client, cake);
  if (order == null) {
    _logger.Log("Generating order failed");
    throw new OrderFailedException();
  }
  return order;
}

Now reading OrderCakeForClient is a joy! Other than the kind of weird assignment of existingOrder in a condition method, which is valid in C# 7, but not that easy to read, one can grasp the logic of the method from a single glance as a process that only runs if four conditions are met.

However, there are some problems here. One of them is that the out syntax only works for non-async methods and it is generally frowned upon these days. The method assumes a cake can just be made instantly, when we know it takes time, care, effort and kitchen cleaning. Also, modern code rarely features synchronous database access.

So how do we fix it? The classic solution for getting rid of the out syntax is to create custom return types that contain everything the method returns. Let's try to rewrite the method with async in mind:

public async Task<Order> OrderCakeForClient(int clientId) {
  var clientExistsResult = await clientExists(clientId);
  if (!clientExistsResult.Success) return null;
  var orderDoesntExistResult = await orderDoesntExist(client, preferences)
  if (!orderDoesntExistResult.Success) return orderDoesntExistResult.Order;
  var getACakeResult = await getACake(preferences);
  if (!getACakeResult.Success) return null;
  return generateOrder(client,cake);
}

private async Task<ClientExistsResult> clientExists(clientId) {
  client = await _clientRepo.GetClient(clientId);
  if (client == null) {
    _logger.Log("Client doesn't exist");
    return new ClientExistsResult { Success = false };
  }
  return new ClientExistsResult { Client = client, Success = false }; 
}

// the rest ommitted for brevity

Wait... this doesn't look good at all! We wrote a ton of extra code and we got... something that is more similar to the original code than the easy to read one. What happened? Several things:

  • because we couldn't return a bool, he had to revert to early exiting - not bad in itself, but adds code that feels to duplicate the logic in the condition methods
  • we added a return type for each condition method - extra code that provides no extra functionality, not to mention ugly
  • already returning bool values was awkward, returning these result objects is a lot more so
  • the only reason why we needed to return a result value (bool or something more complex) was to move the logging behavior in the smaller methods

"Step aside!" the software architect will say and quickly draw on the whiteboard a workflow framework that will allow us to rewrite any flow as a combination of classes that can be configured in XML. He is dragged away from the room, spitting and shouting.

The problem in the code is that we want to do three things at the same time:

  1. write a simple, easy to read, flow-like code
  2. make decisions based on partial results of that code
  3. store the partial results of that code

There is a common software pattern that is normally used for flow like code: the builder pattern. However, it feels unintuitive to use it here. First of all, the builder pattern needs some masterful code writing to make it work with async/await. Plus, most people, when thinking about a builder, they think of a separate reusable class that handles logic that is independent from the place where it is used. But it doesn't need to be so. Let's rewrite this code using a builder like logic:

public async Task<Order> OrderCakeForClient(int clientId)
{
    SetClientId(clientId);
    await IfClientExists();
    await IfClientSubmittedPreferences();
    await IfOrderDoesntExist();
    await IfGotACake();
    return await GenerateOrder();
}

private bool _continueFlow = true;
private int _clientId;
private Client _client;
private Preferences _preferences;
private Order _existingOrder;
private Cake _cake;

public void SetClientId(int clientId)
{
    _clientId = clientId;
    _existingOrder = null;
    _continueFlow = true;
}

public async Task IfClientExists()
{
    if (!_continueFlow) return;
    _client = await _clientRepo.GetClient(_clientId);
    test(_client != null, "Client doesn't exist");
}

public async Task IfClientSubmittedPreferences()
{
    if (!_continueFlow) return;
    _preferences = await _clientRepo.GetPreferences(_client);
    test(_preferences != null, "Client has not submitted preferences");
}

public async Task IfOrderDoesntExist()
{
    if (!_continueFlow) return;
    _existingOrder = await _orderRepo.GetOrder(_client, _preferences);
    test(_existingOrder == null, "Client has already ordered their cake");
}

public async Task IfGotACake()
{
    if (!_continueFlow) return;
    _cake = await _inventoryRepo.GetCakeByPreferences(_preferences)
        ?? await MakeNewCake(_preferences);
    test(_cake != null, "Cannot make cake as requested by client");
}

public async Task<Order> GenerateOrder()
{
    if (!_continueFlow) return _existingOrder;
    var order = await _orderRepo.GenerateOrder(_client, _cake);
    if (order == null)
    {
        _logger.Log("Generating order failed");
        throw new OrderFailedException();
    }
    return order;
}

private void test(bool condition, string logText)
{
    if (!condition)
    {
        _continueFlow = false;
        _logger.Log(logText);
    }
}

No need for a new builder class, just add builder like methods to the existing class. No need to return the instance of the class, since it's only used inside it. No need for chaining because we don't return anything and chaining with async is a nightmare.

The ugly secret is, of course, using fields of the class instead of local variables. That may add other problems, like multithread safety issues, but those are not in the scope of this post.

I've shown a pretty stupid piece of code that anyway was difficult to properly split into smaller methods. I've demonstrated several ways to do that, the choice of which depends on the actual requirements of your code. Hope that helps!

  I have heard about Jack Kerouac and his most famous book On the Road for as long as I can remember, but I had never read it until now. I did watch the 2012 movie with the same name, though, and I gave it the highest rating. I still believe Garrett Hedlund was amazing in it and that the guy needs more great roles like that. So, while whole books have been written about the Beat Generation, Jack Kerouac and his friends and about On the Road itself, what did I, greatest book critic ever, think of it?

  I liked it. I can say that parts of it were lovely and parts of it boring. But consider this: Kerouac wrote this as a "scroll", based on a stream of thoughts randomly thrown on whatever paper he could find on his travels, shaped by whatever place he was in and what mood he was having and which people he was with and what substances coursed through his body. The scroll itself is twice as big as the book he eventually published and On the Road is considered part of the Duluoz Legend series, which spans 13 books. The thing to look for in his writing cannot be about specific details, but about the overall philosophy, the experience.

  That is why I can safely and with certainty say: I will not read the scroll version, I liked the book, but I loved the movie. And while this is not a review of the film, I did notice that many of its critics were mainly focused on "it's not like the book". Gentlemen, if the film would have been about other people doing other things, but in the same spirit as the book, it would still have been On the Road and just as entertaining. Because, while this is based on actual people and actual experiences, the specifics are quite irrelevant. Once you capture the spirit of the thing, the rest is just filler.

  So what is the book about? Jack and his buddy Dean spend the entire time moving from New York to San Francisco and back, using their own cars, car sharing, hitching, jumping on trains, buses, or however they could, enjoying each other's company and the feeling of being on the road and meeting interesting people and living life at its fullest. The film has a great female cast, but you will notice that they are barely doing anything. They are there in the background, because while the story contains them, it is not focused on them. It's even more so in the book, where characters jump in and out of the story: travel companions, drink and drug buddies, random sex, true love, marriages, children, people who let them sleep in their houses with or without pleasure. And while everything is told from the perspective of the writer and Dean has the next more important role, even then you cannot say the story is about them.

  The effect that both book and movie had on me was quite an antisocial one. They made me dream of travelling light, experiencing all kinds of adventures while caring about nothing and nobody, just living in the moment. It's a nice fantasy, one that breaks easily under the weight of my own nature and the oppressive organization of the present, but nice nonetheless. On the Road gives us a glimpse of what was gained and what got lost in 70 years from the perspective of people doing the living back then. There is no hero, no villain, no moral to the story and no mystery to solve. Just people being as free as the world lets them to.

Bottom line: not the best book that I have ever read, but also great, fresh, honest, worth reading, with characters worth knowing. It is important to know that in order to get to the curated, safe, stale world we live in, others had to try all kinds of other things, that freedom is something you feel rather than something given to you. This is a fantasy and an autobiography all at once. That's the part that I loved most.

  I am watching Star Trek: The Next Generation, a show that I have loved since I was a child and was watching obsessively again and again at that time. Yet as I grew older (and hopefully wiser) and with full knowledge of TV and movie culture since then, I see many new things in this show that I was unable at the time of my youth.

  Next Generation is, on the surface, a story about a wonderful future in which humanity has somehow distilled its best qualities and created a post-scarcity utopia that anyone can enjoy and in which everybody can thrive. People are intelligent, educated, passionate, considerate, moral, loyal and dutiful. They don't even have money anymore!  In a show made in 1987, computers were there just to do the bidding of humans, with no creativity or decision power. Security was just a matter of choosing a good password any anyone could access almost everything given a few minutes.

   However this was not unintentional. The vision of the show was focused on "humanity at its best" and so it could never be outmatched by algorithms, machines or cold calculation. And the most beautiful thing of all is Starfleet, an organization dedicated to knowledge and exploration, diplomacy and discovery, where everyone who is insanely qualified can find their place amongst the stars, happy to serve their duty in a heavily structured navy that is at the same time diverse, inclusive, quaint and strict.

  It surely inspired me when I was a child, but now I start seeing things that I couldn't then. The judgement of anyone who is different while expressing views of total tolerance, for example. And I am not talking about species that were particularly designed to be repugnant or immoral, like the Ferengi, but about people. Barclay, for example, a brilliant engineer that can't find the confidence to assert himself is ridiculed for his addiction to the holodeck, called Broccoli behind his back, almost transferred because he is not expressing himself as expected and punctual enough, yet embraced when he saves the day. At that time it felt like an honest mistake that the crew wished to resolve and in the end did. But what if he didn't save the day? In another episode, Riker refuses yet another promotion to captain and an admiral asserts his career will suffer, as other young and brilliant people aim higher than him, which makes him seem a risk avoider. And in yet another episode Picard goes back in time to behave more rationally in his youth, only to find himself in the present relegated to a role of lieutenant that is not taken seriously when asking for advancement because he had always chosen the safe path.

  All this went over my head when I was young, but now it sounds a lot just like the most toxic of corporate cultures. You either fit in and play happy or you are pushed out to a life that no one even mentions. You can tend plants in your garden for the rest of your life, because if you didn't fall in line with the office rulebook, you won't be working there. That doesn't sound like a utopia for me, but a dystopia, a world ruled by churches that expect, with kindness, that you obey the rules exactly, both in your work life and your personal one, move in a certain way, behave in a certain way, talk in a certain way and navigate topics of conversation carefully. In fact, many a time in Star Trek, the line between work and personal life was explicitly rejected. In one episode Deanna Troi shouts to her mother that the crew of the Enterprise is her family and there lies her life. In many others Picard refuses to go on vacation and even there he is reading heavy stuff that will help him at his work.

  The principles spouted by the actors in the show are also routinely broken by actions motivated with sophistry and dramatism. But not just anyone can break those principles. One of the main cast can do it, and always under the benevolent yet strict oversight of the captain. And in case you want to "play the game" and "fake it till you make it" there is always counselor Troi to invade your privacy and broadcast you real emotions to the captain.

  And I admit that I am a corporate guy, enjoying the relative safety and monetary comfort by sacrificing some of my principles and remaining relevant to my level of employment. The truth is that the same environment can be a blessing for some and a nightmare for others. Yet the problem is not the rules themselves, but how static and rigid they are. If one can either choose one way to behave or the other, with no overlap and a large gap between the two, there is little chance for people from a group to move to the other. Without that mobility things stagnate and die and that is exactly my own experience in real life corporations.

  I am not trying to criticize The Next Generation here. It was an amazing show that churned 25 episodes of good storytelling and decent acting per year for seven years in a row and which generated two spinoffs: DS9 and Voyager. Compare this with today's Star Trek: seasons of 13 episodes with three times the budget per episode (adjusted for inflation) and a linear storyline that is neither original nor well thought. What I am trying to say is that under the veneer of a beautiful bright future, one that Gene Roddenberry imagined with the best of intentions, the details belie the influence of the real world and of how people really function. It's a wonderful example of how the same concepts and the same words look great at one time and less so after you experience them.

  Bottom line: I think Gene's vision was great and the future imagined by him puts the present to shame, yet I am sure I would have had a very hard time adapting to life on the Enterprise. Perhaps I would have been the guy at the teleporter station, who obviously has no reason to do anything there unless when orbiting or approaching another ship, doing his job in a place with no windows or chairs and that somehow everyone knows by name. Or the cadet who always finds ways of optimizing things, but can't navigate the complicated rules of political correctness or the chain of command when wanting to express them. Or Barclay. Probably Barclay.

Intro

  Labels. Why do we need them? At first it seems like a natural outcome of people trying to understand their surroundings: good/bad, light/dark, wet/dry, etc. It makes sense to start with a simplified model of reality when it is all brand new. However, as we grow, we soon realize that God/Devil is in the details, that taste is more a matter of subtlety than brute strength and that labels, as useful as they have been, sometimes need throwing away. As the old adage says: a beginner needs to learn the rules, an expert knows all the rules, a master knows when to break the rules.

  So how come, with such a general and all encompassing principle, proven many times over millennia, we still cling to labels? And not only to understand the world around, but to understand ourselves and, ultimately, define ourselves? Not only internally, but externally, as a society? Codifying them in laws and unspoken yet strongly enforced rules?

An innocent example

  Let me give you an example. When we enter adolescence we start getting sexually attracted by other people. So this imaginary adolescent (A) likes one girl, then another, then another. After three girls he decides, with the tacit and active approval of his relatives and friends, he is straight. Another imaginary adolescent (B) likes guys, so he's gay. And now, so that we can identify the usefulness of these concepts, we add a third adolescent (C). A sexy young stud that likes... girls, let's say, and has managed to not only like them, but successfully have sexual encounters with them. He has had sex with 20 girls. So tell me, who is more like who in this triangle of adolescents? How do you split this hyperplane of three people into two parts? How do you cluster these people into two groups? Because to me it seems that A and B are far more alike than any of them is similar to C. Moreover, is the sexual attraction pattern that has been established in early adolescence even stable? What happens if the next person A likes is another guy? Is he bisexual now? By how much? Is he 75% hetero?

  Leaving my personal thoughts aside, can anyone tell me what these labels are for? Because if you find yourself sexually attracted by someone, then for sure you don't need a statistical model to analyze that. Is it for the benefit of the other person? "Sorry, but I am straight", which would translate to something like "Oh, I have to tell you that, based on the statistical evidence for sexual attraction I have gathered, I seem to be exclusively attracted to girls. So don't take it personally. I have nothing against gay people, I just have a biological reason to reject any of your advances". Does that sound in any way useful? Especially since we are being taught that one does not refute another's reasons for sexual or romantic rejection, that they have the given right to unilaterally refuse, regardless of any rational reason.

  One might argue that these labels are like armor to define and strengthen the identity of people. You don't just observe you are straight or gay, you define yourself as such, thus avoiding confusion, minimizing internal conflict and adhering to a community. Then, collectively, one can fight the inevitable "You are weird and must die" situation in which all people find themselves in, at one time or the other, when facing people different from themselves. But then, isn't clearly defining a group of people painting a target on their back? Look at the LGBTQ... whatever community. They are actively combatting the discrimination and disrespect that is thrown at them by finely defining the specific sexual group they belong to, then bundling them all together into a community of completely different people. Because they have a common enemy, you see, the cis people (a term they had to invent to define the majority of people, so they don't have to define themselves as not normal). So if I am gay, for example, I am the G person, not the B person, which also accepts sexual encounters with people of the other sex. Why is that important?

  Why can't I fuck whoever I want to fuck, assuming they agree? Why do I need a label which will restrict my choices in the future?

  People managed to somehow debate gender now. And not in terms of "why does it matter?" but in "you didn't define it correctly. It's spelled Phemail, as per the new gender atlas of 2022!"

A less divisive topic

  And what I am saying is not related just to sexuality. Say race, to take something less divisive. Am I White? How do you know? Because the color of my skin? What if you found out that my parents are both Black and I have a skin condition? Is it ancestry, then? The proportion of genetic code from various (very vaguely defined) groups of people in my own? Then we get to the same thing: if my grandfather is Black, am I 25% Black? What if he was Japanese? What the hell does that matter anyway? Why do we need labels like "Caucasian", "non-White", "person of color", "African American"? Am I a European Romanian as opposed to a South Asian Romanian because his Indian-like race was enslaved in Europe a bunch of centuries ago? Who needs this crap? Is it to define values for eventual retribution for perceived historical slights? Is race an accounting concept?

  I identify as a software developer. I am more alike people writing software that with the majority of men, Romanians, sun deprived people with terribly white skin, guys who like girls or humans in general. And there are a lot of software people that are nothing like me. Is it a useful identity, then, other than for HR people? I would say no. No one cares anyway, except when meeting new people and they ask what I do, I tell them, then there is that awkward "Oh..." and they go ask someone else.

The hell with it

  And the holy trinity would not be complete without religion. Religion is a concept you choose! It's the only thing you are protected by law to believe despite any evidence and to act accordingly. It is the same as the identity shield portion of race or sexuality, but that's where the buck stops. No one can prove you are a Christian or a Buddhist. It's a completely arbitrary belief system that is codified only when interacting with other people. You do to Church and if they start singing, or doing strange hand gestures, you better know the lyrics and the gestures or they won't look positively on you. It's like the secret handshake of the gang in your neighborhood. But when you are all alone and you think about God, it's sure that you are thinking of it slightly different than any other person in the world. So why do you need the label? Why can't you believe in two gods, hedge your bets so to speak? You go to the mosque and then to the synagogue. Surely double dipping would be a worse sin than not believing in the true God, wouldn't it? And then, what God do you believe in more?

  Even nationality is stupid. Does the place where I was born define me, or maybe the one I lived the most in? It certainly influences my culture, my values and one can statistically infer many things about me from them, but they are just influences on the path of my life. Some may be important, some not, I may have rejected some or grew out of them. Other than administrative and bureaucratic reasons, nationality is again a mere choice!

  I agree with people who choose to define themselves in certain ways. I respect every personal choice as long as it doesn't hurt others. I am not against self-defining. What I am against, though, is about giving social and legal power to these labels. And then to redefine them again and again as times change. Think of the tortuous etymology of the word "antisemite" for example. You want to define yourself, fine! Don't impose it on me, though. "I identify as a serial killer. Please don't disrupt me in observing the rituals of my people and let me stab you!"

So what's your point?

  We live in a time where everybody and their grandmother decry divisiveness, extremism, polarization. It seems to me that if we want to minimize that, we should at least renounce placing people in disjunct boxes. One shouldn't care what my race, religion or sexuality is until it's relevant to some sort of interaction. And if they find out, it shouldn't be any more important than any other trivia about my person. I say fight the entire idea of labeling people, as a general principle, whether you do it to hurt them or to declaratively protect them. And if you want to build an atlas to categorize the weird and beautiful human species, do it from a place of observation, not coercion.

Forget canon

  Which brings me to the last point. Some people religiously defend their belief in ... imaginary characters and stories. You hear stuff like "In reality, Star Trek canon says that...". No. I have watched everything Star Trek. There is no canon. Canon is used in the concept of religious writings, where people arbitrarily decide what part of a religion is correct and for which part one should burn other people for supporting. It has no place in fiction. Good writing needs to be consistent. If it spreads over multiple decades, multiple writers, multiple IP owners and different times, it needs to adapt. You can say that something is stupidly inconsistent or that adapting old ideas to new times sometimes is detrimental to those ideas and you'd better start anew with fresh stuff. You might even call people idiots for the way they chose to do any of these things. What you cannot expect is canon for imagination! If you do, you are only helping lawyers carve out the landscape of human fantasy and parcel out terrain and capital for the people who care the least about your entertainment.

Conclusion

  Exploring a new domain always requires defining labels, as a simplistic model for charting the unknown. People are not a new domain, nor are they unknown. They may be unknowable, but they certainly don't belong in nicely shelved boxes in the warehouse of politicians, accountants or lawyers, people lacking all imagination or passion. If you believe the current model of interacting with the world is wrong, maybe the surest way to fix it is to renounce and denounce the labels that define the model.

  A while ago I started looking for books about microbial biology, for whatever reason, and so I also added From Bacteria to Bach and Back, without bothering to look at the description or any of the reviews. And it was a hard to find book, too! So here I am, happy to have gotten it and looking forward to its wisdom. I really try to finish books that I have started, so I did with this one as well, but just couldn't. I had to decide if I want to abandon this and read some other book or just find new reasons to scroll Facebook forever!

  And the reason is not that the book is not saying something interesting and important or that it is not researched. The reason for me being unable to finish reading it is solely based on the style of the writing. Imagine David Attenborough at his most pompous, writing something that has the scope of something Yuval Noah Harari would write and with the condescendence of Richard Dawkins because he wanted to outdo Douglas Hofstadter and you get Daniel C. Dennett writing this book, but without the charisma, conciseness or cleverness of either of the others.

  The book relates exclusively on how evolution leads to intelligence, how our conscious minds can be explained by evolution and mechanistic principles alone and that concepts like free will are not consistent with anything scientific. The problem is that after saying that, it continues to repeat it, more and more smugly, trying to dot every i and cross every t, until reading becomes unbearable. And yes, one could have expected something like this from someone actually named Daniel Clement Dennett the Third, age 75 and having dedicated his life to defining and researching consciousness, but it doesn't make getting through the book any easier. It has nothing to do with bacteria or Bach, other than empty correlations, either.

  Apparently, this should have been the distillation of Dennett's thinking. At almost 500 pages, this is not distilling anything! You don't go into a pub to get a distillate and ask for a pint. And while the subject is interesting and the conclusions iron clad, I do believe that a smart editor could have created a wonderful little book by deleting two thirds of everything written in this.

  Bottom line: sorry, but I couldn't finish it. I couldn't even reach the half point.

 

  BTW, if you are a player of the game, leave a comment. I would like to meet the people I play with.

Intro

  For me it is strange that Kogama Battle isn't a more famous game. I am searching for it on the Internet and no one talks about it. And it's too bad, because it has all the hallmarks of a great game: flexibility, action, strategy, team play, accessibility.

  KB is a browser 3D shooter game. The 3D models are very simple and require little resources, but the network code is pretty good. There are two teams, Red and Blue, each starting from their own "castle". The two castles are three floors high and separated from each other by a water moat in which there are some islands to hop on. The purpose of the game is to reach the flag that is found in the other basecamp. Sounds easy, and it is. But there are so many different ways to win the game, that it becomes extremely amusing to play, if you have people who know how to play it on both sides.

  In this post I will:

  1. enumerate the different strategies for winning
  2. talk about what is good about the game
  3. talk about what is bad about the game
  4. list the items one can use in the game
  5. conclusion

How to win

1. Open the gate

  The obvious way to finish the game seems to be getting the key to the enemy castle (which lies on your side of the water) and carry it to the gate. You have to do this 10 times, then the door opens, allowing access to the enemy flag.

  Counter measures:

  • shoot the enemy as they get the key (either directly or shooting at the target stuck on the platform where the key is, which makes the entire platform explode and kill anyone there)
    • you can use the firewall, too, but it's pretty useless
  • after they open the gate, go to the enemy side, get the key and take it to your gate (applying the key to an open gate closes it and sets the counter back to 10)
    • this of course means your team must defend the flag from the people who entered the base
  • use the builder gun to cover the inside of the gate so that the enemy cannot immediately enter the base
    • the enemy might counter this by shooting a bazooka at the gate before they open it

  The greatest fun here is to get to the enemy side and steal a key when your gate counter is very low, then enter the castle and wait on the top floor. When the enemy has succeeded to open the gate you jump from above and immediately close it. Combined with the builder gun barricade, it makes for great satisfaction to foil your enemy.

2. Use the back door

  On the left side of the stairs to the gate there is a block out of place. It is a hint that you can do something with it. Shoot at it (and the next four blocks) and you open a tunnel to the enemy base. You can only go through it by using the shrinking pill, which means you can penetrate the enemy base, but unarmed and having to wait until you grow back again.

  Counter measures:

  • use the block gun to ... err ... block the tunnel from the inside of the base. Since the enemy is shrunken, they cannot shoot through it
    • there is a way for the enemy to destroy the blocks inside, as well as any defenses, and that is to temporarily switch team. Obviously, this is a form of cheating and only assholes use it, but it adds an element of "sabotage" to the game.
  • kill the tiny enemies, preferably with the flamethrower, when they emerge helpless from the tunnel :)
    • this wastes the resource of a person, but it is fun

3. Come through the window

  One can use the block gun in a variety of ways to gain access, but this is almost like it was designed like that. You need to make a stair like structure with the block gun that leads from the shrinking pill outside to the defense window above. Then, shrink yourself and enter the enemy base through the window, just like with the tunnel.

  Counter measures:

  • use the block gun to block the defense window on the pill side
    • the enemy can destroy that block easily, though, so it must be periodically checked, from outside and inside
  • kill the tiny enemies when they enter the window
  • destroy the blocks as they build the stair

4. Any other way of using the block gun to get to the enemy side:

  • jump and shoot a block under you, creating a column that pushes you up and allows you to get in the enemy base from the top floor
  • attach blocks on the walls of the map and create a bridge to get from one side to another
    • warning, when you create a bridge, the enemy can use it as well
  • shoot from your base to the other base so that there is a bridge created from the enemy base to the central suspended platform, then use the underwater teleporter to get onto the bridge
  • any type of ladder on the enemy base that allows you to get to the top floor

  Counter measures:

  • be vigilant and destroy the block structures constructed by the enemy (a bazooka is most effective)
  • kill enemies that manage to get in the base

5. Ugh! Rocket jumps

  Someone played Quake when they were young and they implemented the same thing here. In my opinion the bazooka is the worst item in the game, killing people after three shots, but destroying a lot of blocks and allowing rocket jumps. It holds 12 shots! I personally believe that people should be ashamed of themselves for using rocket jumps in Kogama Battle, because they are completely screwing the flow of the game.

  That being said, using a bazooka one can reach the other side's flag in less than 30 seconds.

  Another type of jump is pistol jump. I only saw it done once and it looks like a rocket jump, but without getting damaged, which is really dumb to have been allowed. I think you might need to have a jump bonus for this to work. Ugh, bonuses!

  Counter measures:

  • the only real solution is basing someone inside the flag room, armed with a flamethrower or a machine gun, ready to kill the attacker, who should be wounded from the rocket jumps
    • having health around in the base doesn't really help, though
  • some block structures can be erected to deter some sorts of rocket jumps, but it is a trivial matter to destroy them with the same weapon used for the jumps
  • use a sniper to hit them before they rocket jump to your base, which is pretty enjoyable, especially if they have a health bonus and thus die not from your sniper, but from their own jump

6. Team work

  Playing within a common strategy with other people is the fastest way to win in a satisfying manner. Even unlocking a gate takes just a few minutes with people defending the key bearers and having at least two of those. Once a gate is open, there is almost no way to defend the flag from incoming enemies and a strong team can stop anyone from grabbing the 11th key to close the door.

7. Use blocks to guard your flag

  This is more a way to prevent loss, rather than promote a win, but it's necessary. The strategy here involves blocking the way to the flag with blocks. If placed well, they will stop the enemy while the lava wall burns them or force them to fall into a lava pit. Just blocking the entry to the flag room is not enough, usually it takes at least 5 levels of walls. The walls don't need to cover everything from top to bottom, just to stop the movement of the enemy. Sometimes leaving holes in the walls lures enemies thinking there is a way through without having to shoot the blocks out.

  Usually this strategy is essential to delay enemies that opened the gate while you run to close it. Then, press K, which commits suicide, and chances are you will be respawned in the base on the top floor, ready to kill whoever is there.

8. Cheating

  I already said that rocket jumps are shameful, but even worse is switching teams to sabotage because you can't play the game properly. One can do that, and forever lose any self esteem, to use it to destroy block defenses or gain information

The good

  As you can see from above, there are multiple ways to play this. If you play beginners you can even harass them in their own base or write insults with the block gun in their own base, rather than end the round by reaching the flag. There are strategies, counters and counter counters, and they all change based on the composition of the teams. It is the thing that makes it so fun for me. Even for people who only care about shooting, one can be a sniper, a machine gunner, an akimbo shooter, using a flamethrower or a bazooka or a shotgun. People can play offense, defense, or both. There are a myriad ways to use the block gun to do all kinds of things.

  It's a browser game! Just open the page and play! The game moves smoothly, even if sometimes you see people skipping if they have a network issue. It is a shooter, but you don't need special skills to play it. I personally play it with the little laptop dongle on the keyboard (which also makes me unable to shoot while moving, a strange side effect of using the dongle in web games that I can't explain)

  The game is also as short as you want it. I have played 30 minutes rounds protecting the base alone against ten enemies and finished some in 2 minutes.

  There is no chat! Actually there is, but no one uses it because it is an option you have to sign in for. You can do this only on the Kogama web site, but most people play Kogama Battle on other servers. This means no one can shout abuse at you or explain to everybody how things are done or collaborate with the team (unless they use some other channel like a Discord chat) and log in together.

The bad

  The rocket gun! It is so unlike any other item in the game. It destroys everything in its path, except actual players. Carefully crafted block structures are blown away in a second. It holds 12 rounds of ammo! And it allows for rocket jumps. People who rocket jump should be dead when they land!

  The flamethrower. It is a very nice weapon, but has low damage and no lasting flame damage. When you stop shooting it, the damage stops. That's not how flamethrowers work.

  There is no chat! I know this is a good thing, but it is also a bad one. Many a times people who have no idea how to play the game (or trolls) grab a bazooka and start to destroy the defenses trying to get to their own flag! A special kind of person (that is amazingly common) comes and uses the block gun to cover the lava pits so that the enemy can get to the flag better. And they don't even intend harm, they just want to reach the flag and are scared of jumping, I suppose?

  Bonuses. There is a way to get some small perks for the game, like extra life, extra jump, extra speed. I don't know, I never used them. It spices things up, but it also breaks the rhythm of the game. With an extra hit points bonus you don't get instakilled by snipers and you can rocket jump with impunity. I think they are shameful.

  The firewall. Each base has a platform that triggers a wall of fire in front of the gate when a person sits on it. The fire doesn't stick, the damage is low and one needs just the smallest amount of time to use the key to unlock the gate. The firewall, as it stands, is useless.

  The two sides are not created equal. Differences in how blocks stick to the gate, the size of the lava wall and some random blocks on the lower level makes the red side better than the blue one.

  Team inequality is also a problem. One can switch team at any time, join the bigger team, switch again.

Items in the game

Weapons:

  • shotgun
    • fires slowly and in a limited range, but is very powerful. 
    • kills someone in two or three shots, depending on distance
  • flamethrower
    • continuous fire and limited range, medium damage, fires through walls
    • as discussed above, it looks cool and it can be found in a more accessible area of the base, but it's usually less effective than a shotgun
  • akimbo revolvers
    • strange weapons that push you back (no other weapon does that) making aiming difficult, medium damage
    • they are placed outside, good for quickly picking up and destroying blocks or shooting at platform triggers
  • machine gun
    • fires fast, low damage bullets, lots of ammo, pushes people back
    • perfect for pushing someone of a ledge or for defending the base, as it disrupts enemy movement a little
    • good for destroying blocks
  • sniper
    • very high damage, usually kills in one shot (see bonuses)
    • only 5 shots and it needs a long charging time before shooting
    • doesn't affect blocks
  • bazooka
    • destroys blocks easily on a large area, the explosion pushes the shooter (but not the target), needs three shots to kill a player
    • blast also hurts user, but not your own team
    • explosion has area damage that goes through walls as well
    • nasty and stupid weapon :D
  • life gun
    • a weird and kind of useless contraption
    • when fired at an enemy, it sucks away their life, but once stopped, life jumps back to the initial level
    • when used at an ally, it gives life to them, maybe also temporarily. I've never used it.
    • maybe it has a different hidden use as well?
  • block gun
    • fires blocks of destructible stone that can attach themselves to walls or other blocks
    • can be used to defend against bazookas, as placing a block in front of the shooter will make them hurt themselves (even if they are your own team, like for trolls)
    • pressing long will destroy blocks and return them to you

Map features:

  • teleporter
    • there is one in each base lower level that leads in and out and can only be used by the base team
    • there is a neutral one under water which leads to a suspended ledge above it
  • trigger
    • it is a platform that triggers something when someone stands on it
    • there is one in each base to trigger the firewall
    • there is one outside each base, invisible, left of the staircase, sounding an alarm every time someone steps there (announcing a possible tunnel breach)
    • there are triggers on the key platforms, ringing when someone is on them
  • key
    • on each side of the water there is a key that opens the gate on the other side
    • the key is located upon a platform that has a target trigger attached to it
    • takes some time to respawn
    • if you are killed when carrying one, the key is dropped for a few seconds, permitting a team mate to continue carrying it
  • target trigger
    • attached to the platforms on which keys are located
    • if shot, they make the platform explode, killing everything on it
    • takes some time to recharge
  • destroyable blocks
    • not only you can place blocks, there are some placed for you
    • they can be destroyed to gain faster exit access or to get to the flag or secret tunnel
  • lava pits
    • found only in the flag room, they can be jumped over easily
    • if touched by lava you burn fast until you die, even if you get out of it
  • lava wall
    • also in the flag room, it moves from one side of the room to the other and back
    • touching it makes you burn until death
  • lava edges
    • there is one on the top edge of a wall of the top floor as well as around the walls of the map itself
    • pretty useless and only accidentally can someone get burnt by them
  • gates
    • one for each base, they start locked 10 times
    • you need a key with the same color for each of the times to open it
    • a key will reset a gate to closed if used on an open gate
  • middle platform
    • only accessible by using the underwater teleporter (or lucky rocket jumps)
    • it allows for some ways to get to the enemy base as well as an overview of the entire map
    • people sitting on the platform are easily killed from the top of the base
  • shrink pill
    • found outside the base as well as inside the tunnel and inside the base
    • they shrink you to a size that allows for going through small holes or windows
    • you lose any weapon you have when you shrink
  • defense ports
    • each base has two small ones on the lower level, where one can use snipers and bazookas against enemies going for the key
    • each base has two medium ones on the middle level, large enough for a shrunken person to go through
    • each base has large holes in the thin wall on the top floor through which one can look and shoot at the enemies
  • water
    • water makes it almost impossible to see outside it, but you are visible to anyone looking in the water
    • stay long enough under water and you will take very little damage

Game features:

  • the long jump
    • jumps depend on how long one presses space
    • you need to master the long jump before you can play this game well
  • access from the base
    • you can exit the base by using the teleporter or jumping from the top floor
    • in order to exit faster (and safer) use the machine gun to cut through the destructible blocks next to them (or a bazooka, or a block gun)
  • the machine gun push
    • machine gun bullets push the target a bit, which means you can disrupt their movement, push them into lava or into shrink pills (always fun, that)
  • flame through wall
    • much stronger than the firewall is using the flamethrower to shoot through the gate or through walls
    • warning! Do this in front of the gate and you might promote someone shooting a bazooka at you and destroying any block defense there
    • one can sit around a corner or even shoot through floors and give damage while protected from most guns
  • initial block setup
    • it is important when the round starts to cover these bases:
      • block tunnel under the Warning! sign
      • block defense window on the right on the middle floor (where the teleporter and small pill lie outside)
      • block flag by starting from the flag out: block access to the flag, block access out of the lava pit, block escape from lava wall, only then block the entry to the room. Here you need to not block the lava pits or give your enemy footholds above them, instead you block after the pits so that the enemy falls into them if they jump.

Conclusion

  This game is a lot of fun with the right people. If someone would make some small fixes, it could be the seed to a wonderful little game.

  My proposals:

  1. nerf the bazooka
    • less area damage against blocks, two at most and preferable dealing a lot less damage to a block behind a block
    • more damage against people
    • less blast pushback (no rocket jumps)
    • less ammo
  2. upgrade fire damage
    • increase fire damage from fire wall and flamethrower
    • and/or make fire stick to the target for a while
  3. nerf block gun
    • the block gun needs to be fast, so you can't nerf the speed of fire
    • so make it so you can't fire it while moving
      • this will allow for strategic long range structures, but disallow columns and jump-and-fire escapades from one side to the other
  4. force teams equal
    • make it so you can only join the smaller team
    • make the team switch (and initial game join) take a lot longer 
  5. no bonuses
    • remove bonuses, all players should be equal
  6. make it a real capture the flag game. The flag should be captured and taken to your own base before winning
    • this promotes teamwork, as the guy with the flag would not carry any weapons

  That's it. In my mind, this game would be perfect with just a few adjustments.

  You can play this game by googling for it and finding the biggest server at that time. Now, the servers I use are:

  • Crazy Games
  • Y8
  • any other server where Kogama Battle can be found via Google

 Have fun!

  Was I in a mood that I didn't enjoy Revenant Gun or has something changed in Yoon Ha Lee's writing? I can blame it partially on the fact that I didn't remember anything from the previous books, but I do remember I enjoyed them!

  Reading my review of the previous book I see some similarities in feeling: I don't remember much of the story or characters from before and it feels a bit sluggish at the beginning and rushed at the end. But the difference is that I had trouble finishing Revenant Gun and, instead of fondly remembering the situation where the other two books left off and getting closure, I felt like I had difficulty empathizing with any of the characters or caring about the story.

  And it's not like it's a straightforward book. It has two different threads, in one there is a resurrected Jedao reluctantly serving Kujen, the other is another Jedao, inhabiting the body of Cheris. Then there are a zillion officers, hexarhs, servitors, moths, lots of gay love that is unrelated to the story, but may have a place in the culture of this military universe and so on. The writing was decent, but it didn't blow me away.

  Bottom line: Perhaps the lucky ones are those who will read the entire trilogy at once and get both the freshness of the concepts and the closure of the story in one go. As such, I got almost nothing from this.

  Money is the root of all evil is a saying that has proven itself time and time again. Trying to make money from something that was not meant to do that will always soil and corrupt it. It is the case of so called "superchats", chat entries that have money attached to them.

  Here is how it works. Some content creator is doing a live stream and people are discussing the subject in the chat. There have been donation systems that allow people to give money to the creator for a long time and even there you see there is a bit of an issue. The streamer is almost forced by politeness (and because it encourages viewers) to acknowledge every donation. So they punctuate their content with "X has given me Y. Thanks a lot, X". This diminishes, albeit in a small way, the quality of the streamed content. Superchats are this, times 100.

  You see, when a chat message comes with money attached, the streamers are again motivated to acknowledge it. However, this time they read aloud the content of the message as well and respond to it, even if it is just with a sentence. This leads to significantly more disruption, but also has secondary effects that are at the core of the system. People have now been tiered into the ones that write a message and are ignored and the ones that pay to not be ignored, regardless of how useless, stupid or aggressive their chat message is.

  The content creator has only a few options at their disposal:

  • treat the superchats just like normal chat messages, in which case people won't be motivated to superchat, leading to less money for the stream
  • acknowledge and reply to just some of the superchats, which is a form of gambling for the message sender, if you think about it
  • acknowledge and reply to all superchats, which leads to a "super" tier of discussion that can only be accessed if you pay for it

Now, I understand how this system brings more money to the stream, but at what cost? People who crave attention are not the ones that you want to bring to the forefront of any discussion, but even so, many of them are immature teens. In order to have the system working, you need to stream, which motivates the creator to make interactive content and as long as possible to the detriment of short, concise, researched content.

The result is an explosion of low quality live streams, playing (preying!) on people's biases and social instincts, funded by the money of children and highlighting fragments of discussions based on how much they paid and not the quality of their content. Superchats are a disease of the Internet, akin to infomercials, television ads or paid news items. And unlike these, there are no tools to remove the streamer acknowledgements of superchats from the stream.

I am not an activist, but the only way to get rid of this toxic system is to actively fight it. I wonder if it could be seen as gambling, in a legal context. That should shut it down.

  Every month or so I see another article posted by some dev, usually with a catchy title using words like "demystifying" or "understanding" or "N array methods you should be using" or "simplify your Javascript" or something similar. It has become so mundane and boring that it makes me mad someone is still trying to cache on these tired ideas to try to appear smart. So stop doing it! There is no need to explain methods that were introduced in 2009!

  But it gets worse. These articles are partially misleading because Javascript has evolved past the need to receive or return data as arrays. Let me demystify the hell out of you.

  First of all, the methods we are discussing here are .filter and .map. There is of course .reduce, but that one doesn't necessarily return an array. Ironically, one can write both .filter and .map as a reduce function, so fix that one and you can get far. There is also .sort, which for performance reasons works a bit differently and returns nothing, so it cannot be chained as the others can. All of these methods from the Array object have something in common: they receive functions as parameters that are then applied to all of the items in the array. Read that again: all of the items.

  Having functions as first class citizens of the language has always been the case for Javascript, so that's not a great new thing to teach developers. And now, with arrow functions, these methods are even easier to use because there are no scope issues that caused so many hidden errors in the past.

  Let's take a common use example for these methods for data display. You have many data records that need to be displayed. You have to first filter them using some search parameters, then you have to order them so you can take just a maximum of n records to display on a page. Because what you display is not necessarily what you have as a data source, you also apply a transformation function before returning something. The code would look like this:

var colors = [
  {    name: 'red',    R: 255,    G: 0,    B: 0  },
  {    name: 'blue',   R: 0,      G: 0,    B: 255  },
  {    name: 'green',  R: 0,      G: 255,  B: 0  },
  {    name: 'pink',   R: 255,    G: 128,  B: 128  }
];

// it would be more efficient to get the reddish colors in an array
// and sort only those, but we want to discuss chaining array methods
colors.sort((c1, c2) => c1.name > c2.name ? 1 : (c1.name < c2.name ? -1 : 0));

const result = colors
  .filter(c => c.R > c.G && c.R > c.B)
  .slice(page * pageSize, (page + 1) * pageSize)
  .map(c => ({
      name: c.name,
      color: `#${hex(c.R)}${hex(c.G)}${hex(c.B)}`
  }));

This code takes a bunch of colors that have RGB values and a name and returns a page (defined by page and pageSize) of the colors that are "reddish" (more red than blue and green) order by name. The resulting objects have a name and an HTML color string.

This works for an array of four elements, it works fine for arrays of thousands of elements, too, but let's look at what it is doing:

  • we pushed the sort up, thus sorting all colors in order to get the nice syntax at the end, rather than sorting just the reddish colors
  • we filtered all colors, even if we needed just pageSize elements
  • we created an array at every step (three times), even if we only needed one with a max size of pageSize

Let's write this in a classical way, with loops, to see how it works:

const result = [];
let i=0;
for (const c of colors) {
	if (c.R<c.G || c.R<c.B) continue;
	i++;
	if (i<page*pageSize) continue;
	result.push({
      name: c.name,
      color: `#${hex(c.R)}${hex(c.G)}${hex(c.B)}`
    });
	if (result.length>=pageSize) break;
}

And it does this:

  • it iterates through the colors array, but it has an exit condition
  • it ignores not reddish colors
  • it ignores the colors of previous pages, but without storing them anywhere
  • it stores the reddish colors in the result as their transformed version directly
  • it exits the loop if the result is the size of a page, thus only going through (page+1)*pageSize loops

No extra arrays, no extra iterations, only some ugly ass code. But what if we could write this as nicely as in the first example and make it work as efficiently as the second? Because of ECMAScript 6 we actually can!

Take a look at this:

const result = Enumerable.from(colors)
  .where(c => c.R > c.G && c.R > c.B)
  //.orderBy(c => c.name)
  .skip(page * pageSize)
  .take(pageSize)
  .select(c => ({
      name: c.name,
      color: `#${hex(c.R)}${hex(c.G)}${hex(c.B)}`
  }))
  .toArray();

What is this Enumerable thing? It's a class I made to encapsulate the methods .where, .skip, .take and .select and will examine it later. Why these names? Because they mirror similar method names in LINQ (Language Integrated Queries from .NET) and because I wanted to clearly separate them from the array methods.

How does it all work? If you look at the "classical" version of the code you see the new for..of loop introduced in ES6. It uses the concept of "iterable" to go through all of the elements it contains. An array is an iterable, but so is a generator function, also an ES6 construct. A generator function is a function that generates values as it is iterated, the advantage being that it doesn't need to hold all of the items in memory (like an array) and any operation that needs doing on the values is done only on the ones requested by code.

Here is what the code above does:

  • it creates an Enumerable wrapper over array (performs no operation, just assignments)
  • it filters by defining a generator function that only returns reddish colors (but performs no operation) and returns an Enumerable wrapper over the function
  • it ignores the items from previous pages by defining a generator function that counts items and only returns items after the specified number (again, no operation) and returns an Enumerable wrapper over the function
  • it then takes a page full of items, stopping immediately after, by defining a generator function that does that (no operation) and returns an Enumerable wrapper over the function
  • it transforms the colors in output items by defining a generator function that iterates existing items and returns the transformed values (no operation) and returns an Enumerable wrapper over the function
  • it iterates the generator function in the current Enumerable and fills an array with the values (all the operations are performed here)

And here is the flow for each item:

  1. .toArray enumerates the generator function of .select
  2. .select enumerates the generator function of .take
  3. .take enumerates the generator function of .skip
  4. .skip enumerates the generator function of .where
  5. .where enumerates the generator function that iterates over the colors array
  6. the first color is red, which is reddish, so .where "yields" it, it passes as the next item in the iteration
  7. the page is 0, let's say, so .skip has nothing to skip, it yields the color
  8. .take still has pageSize items to take, let's assume 20, so it yields the color
  9. .select yields the color transformed for output
  10. .toArray pushes the color in the result
  11. go to 1.

If for some reason you would only need the first item, not the entire page (imagine using a .first method instead of .toArray) only the steps from 1. to 10. would be executed. No extra arrays, no extra filtering, mapping or assigning.

Am I trying too hard to seem smart? Well, imagine that there are three million colors, a third of them are reddish. The first code would create an array of a million items, by iterating and checking all three million colors, then take a page slice from that (another array, however small), then create another array of mapped objects. This code? It is the equivalent of the classical one, but with extreme readability and ease of use.

OK, what is that .orderBy thing that I commented out? It's a possible method that orders items online, as they come, at the moment of execution (so when .toArray is executed). It is too complex for this blog post, but there is a full implementation of Enumerable that I wrote containing everything you will ever need. In that case .orderBy would only order the minimal number of items required to extract the page ((page+1) * pageSize). The implementation can use custom sorting algorithms that take into account .take and .skip operators, just like in LiNQer.

The purpose of this post was to raise awareness on how Javascript evolved and on how we can write code that is both readable AND efficient.

One actually doesn't need an Enumerable wrapper, and can add the methods to the prototype of all generator functions, as well (see LINQ-like functions in JavaScript with deferred execution). As you can see, this was written 5 years ago, and still people "teach" others that .filter and .map are the Javascript equivalents of .Where and .Select from .NET. NO, they are NOT!

The immense advantage for using a dedicated object is that you can store information for each operator and use it in other operators to optimize things even further (like for orderBy). All code is in one place, it can be unit tested and refined to perfection, while the code using it remains the same.

Here is the code for the simplified Enumerable object used for this post:

class Enumerable {
  constructor(generator) {
	this.generator = generator || function* () { };
  }

  static from(arr) {
	return new Enumerable(arr[Symbol.iterator].bind(arr));
  }

  where(condition) {
    const generator = this.generator();
    const gen = function* () {
      let index = 0;
      for (const item of generator) {
        if (condition(item, index)) {
          yield item;
        }
        index++;
      }
    };
    return new Enumerable(gen);
  }

  take(nr) {
    const generator = this.generator();
    const gen = function* () {
      let nrLeft = nr;
      for (const item of generator) {
        if (nrLeft > 0) {
          yield item;
          nrLeft--;
        }
        if (nrLeft <= 0) {
          break;
        }
      }
    };
    return new Enumerable(gen);
  }

  skip(nr) {
    const generator = this.generator();
    const gen = function* () {
      let nrLeft = nr;
      for (const item of generator) {
        if (nrLeft > 0) {
          nrLeft--;
        } else {
          yield item;
        }
      }
    };
    return new Enumerable(gen);
  }

  select(transform) {
    const generator = this.generator();
    const gen = function* () {
      for (const item of generator) {
		yield transform(item);
      }
    };
    return new Enumerable(gen);
  }

  toArray() {
	return Array.from(this.generator());
  }
}

The post is filled with links and for whatever you don't understand from the post, I urge you to search and learn.

I like Dave Farley's video channel about the software industry quality, Continuous Deployment, so I will share this video about how tech interviews should be like. Not a step by step tutorial as much as asking what is the actual purpose of a tech interview and how to get to achieve it:

[youtube:osnOY5zgdMI]

Top Software Engineering Interview Tips - Dave Farley