mardi 11 juillet 2023

Correct design pattern for invalidating cache after service bus event

Let's say I have two applications: Web API, and Web UI. They are both using the same product database. The business case is very read-intensive (via API) with rare writes (via Web UI). Therefore on the API side there exists singleton ProductCatalog service, which holds most of the active parts in memory as object graph and applies business logic rules to serve read requests. When someone use WebUI to make changes in catalog, I want to update/invalidate the cache inside this service. I will use service bus (Azure Service Bus) to propagate this event.

What is the correct design pattern on Web API side to do this?

  • it feels bad for ProductCatalog to implement subscription to service bus
  • it also feels weird to expose some InvalidateCache method on this service to be called by someone else
  • should there be some component to encapsulate service bus subscriber, and expose incoming messages as regular .NET events? Should this component be therefore dependency (injected) of ProductCatalog, so it can subscribe to these events?

Is there some good example of .NET implementation of something like this?

Why are developers leaning towards less performant and very-easy-to-read coding practices?

I've been a programmer for +7 years now, and have been making a living by it for +5 years; throughout my career I haven't ever felt the need to see codes that even a 5 year old can read (which seems to be one of the measurements that modern practices encourage), neither have I even seen that practice executed in action in a whole production project. So, my question from the community, and specifically from the ones encouraging these practices, is 'why is this considered an evolution, and what are the real productive benefits compared to a more traditional approach?'

For better understanding, here's what I'd call a code 'encouraged by modern approach' in C#:

using System;

namespace ModernApproach {
    class Program {
        static void Main() {
            Person person = new ("John", "Doe");
            person.PrintFullName();
        }
    }

    interface IPrintable {
        void Print();
    }

    class Person : IPrintable {
        private readonly string firstName;
        private readonly string lastName;

        public Person(string firstName, string lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public void Print() {
            Console.WriteLine(GetFullName());
        }

        private string GetFullName() {
            return $"{firstName} {lastName}";
        }
    }
}

and a more traditional approach

// Traditional Approach

using System;

namespace TraditionalApproach {
    class Program {
        static void Main() {
            Person person = new {
                FirstName = "John",
                LastName = "Doe"
            };
            person.PrintFullName();
        }
    }

    class Person {
        public required string FirstName;
        public required string LastName;

        public void PrintFullName() {
            Console.WriteLine($"{FirstName} {LastName}");
        }
    }
}

Of course this isn't an ideal example but it was the best I could come up with right now. I hope you get the idea.

Thanks in advance!

lundi 10 juillet 2023

Two-Column Layout with Spanning Header

I want to create a layout for the following html code.

<div>
   Article Header
</div>

<div>
   <div>
      Article Content
   </div>

