Sunday, 26 December 2021

Promises and catch

I've recently been working on JavaScript code written by other people where they were using .then()/.catch() chains rathern than async-await magic, and I should not change that, so I've had to review a bit how then()/.catch() works (thanks to async-await I've rarely used them in the last years).

The first point is a reminder about promises rejection in general. When inside .then() we want to reject the promise, should we use Promise.reject(new Error()) or throw new Error()?
Well, it's basically the same. If you do a throw inside a .then or a .catch the .then or .catch will trap the exception and reject the current promise. You can read more about this here.

Both methods produce the exact same response. The .then() handler catches the thrown exception and turns it into a rejected promise automatically.

The second point is that I had almost forgottent that the .then() method accepts a second parameter, a handler function to be called when the promise has been rejected. So, what's the difference between that and chaining a .catch() call? I mean:



getData()
.then(
	data => {/* do whatever */},
	error => {/* treat error */}
);

vs

getData()
.then(data => {/* do whatever */})
.catch(error => {/* treat error */});



Well, the behaviour is almost the same, but there's a subtle difference. If the success handler throws an error, in the first case, that error is not being caught, but in the second case, the .catch, will catch that error. It's well explained here

The next thing is with how many .catch() calls you need. If you have a chain of .then() calls and want to catch any exception in any of them, and apply the same treatment, you need just one .catch() at the end of the call. This means that this code:


async function getProcessedMessage(){
	try{
		let msg = await getMessage();
		msg = await correctOrtography(msg);
		msg = await replaceOddWords(msg);
		msg = await addExtraFormatting(msg);
		return msg;
	}
	catch(error){
		console.log("unable to perform the whole processing");
		return "";
	}
}

is equivalent to this:


function getProcessedMessage(){
	return getMessage()
	.then(correctOrtography)
	.then(replaceOddWords)
	.then(addExtraFormatting)
	.catch(error => {
		console.log("unable to perform the whole processing");
		return "";
	})
}


If what we want is managing exceptions call by call (I mean, differently for different .then() calls), to do some treatment (logging the exception and throwing a "higher level one") or recovering (we replace by a default value and continue with the ensuing calls) then we'll have a .catch() for each .then(). This code:


async function getProcessedMessage(){
	let msg;
	try{
		msg = await getMessage();
	}
	catch(error){
		console.log("failed to retrieve message, we'll use the default");
		msg = "default";
	}
	try {
		msg = await translate(msg);
	}
	catch(error){
		console.log("low level error: " + error.message);
		throw new Error("failed to translate);		
	}
	return msg;
}

is equivalent to this:


function getProcessedMessage(){
	getMessage().
	.catch(error){
		console.log("failed to retrieve message, we'll use the default");
		return "default";
	}
	.then(translate)
	.catch(error){
		console.log("low level error: " + error.message);
		throw new Error("failed to translate);			
	}
}

Thursday, 23 December 2021

FIC Xixón 2019

Since I started this blog, for every edition of the Xixon Internationl Film Festival (FICXixon) during which I was in town, I've done a review of the screenings that I attended to. When starting to write the one for 2021 I've realised that I had missed to complete and publish the one from 2019 (in 2020 due to the pandemic the festival was only online, and I did not watch any film). So well, 2 years late, here it is!

Though in 2019 I was in Xixón during the 9 days of the festival, I only attended 3 films of this 57th edition. After the years that I missed the festival cause I was living abroad I no longer have that urge to attend 1 (or more) films per day, and mainly, I only look into films being screened in Teatro Jovellanos, the main site for the festival. Also, I missed a couple of films cause I did not hurry enough to get the tickets... This said, these are the films I watched

  • Thursday, 2019/11/21, La hija de un Ladrón, Belén Funes, Spain, 2019 A good film. It goes through the life of a young Spanish girl striving to get a life for for her and her little kid. She has not had an easy life, with a missing mother; a father that has spent time in prison, an odd relation with the father of her child... and lives for the moment in a shared flat managed by the Catalan social aid system (she's not part of any 'minority' and does not seem to be into drugs or have committed any crime, so don't expect she'll be considered of particular interest to receive much help from the social system...) The girl is a fighter, doing her best to get and keep a job, and to protect her kid and her little brother. Recorded in a rather realistic style, probably this is not a film that you will particularly remember, but you won't quit it either, and you'll have the feeling of having spent your time correctly.

  • Friday, 2019/11/22, Rounds, by Stephan Komandarev, Boulgarie, Serbie, France, 2019. I think this is the second Bulgarian film that I've watched in my life (at least that I'm aware of) and as my previous Bulgarian experience, this is an excellent work, really excellent. It follows the lives of 3 pairs of Sofia policemen working the night shift, and combines masterfully black humor and dark, brutal events to portrait the harsh reallity that those living in that souther slav country face day after day. You can read more here.

  • Saturday, 2019/11/23, Synonyms, Nadav Lapid, Israel-Germany-France, 2018. An absolute piece of crap. There's nothing in this film that is worth wasting your time in front of it.

Sunday, 28 November 2021

Yield based Trampolines

Some weeks ago I came across this article about using trampoline functions with generators to avoid stack overflows in recursive functions. I've recently written about "classic" trampolines for non tail recursions and about an alternative, using await, so I decided to transport the technique explained in that article to a javascript example.

Let's see first an example of adapting a Tail recursive function to be used with a trampoline function to prevent stack overflows in a runtime lacking of TCO (like node.js). We have a recursive factorial like this:


function recursiveFactorial(n, accumulator) {
    if (n <= 0) return accumulator;

    return recursiveFactorial(n-1, n*accumulator);
}

And we transform it into this:


function trampolineReadyFactorial(n, accumulator){
    if (n <= 0) return accumulator;

    return () => recursiveFactorial(n-1, n*accumulator);
}

To use it with a trampoline that we create with a factory:


function createTrampoline(fn){
    return (...args) => {
        let result = fn(...args);

        while (typeof result === "function")
            result = result();
        return result;
    };
}

let factorialTrampoline = createTrampoline(trampolineReadyFactorial);
console.log("factorialTrampoline: " + factorialTrampoline(50, 1));

Now let's do it differently, let's rewrite the "trampoline enabled" recursive function, using generators as explained in that python article.


//there's no recursion cause invoking the generator function returns a generator object, and the code
//inside the generator function is not executed until we call next() on the returned generator object (iterable/iterator)
function* yieldBasedFactorial(n, accumulator){
    if (n <= 0) 
        yield accumulator;
    else
        yield yieldBasedFactorial(n-1, n*accumulator);
}

So now the "trampoline enabled" function no longer returns a function (containing the "recursive" call), but a generator object (iterable-iterator). Calling next() on that generator object will perform the next "recursive" call). We can create a trampoline for this kind of "trampoline enabled" functions, like this:


function createTrampolineFromYieldBasedFn(yieldBasedFn){
    return (...args) => {
        let genObj = yieldBasedFn(...args);
        let item = genObj.next();
        while (item.value.next !== undefined )
            item = item.value.next();
        return item.value;
    }
}

let yieldBasedFactorialTrampoline = createTrampolineFromYieldBasedFn(yieldBasedFactorial);
let result = yieldBasedFactorialTrampoline(50, 1);
console.log("yield based Trampoline 2: " + result);

The trampoline function looks more complex to me in this case, but one could say that the adapted, recursive-like function, seems more close to the original with that yield. As usual, I've uploaded the code to a gist

Sunday, 21 November 2021

Infinite Sequence and More

It's good that I still find interest in bizarre programming topics :-) I recently came across an article about recursive iterators in javascript. What mainly called my attention was the recursive way to create and endless iterator. The "classical", iterative way is something along these lines:


function* infiniteIterable(iter){
    while (true){
        yield* iter;
    }
} 

The recursive way (I managed to write it myself without looking it on the article, to make sure I understood it) is this:


function* infiniteIterableViaRecursion(iter){
    yield* iter;
    yield* infiniteIterableViaRecursion(iter);
} 

Somehow I also came across this other post with an odd title Eliminate try..catch when using async/await by chaining .catch() clauses. What!? Avoiding the "Promise Hell" of a mass of chained then-catch calls and writing it as sequential code is why we all love async-await, so this seemed senseless. Well, looking into the article he refers to a case for which it makes good sense, when the async call returns a value and even in case of an exception we still want to return a (sort of default) value. So rather than this:


let value;
try {
  value = await db.get('nonexistent'); // throws NotFoundError
} catch {
  value = null;
}

We write this, that is quite more concise:


const value = await db.get('nonexistent').catch(() => null);

Sunday, 14 November 2021

LongChamp Marseille

Recently I've been lucky to spend (again) a few days in Marseille. I find this city mesmerizing, in spite of its massive problems: Le Grand Remplacement (it's not a theory, it's a painful reality in at least 1/2 of the city, where non-muslims have become a clear minority), the huge presence of far-left scum and the islamization and criminality that comes along with both previous issues... Marseille is placed in a privileged natural setting, encircled by mountains and the sea, and with a 150 meters high hill right at its center, from where the magical Notre-Dame de la Garde dominates the whole city. Additionally, I absolutely love its urban landscape, a dense city where the old and the new embrace each other and where high-rise constructions spring up unorderly here and there.

I thought I had already written about Marseille after my initial discovery of this impressive city, but I've just realised that unfortunately I never finished a rather long article that I was writing in August 2014!. All I've published about Marseille is this short post. It's strange that I did not mention in it the incredible place that I'm going to describe now, LongChamps.

LongChamp is a park, a garden and gorgeous palace Palais Longchamp, with a beautiful, imposing and delicate fountain (Chateau d'eau). It's the kind of classic French refinement that maybe you would not expect to find in Marseille, though the city has some other excellent examples of magnificent "so French" architecture, e.g. the Prefecture, the Banque de France and the Caisse d'Epargne buildings (the 3 of them really close). Indeed, my first time there, in 2014, I was almost shocked. After that, it was under renovation for like almost 2 years, and now it looks even better. This renovation included improvements to the lightning of the monument, which reminds me that I have pending to go there one day at night. The main sculpture and the cascade are one of those exquisite pieces of art that make you think about what their creators could feel the day it was complete, to what extend they were aware of the beauty they were gifting us with.

From the wikipedia article I've learnt that the achievement that it celebrates, the construction of the Canal de Marseille is still relevant these days, as it still provides 2/3's of its drinking water to Marseille. This is in contrast with another of the great French construction works of all times, the Canal du Midi, that remains an essential source of visual joy for most Toulousains, but no longer has much practical use.

I've come to profoundly hate French rap, save for some Patriotic acts like Tepa (Repose en Paix, combatant) or Millesime K. but well, there is a clip by Soprano with some nice views of LongChamp (you can just mute the sound).

Monday, 1 November 2021

DbContext Creation

There are several ways to create a DBContext in (modern) .Net and they are explained here. There 2 of them that I normally use. This one, when I'm not using any IoC container:


var connectionstring = "Data Source=blogging.db";

var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
optionsBuilder.UseSqlite(connectionstring);
optionsBuilder.UseLazyLoadingProxies();

BloggingContext dbContext = new BloggingContext(optionsBuilder.Options);

The above is pretty clear. We set several options through a builder object, build the options object and pass it over to the DBContext constructor, so that we get a DBContext fully set with all its options. This is much better than if we wereconstructing the object and then setting options on it, that would allow having a partially initialized (and useless) object.

This other mechanism is used when using the built-in IoC container provided by the .Net Base Class Library:


var connectionstring = "Data Source=blogging.db";
ServiceCollection services = new ServiceCollection();
services.AddDbContextFactory<BloggingContext>( optionsBuilder => {
	optionsBuilder.UseSqlite(connectionstring);
	optionsBuilder.UseLazyLoadingProxies();
});

var provider = services.BuildServiceProvider();

BloggingContext dbContext = provider.GetService<BloggingContext>();


Usually I just copy/paste it from some article or from a previous project and don't pay it much more attention, but it has always seemed a bit odd to me, so I've been reflecting a bit on it. We register in the IoC container our DbContext, providing a callback function that configures the DbContextOptionsBuilder and will be invoked when the Container instanciates the DbContext. This callback is not a factory, as it does not create the DbContext, it helps to configure it. This technique is possible becaue the built-in container has "extra knowledge" about DbContexts. I could think of 2 different ways to create the DbContext through the container that look a bit more natural to me.

1. Almost any IoC container allows registering parameters to pass to a constructor. For example in Autofac we can register constant values or register a factory function that is invoked by the container to create the non constant parameter each time it needs to provide the service. We would need that for our case with the DbContextOptions. I think the built-in .Net container does not support this.

2. Registering a Factory that creates a new DbContext each time the IoC container needs one. Indeed we can do that with the built-in container:


            var connectionstring = "Data Source=blogging.db";
            ServiceCollection services = new ServiceCollection();
            
            services.AddTransient<BloggingContext>(s => {
                var optionsBuilder = new DbContextOptionsBuilder<BloggingContext>();
                optionsBuilder.UseSqlite(connectionstring);
                optionsBuilder.UseLazyLoadingProxies();
                return new BloggingContext(optionsBuilder.Options);
            });
            var provider = services.BuildServiceProvider();
            return provider.GetService<BloggingContext>();

I think this seems more natural to me as it's a generic technique that I'm more accustomed to use with other containers and for different object types, but it's slightly more verbose than the specific technique featured by the built-in container.

Saturday, 16 October 2021

Method References

I've been recently reading about method references in Java, particularly interested in whether invokedynamic is also used with them (as it happens with lambdas). The answer is yes and as you can read in that document the main difference is that for lambdas the Java compiler needs to "desugar" the lambda into a private method, which is obviously unnecessary for method references.

When the compiler encounters a lambda expression, it first lowers (desugars) the lambda body into a method whose argument list and return type match that of the lambda expression, possibly with some additional arguments (for values captured from the lexical scope, if any.) At the point at which the lambda expression would be captured, it generates an invokedynamic call site, which, when invoked, returns an instance of the functional interface to which the lambda is being converted. This call site is called the lambda factory for a given lambda. The dynamic arguments to the lambda factory are the values captured from the lexical scope. The bootstrap method of the lambda factory is a standardized method in the Java language runtime library, called the lambda metafactory. The static bootstrap arguments capture information known about the lambda at compile time (the functional interface to which it will be converted, a method handle for the desugared lambda body, information about whether the SAM type is serializable, etc.)

Method references are treated the same way as lambda expressions, except that most method references do not need to be desugared into a new method; we can simply load a constant method handle for the referenced method and pass that to the metafactory.

This other article gives a deeply interesting explanation of how lambdas and invokedynamic works.

Regarding method references (do not confuse them with the related, low level Method Handles), this article explains them pretty well. As I expected you can get a method reference to an instance method that gets its "this" value ("receiver object" in the article) bound to that instance, and you can get method references to static methods. The not so obvious thing is that you can get references to instance methods that are not bound to a "this" value ("References to unbound non-static methods" in the article). They'll use as "this/receiver object" the first parameter received when being invoked. That's pretty nice, as you can reuse the same method reference object with different receivers.

This has made me think about how delegates work in .Net, I could remember that we have something very similar, about which I wrote in one of my first posts. We call that Open Instance Delegates, but their creation is rather less friendly than in Java, so they remain as a not particularly well known feature. As a reminder:


MethodInfo mInf = typeof(Person).GetMethod("DoSomethingInstance");
  Func openDelegate = (Func)(Delegate.CreateDelegate(typeof(Func), mInf));
  //now let's call our Open Delegate with different instances of Person
  Console.WriteLine(openDelegate(p1,"formatting: ", 3));
  Console.WriteLine(openDelegate(new Person(){Name = "Xurde"},"formatting: ", 4));
  Console.WriteLine(openDelegate(new Person(){Name = "Nel"},"formatting: ", 2));


Another nice feature of Java Method references is that we can have references to constructors, using this syntax: ClassName::new. This is not possible in C#, I think because the CLR does not allow binding delegates to ConstructorInfo objects, only to MethodInfo objects. This is not a big deal, because we can just create a lambda that invokes the constructor: () => MyConstructor(), but anyway, it's nice that Java allows to directly reference the constructor.

In my old post I've seen that C# delegates provide also Close Static Delegates, that is a delegate pointing to a static method and where the delegate Target ("this") is bound to a value that will be passed as the first parameter to the static method. I still can not see much use for this, but well, just another feature.