Autor: Dani Barca

  • Callbacks vs async code for events

    I’ve never been totally convinced about callbacks. They are extremely powerful but kinda mess everything up. Whenever I deal with code that uses them, it never feels like the «right» thing to use for the task.

    Once you’ve set up a callback, the class that contains the callback method loses control of when it is called. Yes, we’ve supposedly configured an event that is called once something specific happens, but we rely on some other piece of code to properly understand and handle when that’s supposed to happen.

    Also, there is no visual connection in the code between what triggers the call and the call itself. We subscribe to an event and somewhere else define the callback itself. Whoever comes after us needs to go back and forth around the code and make the proper mental connections to understand what’s going on.

    On the other hand, I find asynchronous code a lot more idiomatic. Let’s take a look at the following example that I’m just making up as I write:

    // Using event callbacks
    public void Setup(){
        NetworkManager.Instance.OnChatMessageSent += OnChatMessageSent;
    }
    
    private void OnDestroy(){
        NetworkManager.Instance.OnChatMessageSent -= OnChatMessageSent;
    }
    
    ………
    
    private void OnChatMessageSent(MessageData message){
        … // Handle chat UI
    }
    
    //-------------------------
    //-------------------------
    
    // Using UniTask
    public void Setup(){
        HandleChatEvents().Forget();
    }
    
    …
    
    public async UniTaskVoid HandleChatEvents(){
        while(this != null && NetworkManager.Instance != null){
            MessageData message = await NetworkManager.Instance.OnChatMessageSentTCS;
    
            … // Handle chat UI
        }
    }

    Although the 2 approaches are very close, I think it’s immediately clear for anyone familiar with async code, what the 2nd implementation is doing. I like how explicitly we declare to be waiting for something to happen.

    The two ideas at play here are very different mental models:

    • I set up a method and someone, at some moment, will call it. I send a token (a callback) and expect someone to properly handle it.
    • I «await» for something specific to happen, halting the execution until that condition is met. It’s perfectly clear what I am waiting for and the before-during-after sequence is easy to follow because it’s perfectly sequential in the code itself. In this case I retrieve (instead of sending) a token (a task) and I am in charge of what to do with it.

    As an added benefit, here NetworkManager doesn’t need to care at all about who’s subscribed to the event, and we don’t need to care about unsubscribing at all. NetworkManager will just resolve its TaskCompletionSource without caring about who’s listening.

    I believe this approach makes code easier to follow and mistakes much more unlikely. I know some developers will be hesitant to use asyncronous code like this, but I have yet to find a good reason not to use it.

    The only downside I found versus a callback is memory allocation, since a task will need to be realocated after every resolution. Its memory impact is low, though, so it should not be a problem unless the events are happening extremely often.

    For those who might not be familiar with TaskCompletionSource: it allows us to create a sort of «token» that can be awaited from asyncronous code, but remains inert until some other piece of code «resolves» it. The most common use-case for TaskCompletionSource is actually to make callback legacy code awaitable, for example:

    // Before - classic (basic) example of callback hell
    public void Setup(){
        Login(success => {
           …… // Handle login status in a nested lambda function
        });
    }
    
    private void Login(Action<bool> callback)
    {
        NetworkManager.Instance.Login(result => {
            switch(result)
            {
                case NetworkManager.LoginStatus.Success:
                    callback?.Invoke(true);
                    break;
                case NetworkManager.LoginStatus.Canceled:
                case NetworkManager.LoginStatus.Failed:
                    Debug.LogError($"Login failed with status {result}");
                    callback?.Invoke(false);
                    break;
            }
        });
    }
    
    // After - we can't change NetworkManager's API but we can break callback hell using a TCS
    public async UniTaskVoid Setup(){
        var success = await Login();
        …… // Handle login status in a subsequent line after awaiting
    }
    
    // Note Login does not need to be async itself because it's not awaiting anything
    private UniTask<bool> Login()
    {
        UniTaskCompletionSource<bool> tcs = new UniTaskCompletionSource<bool>();
        NetworkManager.Instance.Login(result => {
            switch(result)
            {
                case NetworkManager.LoginStatus.Success:
                    tcs.TrySetResult(true);
                    break;
                case NetworkManager.LoginStatus.Canceled:
                case NetworkManager.LoginStatus.Failed:
                    Debug.LogError($"Login failed with status {result}");
                    tcs.TrySetResult(false);
                    break;
            }
        });
    
        return tcs.Task;
    }
    

    Here, NetworkManager is supposed to be out of reach, either because we don’t want to mess with it or because its API is out of our jurisdiction. TaskCompletionSource, though, allows us to handle it like a task and thus stop nesting callbacks.

    Unlocking asyncronous thinking as a programmer can make our code a lot cleaner and easier to understand, specially in interactive applications like videogames.

  • How internet search is changing forever

    Google used to be great. At any time, you were just a few taps away from the answer to any question you can imagine.

    For the last few years, though, Google has become increasingly enshittified. Trying to solve a problem using Google leads to a collection of bullshit articles written automatically by bots and AI.

    When I started interacting with those sites, I thought Google would very shortly bury them in the search results. But for some incomprehensible reason that’s not happened. Only Google knows why they have decided to let their primary product in a state of slow decay. For the last couple years searching has become useless. I find myself appending «Reddit» (or any other specific reputable site) to all my searches if I had any hopes of finding useful information.

    So the solution to a technology that fills the internet with bullshit is another technology capable of filtering it out. In that context I discovered Perplexity.

    Perplexity is what happens when you let ChatGPT search on the internet. Instead of spitting random words that may or may not be true, Perplexity analyzes the question you give them and bases the answer on search results coming from that question.

    The result is an answer that includes references and links to the information it’s based on. It’s able to give reasoned answers like the ones you’d get from ChatGPT, but also give you some confidence on the credibility of its answers, or at least the opportunity to contrast them.

    After a few weeks, I found myself slowly replacing the «thought» of searching something on Google with the one of looking it up on Perplexity. And as a tech-avid user that’s been using Google daily for decades, that’s saying a lot.

    After failing to find what I’m looking for from Google, getting it in a few seconds from Perplexity is mind-bending. And at some point I will just not bother trying with Google anymore.

  • A month on Semaglutide (Wegovy)

    A month on Semaglutide (Wegovy)

    NOTE for readers: I am not a health professional. Everything I write here are the experiences of a normal human being, and shouldn’t be taken seriously as suggestions or diagnostics without consulting with your doctor.

    Being overweight has always been one of my main life struggles. I’ve never been severely obese, but its shadow has followed me since my teenage years. For a few years during the late 2010’s I was able to overcome it, but I slowly crawled back to being overweight until now.

    I’m really tall, at 194 cm, so at least I don’t get a lot of the shame of overweight. Most people are surprised to learn that I’m actually slightly obese (at ~114kg) because my height kind of compensates for it.

    Also, weight used to be a big deal during my 20s, but now that I’m married and have a kid, I don’t feel the need to impress anyone. My only reasons for wanting to lose weight are purely health and, maybe, feeling better with myself.

    Since I know many others are in this same journey or trying to learn more about it, I wanted to share some thoughts and experiences about this.

    Is taking a med to lose weight ok?

    So my first concern about this is, should I want this? Is this the right way to lose weight, or am I cheating? I think first of all you should ask yourself if you need it.

    I believe that if you go to your doctor just to ask them if they can give you Wegovy you’re starting with the wrong mindset. You know perfectly why you want to talk directly about a med: it’s not the first suggestion your doctor will give you after learning about your problems.

    You can’t just go to your doctor and give them a diagnostic and a treatment. That’s not how it works: you go to your doctor to talk about your issues, and then you get a set of suggestions that, normally, you don’t like at all. You already suspect most of what the doctor will tell you. You will have to do all of that EVEN IF YOU TAKE MEDS, and specially AFTER you achieve your objectives, so you don’t immediately throw your progress away. Those lifestyle changes are forever and if you’re going to medicate yourself you better not waste this shot.

    After some years of back and forth with my doctor, she suggested me to try meds. The health motives behind this suggestion were a metabolism that had a serious risk of becoming diabetes in the long run, and a liver that was fatty and would also pose a risk in the long run. So weight is actually not the main reason for me to get serious with health, but it’s heavily linked to it.

    All the serious health issues I have are completely reversible, and I can undo the damage with a change in lifestyle and some lost weight. So if I’m serious about it, why take the meds at all? I think it’s like an insurance, or a warranty. I don’t have the best track record in losing weight and getting serious with my health, so I’m not going to bet all of it onto my sheer willpower if I have an alternative. Wegovy provides me a much higher chance of success: if I failed, the next time I might not have the opportunity to fully revert my situation.

    It’s also a medicine that interacts with the liver in ways that I don’t understand at all, so it’s not just about the weight, there are other medical reasons to take it.

    I know it’s not the socially acceptable and «pretty» way to fix all of my problems, but I have the rest of my life to do all the right things, my priority right now is to get out of risk and I’ll use any tool available for it (as long as it’s prescribed and recommended by a doctor, of course)

    How does Wegovy feel?

    After getting my first shot I was kinda expecting to feel something, but I just didn’t. Besides the slight discomfort of the needle, there’s no immediate feeling.

    During the first 24h I felt nothing at all. After that time, I started feeling slight nauseous. I actually had a family gathering that day, so I would have usually eaten heavily that day, but found myself unable to eat more than a standard serving. I was full.

    So that’s it, that’s how Wegovy feels: you’re full. All the time. The following days the sensation became stronger and at some moments I was almost unable to eat even after many hours of fasting. On the worst days it’s like trying to eat something after a Christmas meal: you try to eat but feel the food going up your throat. Even though there’s no food at all in this case.

    Your body adapts quickly to it and soon it becomes more like a regulator. You start eating normal sized meals and feeling full after it.

    That’s why I think this med actually helps with habit forming. The first weeks, whenever I saw a massive plate my head said «I can eat this» because I would usually be completely able to take it all in and then go for another round. Now, I feel like my mind is slowly having to re-learn what’s a normal sized meal, and not desiring to keep eating even if there’s more food available.

    I don’t know what will happen when I drop the medicine but I’m sure food is not going to look the same as it did before. At that moment, I will have to be careful not to do the same mistakes again, but I will have somewhere to start from.

    Did it have side-effects?

    Besides some nausea for the first days, I’m not sure if I can call my other «effects» a direct side-effect of Wegovy.

    Apparently, amongst many other things semaglutide does two important things: decreases your body’s secretion of glucose, and increases your body’s secretion of insulin. Take that, and also lack and of hunger (i.e. you don’t eat as much as before), and you get hypoglycemia.

    When you have a large meal your body compensates producing lots of insulin to lower your blood sugar. If the meal is REALLY large, your body overcompensates for it and causes what’s commonly known as a «sugar crash», causing hypoglycemia.

    I had two different issues that lead to the same situation. I’m used to eat whenever I feel like it, which is just often enough for me to replenish all the nutrients needed in my body. But now I can spend full days almost not eating.

    So I started feeling very tired without an explanation. It was progressive and not bad enough to worry about it, but I was getting consistently tired. I didn’t really know where it came from.

    And then I went on vacation for a weekend and had a big breakfast one day. It wasn’t even big for what I used to eat, but it was huge for my new «standards». Two hours later I was absolutely wasted. That same feeling from the previous days but much much worse, and with new symptoms like headache, heart palpitations, and slight cold and tremors.

    To make matters worse, I was completely full from such a big breakfast, so eating was not in my top-40 priorities. After a visit to the ER everything made sense. It was something that never happened to me before: I had low blood sugar.

    I learned two important things that day: how low blood sugar feels, and that I can’t just eat mindlessly whenever I feel like it. I need to consciously mind what I eat and what I don’t eat.

    Takeaways

    My takeaway is that Wegovy is not only helping change my mind about how much I can eat, it’s also forcing me deeply think about it. And this would have been much harder to learn without this med. After this experience I realised what I eat has a direct impact on how I feel for the next few hours, or even days.

    I found myself taking care of my carbs and iron intakes in a way that I had never before, and now I think I feel even better (less tired) than before starting, when I ate as much as I wanted. That’s something I will forever be taking an eye on: even if I fail miserably in my journey, whenever I feel tired this experience will come to my mind.

    I’ve lost 4kg during this month, and my doctor has decided to stay on the same dosage for the 2nd month, mainly because we want to keep an eye on those sugar levels and make sure I am stable before going up, and also because you don’t take the dose up unnecessarily if it’s giving the desired effect as is.

    Losing weight consistently is also extremely helpful to implement all the lifestyle changes that are needed. If you’re reading this, you probably know how it feels to do «all the right things» for a month just to find you weight more than when you started.

    I think providing a consistent sense of progress is really helpful, and the fact that going «wrong» has consequences (like in my bad breakfast example) also helps equalize temptations out. Now I know I can indulge, but indulging big is just not an option, and it’s important for me to learn that. Without the consequences it would have taken me much longer to realize this.

  • A week in a children’s hospital (Sant Joan de Deu, Barcelona)

    Sant Joan de Deu’s main hall, source: BCN3D

    There is nothing more terrifying than your kid getting hurt. Of course I knew this already, but we are going through this horrifying experience at this very moment. I don’t want to go into much detail about why, but whoever’s wondering about it, just needs to know that our kid is stable and out of danger, he will be alright soon.

    I am writing from one of the hall spaces in the Sant Joan de Deu hospital, in Barcelona. Sant Joan de Deu (SJD) is by far the most impressive hospital I’ve ever been in. It’s the closest a hospital can get to a Theme Park, and that really makes a huge difference when it’s about kids.

    For a series of unrelated reasons I’ve had the chance of visiting several public hospitals in Barcelona during the last couple years, and have witnessed the impressive infrastructure we enjoy in this city. SJD, as impressive as it is, is just a tad better than some of the other public healthcare alternatives around here.

    So my first take about this whole experience is how grateful I am for me and my family enjoying Spanish healthcare. I see it often dismissed as too expensive regarding taxes, but trust me: as high as taxes are, if you only use public healthcare once in your life (that one time when it really matters) you’ve already saved a ton of money on healthcare.

    In Spain, my notion regarding healthcare is as follows: you should (if you can) get a private insurance for unimportant stuff, and use public healthcare for serious matters. We actually enjoy much lower private insurance prices thanks to public healthcare: private healthcare supports itself on public healthcare for certain matters, allowing companies to offer lower prices.

    We don’t really need private healthcare at all, but use it for most stuff because it offers much better wait times when you need small checks, consultations and tests, but even though we have the best and most expensive possible private insurance available for our kid, as we rushed to the hospital we soon realized SJD was the one place where he would get the best medical attention. And I think we were right.

    During the last 3 days we’ve spent in here, I am deeply shocked by what I’ve seen here. I realized SJD is not just a hospital: it’s a place that holds people in the worst moment of their life.

    Being a parent made me realize of how innocent children are. They just don’t deserve any kind of suffering, and seeing them, hearing them through the corridors, is extremely painful. During the night you keep hearing kids screaming and crying, so scared, confused, in pain. You also see their parents worried, hoping for the best. It’s absolutely heartbreaking.

    I’ve seen kids play in the game areas with a smile, while their parents follow them holding medical apparel. The elevators have colorful screens or star patterns in their ceilings so when children enter on a gurney they can see them. The emergency corridors are full of constellation patterns with lights. There’s little experiences everywhere and it matters so, so much.

    At some point we heard a big clapping and celebration noise on our corridor, and looking at what’s up, I saw a group of nurses and doctors celebrating how one of the kids who was spending a long time in there left the hospital, healed.

    I also saw a really young couple mourn the loss of their firstborn. It sounded like something they were expecting, because they were not in shock, and I cannot begin to imagine all the pain they have been through and still are. They were being attended by a nurse specialized in mourning fathers.

    Without being here, it’s impossible to realize the amount of people that are suffering inside. For all these people I realized how the hospital makes things better for them, and how much every little detail matters.

    To say that I am deeply impacted would be an understatement. We decided that whenever this is all over we’re going to donate as much as we can to the hospital, and I’m writing this hoping to make more people aware of the amazing work that is being done here.

  • Marrying a company

    On 2015 I was really happy to move all my photos library onto Google Photos.

    Google Photos was perfect, and it’s still probably the best cloud photo library out there. It has a great timeline, excellent album and classification features, as well as sharing capabilities.

    The problem? Because of how Google’s business model is set up, they will do everything in their hand to keep you from leaving their service. It makes sense for them to make their product as good as possible so you don’t feel the temptation of leaving, but at some point Google implemented some practices that made me feel uneasy having my photos in their service.

    First of all, they make it as unintuitive as possible to download your photo library. To do so, you need to access an obscure configuration site in your Google account that lets you download all your data, select only photographies, and select a few options about the download that only tech-savvy people will understand.

    After downloading my pictures, I realized that Google has literally no option letting users delete their pictures automatically. The only alternative is to select them one by one, or go nuclear and delete the whole account (something that they well know nobody will do, since it’s tied to their email service as well). If downloading pics is for tech-savvy people, deleting them is out of reach for anyone without a notion about programming: I had to use a Javascript script that would automatically select all images and delete them, and disable CSS rendering to make the process quicker.

    It’s clear to me that Google wants you to marry them. Not only that, they want to be like an abusive husband: leaving you no other option than to stay with them.

    If I have to marry a company, I want it to be like my wife, who makes sure I have as much freedom as possible, so as I will stay with her because of how much I love her and how much I get from our relationship.

    During the last few years, I find myself giving lots of thought into what companies I choose for things that matter. I pay lots of attention into businesses that include an exit plan, not only easing how you start using their products, but also how you stop doing so.

    For example, I chose Bitwarden as my password manager and plan to keep my subscription for two reasons: their product is built onto open source software, so if they decide to just shut their business, there’s a good chance someone else will come and keep the service going. And second, they have really straightforward export capabilities that let me do periodic backups of my password library and will allow me to go somewhere else if for some reason I’m not happy anymore.

    I also chose to host my own cloud using a Synology NAS, where I keep my current collection. They might stop providing support and updates to my device one day, but as long as the NAS is running its software and the services that come bundled will keep working as expected. My pictures are just in a folder that I can just drag-and-drop into another service if I want, and with a second device for backups (in a different location) it’s, although expensive, just as safe as Google One.

    In the future I will continue to choose freedom and stability over convenience, even if that means paying a higher price.

  • Writing a lot isn’t enough, but not writing is worse

    I recently came across an article from a guy who has very interesting thoughts about how to generate a skill. He’s specifically concerned about how to become better at writing, and explains how lots of writing is not enough to become a good writer.

    This is something I’ve struggled with too. I’ve been a blogger for many years, but always oscillate between writing a lot and not writing at all.

    Let’s think for a second about the mind of someone who writes a blog. They don’t think about money (blogging rarely becomes a serious business), they don’t do it to sell anything. They just think they have something inside and want to throw it at the world. Blogging is an act of ego, it’s about what one thinks of himself, and as such, it must be perfect.

    A blogger cares a lot about what others think of them, which is exactly how one becomes a perfectionist. As a perfectionist, writing is an uphill battle: bloggers end up spending many hours on a single article, most of which is just reviewing and editing.

    In his article, my blogger makes really good points about how you can’t just write an article and thoughtlessly publish it. Our mind has different levels of focus, and keeps working on a task even while we are not actively doing it (this is 100% true by the way), so he suggests to let articles «marinate» before publishing them.

    I agree with these ideas, but I think it’s counterproductive for someone who still in the habit forming phase. Caring too much about how good an article is will make us dread writing it, and thus kill any chance of forming an habit to write.

    Unless you really want to be a professional writer, I think blogging must be, first of all, for ourselves. A self-care act, even. Perfectionism is how you end up dreading the task: just thinking about the things I need to get right to publish a really good article makes me not want to write ever again. And it’s absolutely impossible to create a habit if you start by dreading the very same habit you’re trying to create.

    To me, the whole idea of «letting articles marinate», is also a perfect recipe for failure. At least at the beggining. If you really want your articles to be better the first step to improve is to avoid dreading the task. Just write, forget if it’s good or bad, it will become better with time.

    As we keep growing, we will start structuring the text better, making less mistakes, and improving. We might also start spending more time on each article if we grow an audience, it’s much easier to spend time on it if we know there’s people who care about and are waiting for it.

  • Coffee as how hobbies should be

    I’ve been a coffee nerd for some time already. Year after year I keep getting deeper into it, at this point it’s some kind of long-term hobby of mine.

    Coffee is a slow hobby for me. In one hand, it’s a basic part of my day: I have not spent more than 48h without it for many years, so I’m pretty used to the process of making coffee and sometime don’t even put much thought into it. On the other hand, it’s a vast subject that no one can ever fully master, no matter how much time you put into it.

    This, combined with my inclination to brief bursts of obsessive fascination with various topics, makes me periodically come and go to this world.

    At my bottom, I just make sure to buy good (great) quality coffee and to keep a reasonable routine that keeps my quality requirements. At my top, I start reading about it, watching videos, buying new apparel, thinking about how to improve my coffee and what the next steps are to some day, get better from this world.

    This is not the best approach if one really wants to get the most out of it, but in my opinion this is how healthy hobbies should be: something we really enjoy whenever we feel like it, and that we can keep on a side from time to time and just admire from a distance.

    At some point, I might decide that one of my interests is worth more than that, and that’s the right moment to make a commitment and get deeper into it. It’s important to choose such commitment carefully when one has diverse interests: there’s a limited amount of energy one can spend and we can’t possibly go in-depth into everything.

  • Happy birthday to me

    Today is my 31st birthday. I thought it might be a good time to reflect on what’s basically the craziest year of my life, and the one with the most changes.

    During 2022, at age 29, I made a decision that would resonate a year and a half later and make my 2023 a lot more exciting. I asked the woman of my life, Carla, to marry me. This decision made lots of sense to me since she was not only the woman who had decided to tolerate my quirks, she’s also the most caring and incredible woman that I could ever dream of, and a life without her would be a void life. Those who have the luck of deserving her love know that there is not much more valuable than that.

    Despite all the wedding planning, 2022 was a pretty quiet year in retrospective. The few months before the wedding have been the most intense of my life. Organizing a wedding is no joke, and certainly something I would never go through for a second time, but thanks to Carla’s insane event planning skills, it was 100% worth it and a wedding that none of guests will ever forget.

    The first few months of 2023 have been crazy for a second reason: in May 2023 I was able to publish my first game ever. It’s a project I’m extremely proud of, and represents a milestone in my career. I feel like it’s the first really sensible project in my curriculum, and the first that I helped build from the ground up.

    Of course the few weeks before a release date are really intense, and seeing the users react and enjoy the game (and also shit on it from time to time) is pretty surreal.

    This last few months of 2023 hint at 2024 being even crazier: Carla and I are expecting a child. It’s a boy and he’ll come to our lifes around April. We’re getting ready for what’s probably the greatest event in our lifes and it feels quite surreal. We even got a car, not just any car but a «daddy car», bought with a family in mind and getting us officially in the adult world.

  • First dive into car tech

    My wife and I took the chance to upgrade our old Chevrolet Spark to a newer Volkswagen T-Roc. This is a huge bump up for us. We needed a bigger car now that we’re heading into adulthood and starting a family. Technology and safety features were also a big factor in our decision making. We didn’t plan to get such a good car, but turns out my 194cm of height can’t really get comfortable in any car, not even models we thought were big.

    As a tech enthusiast, this is not quite the high-tech jump I would’ve dreamt of (I’m really looking forward to trying EVs and self-driving capabilities) but nonetheless we found ourselves light years from where we started.

    Our new car is much safer than our previous one, full of features like lane detection, adaptive cruise control (which is almost like magic), automated parking assistant, fatigue detection… It has automatic gear switching (which is not a common feature in Spain), and it’s also comforting to drive a newer and up-to-date car (I was worrying our luck with the previous one could run out at any moment).

    In hindsight, I feel like a bigger jump could have made me feel a bit overwhelmed. This setup has already taking lots of getting used to as it is. Watching the wheel turn itself automatically (for the park assist) can be very stressful at first, so I can only imagine what it’s like to see it while going 120km/h in the highway.

    I’m really looking forward for the next step in a few years, but I’m pretty sure this is the appropriate one at the current moment and context, the one that feels «right». The next move will be much easier now that we’re already on a higher tier of quality and tech.