   <div>
      The Sidebar
   </div>
</div>

There are two columns, and the article header that contains H1 spans across the columns. I thought about wrapping the article's header and content inside an article tag, but is it okay to have the sidebar inside too? Or is there a better way to do that?

How to implement a generic type member of a class?

I have a class CarInfo that holds information of a car and its owner. The owner can be either a known customer (i.e. we can look it up and populate a Customer class) or we only know the name of the customer (in which case we cannot populate a Customer class). I have a Blazor form that exposes the CarInfo class. How do I design this class in respect to the customer info member, which can be either Customer or just First- and last name?

public CarInfo
{
     public Guid Id { get; }
     ...
     public Customer? { get; set; }           // Either this member can be populated
     public string? FirstName { get; set; }   // or the First- and Last name members.
     public string? LastName { get; set; }
     ...
}

What is the best design to handle this? Should I break out Customer and First- and Last name into a new class, e.g. CustomerInfo and handle this polymorphism there?

public CustomerInfo
{
   public Customer? { get; private set; }
   public string? FirstName { get; private set; }
   public string? LastName { get; private set; }

   public CustomerInfo(Customer customer) => Customer = customer;
   public CustomerInfo(string firstName, string lastName)
   {
      FirstName = firstName;
      LastName = lastName;
   }
}

and use it like this?

public CarInfo
{
    public Guid Id { get; }
    ...
    public CustomerInfo { get; set; }           
    ...
}

I'm a little stuck in what best practises or patterns should be referred to here.

dimanche 9 juillet 2023

Can't access protected members in derived class in Decorator pattern implementation

I'm trying to implement the decorator pattern, but my derived/decorator class can't access protected members of it's "decorated" member which is of the base class type. Here's what I mean

#include <iostream>

class A
{
protected:
    void func() { std::cout << "func ran\n"; }
};

class B : public A
{
public:
    void func2() { a->func(); }
    A* a;
};

int main()
{
    A a;
    B b;
    b.a = &a;
    b.func2();
}

This code produces an error saying "func" is protected within this context.

I could add B as a friend of A but I don't wanna have to change the existing code everytime I add something.

Is there an alternative way to do this?

lottiefiles vs SVGs vs GIFs in flutter

FYI (new to flutter and mobile development) I am planning to build a flutter application for kids which may have sounds animations etc .., on production when user installs the app in the mobile , user may see lot of sections with lot of animated pics, so if user downloads all these images/gifs/lotties files it will consume a lot of user memory , so what are best file formats for these kind of applications and is there any other way other like keeping all the images or files in firebase or s3 and download the images while user using the particular section and wipeout once user leaves the section.

can you please suggest some design patterns to handle these kind of applications ?

How to create singleton classes dynamically in python

I want to create classes dynamically such that : class is created as per the "name" provided by the user. This class should be singleton.

I want to implement some sort of messaging functionality where the communication channel (topic) with name "name" should be created only once (singleton), and several observers can be attached to that topic.

I tried to do something like below but not sure how to create singleton classes dynamically.

class GTopic:
    def register(self, observer):
        pass


class TopicA(GTopic):
    instance = None

    class __TopicA:
        def __init__(self):
            self._observers = []
            self.messages = []

        def register(self, observer):
            if observer not in self._observers:
                self._observers.append(observer)

        def send_message(self, msg):
            for observer in self._observers:
                observer.update(__class__.__name__, id(self), msg)
            self.messages.remove(msg)

        def send(self, msg):
            if not msg:
                return
            self.messages.append(msg)
            self.send_message(msg)

    def __new__(cls):
        if not TopicA.instance:
            TopicA.instance = TopicA.__TopicA()
            print("TopicA not present, creating new")
        print("TopicA already present")
        return TopicA.instance


class TopicB(GTopic):
    instance = None

    class __TopicB:
        def __init__(self):
            self._observers = []
            self.messages = []

        def register(self, observer):
            if observer not in self._observers:
                self._observers.append(observer)

        def send_message(self, msg):
            for observer in self._observers:
                observer.update(__class__.__name__, id(self), msg)
            self.messages.remove(msg)

        def send(self, msg):
            if not msg:
                return
            self.messages.append(msg)
            self.send_message(msg)

    def __new__(cls):
        if not TopicB.instance:
            TopicB.instance = TopicB.__TopicB()
            print("TopicB not present, creating new")
        print("TopicB already present")
        return TopicB.instance

"""
def __new__(cls):
    if not cls.instance:
        cls.instance = cls.cls()
        print(f"{cls} not present, creating new")
    print(f"{cls} already present")
    return cls.instance
"""

class GQueue:

    @staticmethod
    def get_topic(topic):
        if topic == "A":
            return TopicA()
        elif topic == "B":
            return TopicB()
        """
        else:
            Topic = type("Topic{}".format(topic), (TopicA,), {"instance": None, "__new__": __new__})
            return Topic()
        """


class Observer:
    def __init__(self, a=0):
        self.a = a

    def update(self, topic_name, topic_id, msg):
        print(f"Message for observer {id(self)} from {topic_name}: {msg}")
        self.a = 1


if __name__ == "__main__":
    # client code
    topic_a = GQueue.get_topic("A")
    topic_b = GQueue.get_topic("B")
    obs1 = Observer()
    obs2 = Observer()
    topic_a.register(obs1)
    topic_b.register(obs1)
    topic_a.register(obs2)
    topic_a.send("hello to A")
    topic_b.send("hello to B")

    # Now I want to do something like :

    """
    topic_x = GQueue.get_topic("X")
    topic_x.register(obs1)
    """

Above code works fine. Now I want to do something like :

    topic_x = GQueue.get_topic("X")
    topic_x.register(obs1)