jeudi 31 août 2023

Why is this code not in a singleton pattern?

According to the design rules, a singleton pattern must exist in an instance. If I remove the line of code and return an object, will the function be a single pattern?

const singleton = (function(){
    
    let instance, 
         counter = 0;
    
    const createInstance = () => ({
        getCounter: () => counter,
        addCounter: (num) => counter += num,
    })
    
    
    return {                                    
        getInsctance: () => createInstance()  //  insctance || (insctance = createInsctance())  ????
    } 
    
})()


const r = singleton.getInsctance()
const r2 = singleton.getInsctance()

r.addCounter(12) 
r2.addCounter(32) 

singleton.counter = 100 

console.log(r2.getCounter()) // 44
console.log(r.getCounter())  // 44

Why is this feature not singleton pattern?

How to put my div three and div four in the second row of flexbox container? [closed]

I am doing theodinproject project and i want my main div which is flex-container to contain all the elements there are but i want my div three and div four to get on the next row i mean below div one and div two. But i dont know how i can achieve this. I am sharing my code.enter image description hereenter image description here

I tried adding flex-basis to third and fourth div but nothing happened.

mercredi 30 août 2023

What's the Most Effective Approach for Clearing Specific Browser Local Storage in a ReactJS App? Socket Connections or Message Queue?

I have a ReactJs based on some particular situation I want all the clients must clear some specific part of their browser's local storage. I am not able to find the optimal approach. Should I go for sockets but it will make millions of connections or should I use a message queue?

Managing Different Response Structures and Database When Integrating Multiple E-commerce Platforms

I'm currently working on a project that involves integrating with various e-commerce platforms such as Etsy, Amazon, eBay, and Wayfair. These platforms offer functionalities like product listing, updating, invoicing, image uploading, and order retrieval. However, the challenge arises from the distinct response structures presented by each platform's APIs.

While the core operations across these platforms are similar, the APIs return responses in notably different formats. The diversity in response structures complicates the integration process. I'm seeking advice on how to efficiently handle these varying response structures while ensuring a clean and well-organized codebase in C#.

Moreover, I'd appreciate insights on how to manage the database schema for such an integration. Should I store all the platform-specific variables together or maintain separate product tables for each platform? How do I design the database to accommodate the unique attributes and requirements of each platform?

If any of you have faced similar challenges, I would greatly appreciate your insights and recommendations. Specifically, I'm interested in strategies to streamline the integration across multiple e-commerce platforms while adapting to their unique response structures. Additionally, I'm seeking guidance on the most effective database schema design to handle the diverse data coming from these platforms.

Thank you so much for your time and assistance in advance!

How to handle authentication (with registration) with custom user fields, relations, images in microservice architecture?

I'm new to microservices. Always used monolith frameworks.

I don't quite understand how to implement in microservices architecture for this sample project:

Client Application (SPA)

Backend

  • Users with different access (user, admin)
  • Quizzes (with quiz-sessions for each user.)
  • Gifts (for successfully completing quiz or questionary)
  • Images for quizzes
  • Images for gifts

I am planning on using API Gateway pattern for all requests from client side to be checked for authentication.

I kind of understand that API Gateway can generate JWT Tokens or similar and give them back to client side. Also API Gateway will store routes which require authentication and pass requests through only on authentication being successful.

I don't understand how to connect users microservice here. If I understand correctly - microservices are designed not only for decoupling but also for being reusable components (at least my main wish to create reusable microservices).

So API Gateway can be aware of user microservice and create users for registration there.

But what about sending emails for confirmation? How can this be done here? I assume I can create email sender microservice, and API Gateway will be aware of it as well.

But when business logic dictates to add additional field to users, except fields like email, name, phone etc. For example age, occupation, height etc? Wouldn't it make users microservice contaminated with custom business logic?

And after all that, I wonder how can I make relations between users and quizzes and gifts?

I intend to use docker and each stateful microservice to have it's own separate database (each microservice - separate docker compose files). Again, for reusing microservices after in different projects.

And how to store images? In what microservice precisely?

How should I go about making a list of items with subtly different behavior?

I'm starting work on a new project, based on a node editor workflow. I'm using WPF, with Nodify as the central driver. That forces an MVVM model, but I'm planning on adding a computation layer entirely separate from that, because I want to abstract away some of the details that are relevant to the visual representation (such as the position or amount of connectors a node has). It will have about 30 types of nodes, with similar behavior in terms of user interaction but with different parameters. And I've come to a dilemma: how do I organize that? I've come up with a few different solutions, but I'm not really sold on any of them and I'm open to other ideas.

  1. Spend a few hours working on a modular plugin system, and build each node type as a separate .dll file that later gets loaded dynamically. This has the advantage that one file can contain both classes relevant to the frontend (such as their ViewModel) and to the backend logic. However, this complicates the file structure and requires a dynamic loader. And there won't be a need for user-defined nodes, nor do I think that there will be enough changes in the future to benefit from smaller updates.
  2. Create a directory with a file per node type, that includes both presentation and logic code, and then manually make a list of them where it's relevant. This has the benefit of a straightforward implementation, but adding any new types will require changes in at least two places and sounds like a nightmare to maintain.
  3. Try to squeeze the logic as a part of the MVVM model. I'm not sure how I would go about doing this, as it requires stripping away some information and adding information that will not be stored anywhere persistently, and will be destroyed after the computation ends. This leads me to think that there is no place in MVVM to store it. And the analysis performed on the graph resulting from the transforms will require access to data from all nodes, as nodes won't be able to do the required calculations by themselves.

This doesn't seem like an uncommon issue, so I assume there is a design pattern already for it, but wording this issue has proven to be difficult enough to discourage me from looking for one.

what does it mean Define the Normal Flow in clean code book?

I am reading clean code which is written by Robert C. Martin in the 7 section about error handling There is a piece of code that I could not understand it.

try {
 MealExpenses expenses = expenseReportDAO.getMeals(employee.getID());
 m_total += expenses.getTotal();
} catch(MealExpensesNotFound e) {
 m_total += getMealPerDiem();
}

what does it mean? and it is written that we need to refactor it via special case pattern like the following:

public class PerDiemMealExpenses implements MealExpenses {
 public int getTotal() {
 // return the per diem default
 }
}

Can you translate it in a simple way for me? thank you in advance.

mardi 29 août 2023

I noticed that the `new` keyword is not used when creating the reference to the instance. Here's the code snippet:

public class SingletonExample { private static SingletonExample instance;

private SingletonExample() {
    // Private constructor
    System.out.println("SingletonExample instance created.");
}

public static SingletonExample getInstance() {
    if (instance == null) {
        instance = new SingletonExample();
    }
    return instance;
}

public void displayMessage() {
    System.out.println("Hello from SingletonExample!");
}

public static void main(String[] args) {
    // This won't work : SingletonExample instance = new SingletonExample();

    // Getting an instance of SingletonExample using getInstance() method
   SingletonExample singleton = SingletonExample.getInstance();
    singleton.displayMessage();
    
}

}

I expected that creating a new instance of a class would involve using the new keyword, but it appears that the getInstance() method handles this without it. I'm looking for an explanation of why the new keyword is omitted in this scenario and how the instance is actually created using the getInstance() method.

Can someone provide insights into how the getInstance() method works in this context and why the new keyword is not used?

How do modern C++ developers assemble architectural elements for interactive 2D vector graphics apps [closed]

The emergence of C++20 instills confidence in the enduring use of C++ for Computer Graphics (CG) development. Within this context, a pertinent question arises: What represents the most auspicious approach to address the foundational architectural design when dealing with interactive 2D vector graphics, taking into account the contemporary features of C++? Furthermore, what constitutes the optimal practice for modern C++ developers when it comes to harmonizing elements such as Drawable primitives, Transformations, Animations, Component-Oriented Design, Entity Component System, Scene Graph, Canvas, Viewport, etc.?

I've been exploring various publications that cover the implementation of fundamental Design Patterns using C++ in a general context. Additionally, I've come across articles that delve into a wide array of topics related to the design of 3D game engines, with a strong emphasis on rendering techniques. These resources are notably comprehensive and offer practical insights.

However, I've noticed a scarcity of information that provides a deep understanding of the design patterns and underlying architecture specifically tailored for creating interactive 2D graphics using modern C++, just before the rendering stage.

I've also reached out with this question to several C++-dedicated groups. The responses have been limited so far. One particularly valuable insight I received pertains to the challenges associated with using an Entity-Component-System (ECS) architecture in C++, particularly due to the complexities involved in managing ownership relationships. Although the responses have been few, they are significant, given the specific focus of the topic.

The significance of this subject becomes even more pronounced in light of the advancements in C++ since C++11. These advancements have kept the language relevant and appealing for vector graphics tasks. They also encourage a reevaluation of the methodologies employed in the past. For instance, the adoption of ECS as a concept gained traction relatively recently and has undoubtedly influenced the approaches we take in design.

lundi 28 août 2023

what is the arms pattern?

In the Rust book he said

A match expression is made up of arms. An arm consists of a pattern to match against, and the code that should be run if the value given to match fits that arm’s pattern. Rust takes the value given to match and looks through each arm’s pattern in turn.

But the example is very weak (is not the goal of the book)

I am not a native English speaker, maybe is that why this simple phrase is so confusing to me. Even chatgpt didn't give me an answer about that.

What is the Arms Pattern?

How to resolve error For the response: use 'Content-Type' header"

I'm using Design Center to specify my API and have to add some Rule Sets. One on them is API Team Best Practices and indicates the follow error:

Error: [API Team Best Practices] For the response use 'content-Type' header .

My code follow like this:

Design Center Image

Then I Add the content Header , like this

After fix the error

But The Rule set still error me , calling the following message:

**

  1. Parameters of type string must have the format field declared.

**

what am i missing? Any help ? Thanks

Use this article as reference of my problem https://help.mulesoft.com/s/article/Error-Error-Anypoint-Best-Practices-For-the-response-use-Content-Type-header-occurs-wen-designing-an-API-Specs-in-Design-Center-based-on-Anypoint-API-governance-Best-Practices

Add text to the bubbles in a CSS made diagram for a web app

I have created a basic star topology diagram using simple CSS and HTML. I have 2 problems with the code I have:

  1. When I try to add text to the bubbles, it overflows from the bubble and the text is not oriented based on the bubble.
  2. Instead of a simple bubble I would like a cloud shape.

Any suggestions/solutions would be highly appreciated.

* {
  margin: 0;
  padding: 0;
}

html,
body {
  height: 100%;
}

body {
  display: flex;
  align-items: center;
  justify-content: center;
}

figure {
  --containerWidth: 500px;
  --containerHeight: 500px;
  width: var(--containerWidth);
  height: var(--containerHeight);
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

figure div {
  background: gray;
  width: 140px;
  height: 140px;
  border-radius: 50%;
}

figure .connected-device {
  --connectedDeviceWidth: 100px;
  --connectedDeviceHeight: 100px;
  width: var(--connectedDeviceWidth);
  height: var(--connectedDeviceHeight);
  position: absolute;
  background: gold;
  top: 0;
  transform-origin: calc(var(--connectedDeviceHeight) / 2) calc(var(--containerHeight) / 2);
  display: flex;
  justify-content: center;
}

figure .connected-device::before {
  content: '';
  height: calc((var(--containerHeight) / 2) - var(--connectedDeviceHeight));
  display: block;
  border-right: 2px dashed grey;
  position: relative;
  top: var(--connectedDeviceHeight);
}

figure .connected-device:nth-of-type(2) {
  transform: rotate(calc(1 / var(--number-connectedDevices) * 360deg));
}

figure .connected-device:nth-of-type(3) {
  transform: rotate(calc(2 / var(--number-connectedDevices) * 360deg));
}

figure .connected-device:nth-of-type(4) {
  transform: rotate(calc(3 / var(--number-connectedDevices) * 360deg));
}

figure .connected-device:nth-of-type(5) {
  transform: rotate(calc(4 / var(--number-connectedDevices) * 360deg));
}

figure .connected-device:nth-of-type(6) {
  transform: rotate(calc(5 / var(--number-connectedDevices) * 360deg));
}

figure .connected-device:nth-of-type(7) {
  transform: rotate(calc(6 / var(--number-connectedDevices) * 360deg));
}

figure .connected-device:nth-of-type(8) {
  transform: rotate(calc(7 / var(--number-connectedDevices) * 360deg));
}
<figure style="--number-connectedDevices: 8">
  <div class="central-device"></div>
  <div class="connected-device"></div>
  <div class="connected-device"></div>
  <div class="connected-device"></div>
  <div class="connected-device"></div>
  <div class="connected-device"></div>
  <div class="connected-device"></div>
  <div class="connected-device"></div>
  <div class="connected-device"></div>
</figure>

Using color fill and shaded pattern in a stacked column chart in VBA

would you mind to tell me how to use the following macro taken from this website ( see below ), if the data are in a stacked column, which means that I want the macro to apply to horizontal Axis Labels( Category ) not the Legend Entries (Series). I tried to change the macro to read the categories and not the series but it doesn’t work. I don’t know if I’m clear in my request. The code seems to work only for pie chart and simple histogram chart but not for stacked column chart. Also how to use color and shaded pattern not only filling the colors. Thank you very much for your help.

` Sub ColorByCategoryLabel()

Dim nChart As ChartObject Dim rPatterns As Range Dim iCategory As Long Dim vCategories As Variant Dim rCategory As Range Dim iSeries As Long

Set rPatterns = Worksheets("Colors").Range("Color")

For Each nCht In ActiveWorkbook.Worksheets("Pie Charts").ChartObjects For iSeries = 1 To 1

    With nCht.Chart.SeriesCollection(iSeries)
      
      vCategories = .XValues
      
      For iCategory = 1 To UBound(vCategories)
          Set rCategory = rPatterns.Find(What:=vCategories(iCategory), LookAt:=xlWhole)
      
          If rCategory Is Nothing Then
              MsgBox vCategories(iCategory) & " Not Found"
          Else
              .Points(iCategory).Format.Fill.ForeColor.RGB = rCategory.Interior.Color
              '.Points(iCategory).Format.Fill.ForeColor.RGB = rCategory.Interior.Pattern
          End If
      Next
        
    End With
  Next
Next

End Sub`

What is the best way/method to work with objects with difficult structure? [closed]

I'm currently working on an online shop, and I receive from the server objects with a rather complex structure (product, user objects).

What is the best to work with objects with different structure? Is there any design Patterns, or other methods?

Now I reading refactoring guru book and my look is on Facade pattern.

Sometimes in my code there are rows like this

this.product?.masterData.current.masterVariant.prices[0];
or
this.product?.masterData.current.masterVariant.images[0].url || ''

How to properly correct such long lines of code, should I create a separate class for this? And if so, which one?

Suggestion on design pattern for event driven webapi development [closed]

I need experts' suggestion here to decide the disign to construct the Web Api. All I know is RESTful API where user can GET/POST/PUT/DELETE to manipulate data and response usually been sent to the client caller.

We have a requirement when API is called by a client, it may not receive the response immediately. In different words, the API has to perform some complex logic which may take few seconds and then this processed message requires to pass as Kafka message, where different clients receive the message and process it.

Once this is done, API can say that work is done and send response back to the clients.

Can anyone suggest the best design to overcome this requirement? (Technology chosen so far is .Net 6 Web API)

if I develop RESTful API in conventional way, the response does not matter to the client as this is just like.. 'Hey, wait please.. work in progress' kind of message. I am attaching basic diagram to give the idea how we want
enter image description here

dimanche 27 août 2023

What should the service layer return to the controller when validating data in service layer?

I have a small car API that is made up of a controller, service and repository I want to validate the data from within the service layer and return the 200, 404 or 400 with a little message saying what the problem is from the service. In other words, I want to move all the logic from the controller to the service layer.

How can I return a status code and if it's an error what caused the error, from the service layer to the controller?

API Controller method:

        [HttpGet("GetById/{Id:int}", Name = "GetCar")]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status404NotFound)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]

        public IActionResult GetById(int Id)
        {
            if (Id < 1)
            {
                ModelState.AddModelError("CarIdIsZero", "Car Id Must Not Be Less Than One !");
                return BadRequest(ModelState);
            }

            var car = _db.Car.FirstOrDefault(u => u.Id == Id);

            if (car == null)
            {
                ModelState.AddModelError("CarNotFound", "Car was not found !");
                return NotFound(ModelState);
            }

            return Ok(car);

        }

Service Layer Method:

public IActionResult GetById(int carId)
        {
            return;
        }

Repository Layer Method:

    public IEnumerable<Car> Get()
        {
            return _db.Car;
        }
       

How do I make ViewModels talk to each other in a Compose Desktop app?

I'm building a Jetpack Compose Deskop app that currently as a draft looks like this:

enter image description here

The 1 and 2 are two ViewModels:

// 1
class FilterViewModel {
    val query = mutableStateOf<String?>(null)
    val timeframe = mutableStateOf("Any")
}

// 2
class GridViewModel {
    val items = mutableListOf("foo", "bar", "baz")
}

I'd like the GridViewModel to update its items when the FilterViewModel changes. How do I do that in this situation? Does Jetpack Compose Deskop have anything to offer here or perhaps there are some more general solutions?

samedi 26 août 2023

c++ pattern design inheritance confusion

I want to create a hierarchy of classes that are derived from "genericClass". My problem is that I want to derive classes like "person", "car"... all of the derived classes have specific methods lets suppose:

Person -> getAge(), getSalary()

Car -> getEngine(), getMaxSpeed()

So when I create a "genericClass" pointer I would like to be able to access those functions (remember that they are not defined as virtual in "genericClass").

As far as I know the problem can be solved just by marking them as virtual in the genericClass or casting but I would like to know if a third solution exist.

#pragma once
#include <iostream>
#include <string>
using namespace std;

class genericClass {
 private:
 public:
  genericClass(){};
  ~genericClass(){};
};

class person : public genericClass {
 private:
  int age;
  double salary;

 public:
  person(int a, double b) : genericClass{}, age{a}, salary{b} {}
  ~person() {}

  int getAge() const { return age; }
  double getSalary() const { return salary; }
};

class car : public genericClass {
 private:
  string engine; // string is just a random type for this problem
  double maxspeed;

 public:
  car(string a, double b) : genericClass{}, engine{a}, maxspeed{b} {}
  ~car() {}

  string getEngine() const { return engine; }
  double getMaxSpeed() const { return maxspeed; }
};

int main() {
    genericClass* object = new person{23, 100};
    cout << object->getAge(); 
}

as you can see I cant access the methods because genericClass doesn't know about derived classes methods, happening the same for car

As I previously said I can write them as virtual int getAge() const; in the genericClass. This solution would lead to a massive genericClass with too many virtual methods if I want all of the classes to be derived from genericClass.

vendredi 25 août 2023

Does anyone know a good design to manage a group of multi-read single-write resources in C++

Problem: As the title, say, I have a group of resources I need to manage in a multi-threaded C++ program. Each resource should allow multi-read single-write access. Does anyone know a good design to solve this problem?

Attempted solution: The following outlines what I'm thinking about:

Given a resource as:

struct Resource {
    //...
};

I have a global Token Manager used to manage read/write tokens:

class TokenManager {
    private:
    std::mutex m_mutex;
    std::unordered_map<int, std::shared_mutex> m_tokens;

    auto &fetch(const int key) {
        std::lock_guard g(m_mutex);
        return m_tokens[key];
    }

    public:
    auto CreateWriteToken(const int key) {
        return WriteToken{key, fetch(key)};
    }

    auto CreateReadToken(const int key) {
        return ReadToken{key, fetch(key)};
    }
};

The WriteToken represent write access to the resource, and it is derived from the Token base class:

class Token {
    Resource m_resource;
    
    protected:
    Token(const int key) {
        //open resource based on key
    };

    public:
    void Visit(const Visitor v) {
        v(m_resouce);
    }
};

class WriteToken : public Token {
    std::unique_lock m_lock;

    public:
    WriteToken(const int key, std::shared_mutex &m) : Token(key), m_lock(m) {}
};

The ReadToken represent read access to the resource:

class ReadToken : public Token {
    std::shared_lock m_lock;

    public:
    ReadToken(const int key, std::shared_mutex &m) : Token(key), m_lock(m) {}
};

Can you see any obvious flaw in this design? Do you know a better design?

How to loosen the coupling for an implementation of a map maker?

I want to create a simple dungeon crawler game in Java. The Main function can take an argument "-t" that says that the program uses a file to build the maps and the UI is characters printed to the application screen (and not using JavaFX as an example). I want to make it so I can easily add other ways to make the map (like with a graphic mapmaker) and make the UI use some images, not text. the mapmaking using the file only needs the string path of the file. but other ways of making a map might need other parameters so I can't use an abstract class with the getMap() function that will be implemented in the concrete mapMaking class. I researched and I think this might be a case for dependency injection although I haven't used this design before and can't tell how to implement it here:

public class Main {

    public static void main(String[] args) throws Exception {

        Map map;
        MapGUI mapGUI;
        MapMaker fileMaker;

        if(args[0].compareToIgnoreCase("-t") == 0) {

            mapMaker = new FileMapMaker();
            mapGUI = new MapTextGUI();

        }//other cases will be added in the future...

        map = getMap(mapMaker);

        mapGUI.print(map);
    }
        //might need different parameters here
    private static Map getMap(MapMaker mapMaker) {/*how to inject  here the relevant parameters for each case of map maker  */
        return null;
    }
}

Interactive 2D vector graphics design patterns for modern C++ [closed]

C++20 gives confidence that the graphics will continue to be mainly done with C++. In this regard, the following question appears to be topical: What is a good source of materials to read/watch about approaches to the basic architecture and design patterns for interactive 2D vector graphics using modern C++? You know, about all sorts of Component-Oriented Design, Entity Component System, Scene Graph, Canvas, Viewports and all that?

What I managed to find is a Cherno's channel on his Hazel game engine. It's good, however is not specific to the basics of architecture as it tries to grasp a very wide range of aspects concerning game engines that require more attention than design patterns in the context of the channel's purpose. There's also a very nice channel by Douglas Schmidt on Design Patterns by Example with C++. It is very comprehensive and practical. And again, there's no much that can give understanding about the design patterns and basic architecture used specifically for interactive graphics where years of experience have already resulted in lots of conventional approaches to the code base.

The question arises also for the reason that advancements in C++ since C++11 make this language still very desirable in the context of vector graphics while motivating to revise the approaches used in the past.

jeudi 24 août 2023

what could be possible latitude and longitude [closed]

img

the japanese translation lead to me 35 as latitude and i've no idea about longitude.

Hey! we need to reach planet ElCamino as fast as possible. My friends sifrant, codebuster, sygamar are waiting with supplies there. Try to find the coordinates of the planet.

....incoming....incoming Jesse!!! we have an incoming message from sifrant...日本の東京の緯度に床関数を適用する

Hey friend! we have an incoming message from codebuster... (64)16 + (110)2 ..........SIGNAL LOST....

We are now alone, all connections are lost. We need to find the coordinates of the planet ASAP.

Design Pattern in C#

I maybe overthinking here and too conscious about using design patterns. But I am somehow stumped.

I have this main class called MainProcessor. It will have a method that will call around 20 classes' Execute() method asynchronously. These 2 classes will do its own thing in its respective 'Execute' method. It is unfortunately not Fire & Forget. The child class has to relay back a message to my MainProcessor class.

After these 20 little classes are done with the execution of their respective Execute() method, it has to convey back to the MainProcessor class if it's a success or not. The ordering of executing the Execute() method does not matter, as long as it is all async and each child class 'events' back a message to the MainProcessor class that it is done. I cannot use MSMQ or a Pub/Sub model here.

This is in .NET Core and I don't want to inject 20 'target' classes into my MainProcesor class's constructor because tomorrow we may add 10 more ChildProcessor classes and I cannot afford to change the MainProcessor class' constructor by adding more injecting logic, as it seems wrong. How can I make my class design so loosely coupled and dynamic?

If I go in with a simple abstract class with an Execute() method and implement it across my 20 child classes, how do I relay an event back to my calling class that the execute() method is done? I have never done events much to communicate between a calling and a called class, especially when it involves abstraction.

I have started off using a Concurrent Dictionary and I plan to use one of those Task.RunAll() async methods by looping through the ConcurrentDictionary. It is such an unfamiliar territory to me those Task related async calls. If I blink, I would be calling it all synchronously.

Is there a design pattern that I can think of here or what is the best way to implement this?

Thanks

Why do singletons use a function that returns an object instead of a simple initializing function?

On this site and others, I always see singletons written like this:

<?php

Class Singleton {
    private static $code = null;
    private static $instance = null;
    
    private function __construct() {
        self::$code = 'some_expensive_operation';
    }
    
    public static function getInstance() {
        if ( is_null(self::$instance) ) {
            self::$instance = new Singleton();
        }
     
        return self::$instance;
    }
    
    public static function useCode() {
        echo self::$code;
    }
}

// to use
$object1 = Singleton::getInstance();
$object1::useCode();

?>

But wouldn't it make more sense to write them like this, with a regular initializing function instead of a constructor?

<?php

Class Singleton {
    private static $code = null;
    
    public static function initialize() {
        if ( is_null(self::$code) ) {
            self::$code = 'some_expensive_operation';
        }
    }
    
    public static function useCode() {
        echo self::$code;
    }
}

Singleton::initialize();

// to use
Singleton::useCode();

?>

I'm drawn to the second example because using it only requires one line and no throwaway variable. It seems much cleaner.

Observer Pattern - notification with multiple values [closed]

In my application, I'm using the observer pattern for updating the user interface (GUI), logging measured values to a file, and so on. The method that retrieves new values returns a dictionary like {'x': x_value, 'y': y_value, ...}.

I want to implement safety functions that will verify whether the values meet certain conditions, and if so, trigger appropriate emergency actions.

For this purpose, I've created an Alarm class that takes a condition and a reaction as two methods. Such alarms are attached to the relevant events in the subject.

I'm wondering which approach would be better: a) Notifying about each value separately, which would allow defining the alarm condition as something like lambda value: value > 20. This solution seems straightforward but lacks flexibility. b) Notifying about all measurements at once and ignoring values that are not of interest, like lambda *_, value = None, **_: value is not None and value > 20. This approach is more flexible as all alarms are attached to one event, but it might raise some concerns.

Or maybe there's another way?

mercredi 23 août 2023

Why are distinct classes necessary for Customer and Account in the design of the Amazon Shopping System?

I've been studying the low-level design (LLD) of the Amazon Shopping Website on Educative. In this context, I've come across two classes: 'Customer' and 'Account' (details provided below). Could someone offer insights into the reasons behind keeping these classes separate? How is this approach a better design than having a single class that combines the information from both?

Definitions

Customer: The Customer abstract class refers to a user trying to buy a product from Amazon. Hence, it can access the items present in the shopping cart through the getShoppingCart()function.

Account: The Account class accesses and showcases the personal details of the authenticated user and the admin, who are the two types of registered accounts available in the system. Users with an account will have the option to add and access multiple shipping addresses as well as add and delete different products and product reviews.

Class Diagrams: Customer Account

I am unable to figure out why this design is good

Async await Chain Responsibility Pattern

Hello i am having an issue using async and await in a Chain Responsibility Pattern, when the HandlerRequest is executed and an await operation is hitting another task is fire not waiting the first task to finish, so the first task doesn't finish and the second task finish exiting the method, leaving the first task uncompleted

Calling a queue of operations to execute

private async Task DoOperations(CancellationToken token)
{
    foreach (var operation in _operationDetails)
    {
        if (token.IsCancellationRequested)
        {
            return;
        }

        await h1.HandleRequest(operation.OperationTask);
    }
}

Handler

public abstract class Handler
{
    protected Handler successor;
    
    public void SetSuccessor(Handler successor)
    {
        this.successor = successor;
    }
    
    public abstract Task HandleRequest(OperationDetails.OPERATIONS operation);
}

Portion of code Handler h1

public override async Task HandleRequest(OperationDetails.OPERATIONS operation)
{
    if (operation == OperationDetails.OPERATIONS.SERVER_GET_AUDIO_LIST)
    {
        _updateLabelMessage?.Invoke(this, "Obteniendo lista de audios del servidor.");
        var result = await _services.AudioService.DownloadAudioListServerAsync(_token);
        _raiseRichTextInsertMessage?.Invoke(this, (result.status, result.statusMessage));
        if (result.status)
        {
            _getAudioListFiles?.Invoke(this, result.data);
        }
    }
    else if (successor != null)
    {
        successor.HandleRequest(operation);
    }
}

Portion of code Handler h3

public override async Task HandleRequest(OperationDetails.OPERATIONS operation)
{
    if (operation == OperationDetails.OPERATIONS.SERVER_DELETE_AUDIO)
    {
        _updateLabelMessage?.Invoke(this, "Eliminando audios del servidor");
        foreach (AudioFile file in _audioFileListToDelete)
        {
            _updateLabelMessage?.Invoke(this, "Eliminando audio: " + file.name);
            var result = await _services.AudioService.DeleteAudioServer(file.name, _token);
            _raiseRichTextInsertMessage?.Invoke(this, (result.status, result.statusMessage));
            if (_token.IsCancellationRequested)
            {
                _raiseRichTextInsertMessage?.Invoke(this, (false, "Operacion Cancelada."));
                return;
            }
        }
    }
    else if (successor != null)
    {
        successor.HandleRequest(operation);
    }
}

The first operation called is h3 but when this line of code is executed

var result = await _services.AudioService.DeleteAudioServer(file.name, _token);

The next handler (h1) is called not processing all the files in _audioFileListToDelete

Role dependent behaviour in state pattern

I have a a class course which uses the state pattern to model the state of a course. A course starts as a draft, can then be handed in to be approved by an admin. If the course was approved it can be published via the rest api. Before being published courses may be canceled or deleted by the creator itself. If the course was already published only admins should be able to edit the course.

Until now I ended up with a mixture of conditionals to verify a certain user has required permission to change the state of the course and state pattern to verify correct state transitions.

Is there a way to integrate this behaviour in a single pattern? As I'm using DDD integrating permissions directly into the business rules this would violate DDD rules if I'm right

mardi 22 août 2023

Why is my python code printing this weird pattern?

I am trying to solve the following pattern: enter image description here

And here is the code that I wrote:

limit = 10
for i in range(1, 12):
    for j in range(i):
        print(" "*j, end="")

    if limit >= 0:
        for j in range(0, limit):
            print(j, end="")

    limit -= 1
    print()

But it is printing this weird pattern:

enter image description here

Strategy for syncing a SQL database with a spreadsheet?

This is more of a general design pattern and UX question than a technical one.

I am working on a SQL database which contains product inventory (using Django). Currently, this inventory is managed by another (non-technical) employee via a spreadsheet which contains all inventory information and is updated daily. In order to support this employee's workflow, I would like to have the option of uploading the spreadsheet to the server, have it processed, and reflect the changes in the inventory (SQL database). Here's the catch: The SQL database can also be updated by customers via our API. When a user purchases an item, it is removed from the inventory, meaning that our employee's spreadsheet becomes out of sync. Furthermore, if users are modifying the database and the employee does not have the most up-to-date version, when the employee goes to upload their spreadsheet, the changes made by users would be overridden.

Here are options I am considering:

  1. Require our employee to adopt a custom interface to manage inventory and ditch the spreadsheet. I am hesitant on this option because I want to support their existing workflow.
  2. Use an API like on Google Drive to update the spreadsheet programmatically whenever the database changes. Somehow this must also work in the opposite direction: when the employee updates the spreadsheet, the server must be made aware and update the database accordingly. My concern with this (specifically the latter aspect) is data integrity: it is easy for the employee to enter invalid data on their Google Sheet, resulting in failed updates to the database, and not much option to inform the employee of the failed insertion.
  3. Ensure that the employee downloads the latest state of the database before uploading a new spreadsheet. I am not sure how this can be enforced, and there seems to be a lot of room for error here.

Overall I am not sure the best way to proceed. Has anyone ever dealt with something like this, and if so how did you resolve it?

Using scoped services (ie DbContext) from two scopes without service locator

I need to write some service with method that needs to perform two units of work, where second one will be preformed even if first failed and was rolled back. Creating and rolling back transaction is not enough, because DbContext still remembers changes from first unit of work. Therefore I need two DbContexts. Because I use other services to perform the work itself, I need to get the DbContext to them and i want it to be injected, not manually created or obtained via service locator.

Usual approach is to inject IServiceScopeFactory, create scope and from it resolve services involved in the work (DbContext to manage transaction and some service to do the work using this DbContext). What I don't like about this, is that nowhere in signature of the containing service or it's methods is information that those services are needed, and that my service knows about IServiceScopeFactory therefore knows at least something about used DI framework.

I'd like solution that allows my services to know as little as possible about DI framwork (it is allowed to know that conceptually scopes exist, but should not depend on any class/interface from DI framework).

lundi 21 août 2023

Design question: should calculation done in frontend be stored in backend?

I'm making a dish price calculator web app with MEAN.

On the component DishDetail I calculate the price of the dish based on added ingredients (I call them dish components).

The HTML:

<p class="card-text"><b>Total cost:</b> </p>

which is calculated with the following function:

  getDishTotalCost(): void {
    this.totalCost = 0;
    this.dishComponents.forEach((component, index) => {
      this.totalCost += component.price * this.dish!.components[index].componentQuantity;
    });
  }

It is first calculated in ngOnInit() and also updated for each change of component quantity:

  onQuantityChange(_newValue: any) {
    this.getDishTotalCost();
    this.validateQuantityInput();
  }

which is called like this from the HTML:

(ngModelChange)="onQuantityChange($event)"

My question is: Should I store the value of totalCost in the database? Or is it "enough" to calculate only in the frontend? What is best practice? What are pros and cons by keeping it front-end only/add to database? Could there be any later implications for this decision? Looking for guidance, thank you!

Database for event driven system with multiple publishers

I am working on an event-driven system, we have a service that subscribes to 2 different event types, each coming from a separate service. In my service, I must combine them and emit the data again as an event. I am using typescript along with Postgres as a database. The rate of incoming events is relatively high and the records keep on updating. I have tried optimist(using version number) and pessimist locking(row-level lock).

With optimist locking there was a delay introduced and with pessimist locking there were many deadlocks. I was thinking to go with some lock-free design, but with that, I need to have many joins and the solution becomes more complex.

enter image description here

Event A

{
order_num:'123'
order_value:1000
route_code : 'r1'
}
{
order_num:'456'
order_value:450
route_code : 'r1'
}

Event B

{
route_code:'r1'
route_paths:[{
path_id:'p1'
path_start:'abc'
path_end:'xyz'
},
{
path_id:'p2'
path_start:'def'
path_end:'pqr'
}]
}

Event S Output

{
path_id:'p1'
path_start:'abc'
path_end:'xyz'
orders:[{
order_num:'123'
order_value:1000
},
{
order_num:'456'
order_value:450
}]
}


{
path_id:'p2'
path_start:'def'
path_end:'pqr'
orders:[{
order_num:'123'
order_value:1000
},
{
order_num:'456'
order_value:450
}]
}

There may be more services in future that Service S will subscribe to, so just wanted to design in a way that complexity is minimum.

I am not sure what is a better approach here. If I am doing something wrong please let me know.

dimanche 20 août 2023

What is the point of implementing an interface in go?

This code bellow gives runtime error: invalid memory address or nil pointer dereference, curious why enters the if clause and what is the point of implementing an interface in go if that if verifies for having the function without "implementing". The Module keyword within the Media creates the property Module within itself, that seems to act as a property of struct but also inherits its functions.

package main

type Module interface {
    Init()
}

type Media struct {
    Module // <- Why?
}

// func (m *Media) Init() {}

func main() {

    var v any = &Media{}

    if module, isModule := v.(Module); isModule {
        module.Init()
    }
}

What's the best way to deal with circular object-owning references in a one/many-to-many C++ class associations?

Good day. I am facing a programming design task and am struggling with choosing the best approach for implementation due to lack of experience. I'd be glad to hear which practices, paradigms, or patterns are applicable to this case.

Problem Setting

You need to code, in C++98 standard, a Worker class that can own abstract Tools. Tools can exist on their own, hence can be equipped and unequipped by workers; tools can't have more than one worker owner.

However, what makes this trickier is the fact lifetimes of these objects need to be managed accordingly:

  • If a Tool is destroyed, it needs to get unequipped, since holding a pointer to a destroyed tool can lead to undefined behavior.
  • Similarly, if Worker is destroyed, the Tool should be disowned.
  • If a Tool is already given to a Worker, giving it to another Worker does remove the Tool from the original worker.

On top of that, suppose there's a class called Workshop. Workshops must accept only workers who have an available tool of a certain pre-determined type (I decided to make Workshop a template for a Tool subtype).

If a workshop enrolls a worker, a random available tool of correct type gets associated with it and becomes unavailable to other enrollments. Again,

  • If a Worker is destroyed, they leave the workshop.
  • If a Tool that a Worker is using in a Workshop gets destroyed or assigned to another worker, the Worker leaves the Workshop.

Questions

What is the best approach to this type of relationship?

Currently, in order to implement the tool disowning upon destruction, I store Tool pointers inside workers, and a Worker pointer inside Tools. ~Tool() calls a Worker method that unequips it. However, since I want to make it possible to destroy the relationship from both classes, say, have a Tool::unset_owner() and Worker::unequip(Tool*), both of them keep calling each other, resulting sometimes in infinite loops.

To add the Workshop support, I decided to create a WorkshopBase to hide its ToolType template, and hold an std::map<Tool*, WorkshopBase*> in Worker to register tools and workshops. But, it further results in chains of calling double-sided methods that attempt to remove/insert pointers from each other.

However, I feel like I'm missing something essential and am violating some best practices for such one-to-many + many-to-many relationships. So my question is:

  • How to avoid coupling in this case as much as possible?
  • I've seen many posts that claim this is a bad practice. I wonder if there's a design pattern to address this? Do you think an event system with management classes would be a better fit?
  • All in all, how to achieve my desired result gracefully?

Reminder: I'm looking for a C++98 solution. However, I would prefer to have answers with solutions with newer standards, with *_ptr<> classes usage, maybe, as a footnote.

Design pattern to ensure do something & write database success

Assuming I want to build a cinema aggregator app, I have a transaction database. I want to save the state after the customer makes a booking.

So the flow will be like, init the data, make a book to my supplier by HTTP call, then update the data in the database

if the HTTP call is a success, it's ok, but the problem is when the HTTP call succeeds but the app fails to update the transaction status in the database.

is there any design pattern to use, to make sure the update operation is success when the HTTP call is success?

samedi 19 août 2023

Design suggestion for a reporting component

I am designing a reporting component. There are multiple reports that gets generated by different components and projects. All I am trying is to design a service to unify and generate reports.

The main constraint is the Database access where access is limited so this component cannot access all schemas however it can access its own schema. Only the main components can access their respective schema.

How do I effectively design a component (it can be a spring batch or a consumer or a service)

vendredi 18 août 2023

How is saga design pattern different from pub sub model in micro service architecture?

In saga one component calls another using a topic in between ,same thing happens in pub shub model .Then how both are different ?

React state management across functional components design pattern

I am working on a module that displays a list of records and allows the user to action a full create, read, update and delete on an individual record via a modal. To make the situation more complex the records have sub-records along with meta-data. A simplified example would be a recipes application.

We would have a top-level list of recipes displayed in a table including their name and ingredients. Users can click a single record to present the recipe in a modal with the table still visible in the background. From here they can unlock the modal to allow editing of the single record (ie; name, description, author) or update the list of ingredients individually via a nested table within view modal.

This module is built using the native state management with functional components split by logical action, ie; the list view and each CRUD modal state are separate. The ingredients are displayed in the view dialog but are rendered by their own functional component in a table. What is the recommended way to manage the states across these components?

At present the top-level list component holds all records in a single state with the below and the data being loaded in via a lazy load function:

const [recipes, setRecipes] = useState<IRecipe[]>();

As the table is built up via a map it passes each recipe through to the callback when displaying the modal, the modal component then initialises its own state for a single recipe with the value passed via the props.

const [recipe, setRecipe] = useState<IRecipe>(app);

Any actions taken against the recipe update the single recipe state within its context and similarly the recipe ingredients are passed down to their own functional component that hold them in their own IIngredients[] state.

This all works wonderfully for rendering the data however the concerns come around updating the root state upon close of the dialog as the top level table needs to display the new information. What is the optimal method for managing this to make sure the root list state is up to date and accurate?

The community seems divided on using the single top-level state throughout all modules or how this module is currently implemented. A single top-level state seems resource intensive and would involve lower modules performing logic beyond it's bounds however the alternative would be a lot of mirrored states being updated synchronously across multiple levels. I have also seen suggestions to use useReducer over useState but there are no clear design patterns leaning towards one or the other.

As a limitation, 3rd party state management like Redux is ruled out, the module is only to use native functionality.

Abstract factory pattern in java

why a certain variable is protected in the abstract factory pattern in java? we use protected access specifier in the abstract factory pattern. so, why we use them and what is the use of the protected or private specifier in this pattern

jeudi 17 août 2023

What is a Common Pattern for CLI Args vs Environment Vars vs defaults in go?

I would like to define a tool which provides a CLI Interface to set parameters when run locally but can also just use environment variables to set the needed parameters. Lastly there should be sane defaults set for most (not all) parameters.

The precedence should be:

  1. CLI Args
  2. Env Variables
  3. Defaults

Currently I am using cobra to parse the cli args and to define the defaults e.g.:

cmd.PersistentFlags().StringVar(&s3bucketName, "s3-bucket", "my-default-bucket", "S3 Bucket to store results")

In order load the env variables I am then checking every parameter for it's nil value and default and then overwriting it with an environment variable if present.

E.g.

envS3bucket, exists := os.LookupEnv("S3_BUCKET")
if exists && (s3bucketName == "" || s3bucketname == "my-default-bucket") {
  s3bucketName = envS3bucket
}

This is a bit tedious if you do this for a lot of variables. Additionaly I need to define a defaultS3BucketName variable or duplicate the actual default value as seen above.

I also tried doing this with envconfig along the lines of:

import  "github.com/kelseyhightower/envconfig"

type Parameters struct {
  s3Bucketname string `default:"my-default-bucket"`
  ...
}

var params Parameters

[...]

err := envconfig.Process("myapp", &params)
if err != nil {
  log.Fatal(err.Error())
}

cmd.PersistentFlags().StringVar(&params.s3bucketName, "s3-bucket", params.s3bucketName, "S3 Bucket to store results")

This works but it "leaks" the env variables into the help string (e.g. S3 Bucket to store results (default "my-default-bucket")), which is not ideal for keys and passwords.

I assume that I am not the first one to encounter this situation, however I could not find a common pattern as to how this is done. Can someone point me to a clean way of doing this?

How the attribute pattern works in the Oracle Cloud Data Integrator?

I have configured an extraction in Oracle Data Integrator from OCI, and the table that I want to extract, is already configured in the database to save the extraction. The problem is that the name of the attributes are not the same and I want to link the names by using a pattern.

View from the pattern linking

As you can see in the image, for example in the source I have tables like ApInvoicesAcctsPayCombinationsId, this should link with the attribute ACCTS_PAY_COMBINATIONS_ID, or for example ApInvoicesAmountPaid should link with ApInvoicesAmountPaid.

I haven't find information of how to use patterns from Oracle, I would like to see some examples.

I want to convert with Oracle pattern ApInvoicesAcctsPayCombinationsId into PAY_COMBINATIONS_ID, removing always the "ApInvoices" from the string and converting camel to underscored.

Thank you.

mercredi 16 août 2023

How can we reduce a Multi-Functional Class with conditional logic into Fundamental classes with Specific logic - C# ASP.NET CORE?

In an ASP.NET Core EF application, I have a 'CentralDesignObject' with many types of related data, and a significant amount of derived/calculated values based on the information applied to the 'CentralDesignObject'.

This 'CentralDesignObject' contains a many-to-one relationship with a 'DesignType' object, which defines various fundamental characteristics of the Central Design Object.

While there are broad similarities across all the 'DesignTypes' in terms of the types of related data and in terms of the objects calculation results, there are some calculation methodology differences depending on the 'DesignType'. These are expressed through conditionals within certain calculation routines.

The

CentralDesignObject{

  public Guid DesignObjectId {get; set;}

  public int DesignTypeId {get; set;}
  [ForeignKey("DesignTypeId")] 
  public DesignType {get; set;}
    
  public ICollection<RelatedDataA> RelatedDataA {get; set;}

  public ICollection<RelatedDataB> RelatedDataB {get; set;}

  public CalculationMethod_X() {
  
    if (DesignType.Name == 'foo') {  
      // do x
      return x;
      } else if (DesignType.Name == 'bar') {
      // do y
      // Slightly different result
      return y;
      }
    }
}


`public class RelatedDataA{

    public int RelatedDataAId {get; set;]
   
    public Guid CentralDesignObjectId {get; set;}
    [ForeignKey("CentralDesignObjectId")]
    public CentralDesignObject CentralDesignObject {get; set;}   

    public decimal A {get; set;}

    public decimal B {get; set;}
}

public class RelatedDataB{

    public int RelatedDataBId {get; set;]

    public Guid CentralDesignObjectId {get; set;}
    [ForeignKey("CentralDesignObjectId")]
    public CentralDesignObject CentralDesignObject {get; set;}

    public decimal A {get; set;}
    public decimal B {get; set;}
}

As more 'DesignTypes' are added, the approach has been to add conditional expressions within various calculations as required. The core concept I am trying to get a handle on is how to move away from ever growing conditional loops as the number of 'DesignTypes' grows. My thought was potentially implementing the core of the 'CentralDesignObject' as an base abstract class or interface and then creating Concrete Implementations for each 'DesignType' of the 'CentralDesignObject' as separate classes.

RelatedDataA, RelatedDataB, etc are still all relevant to each of these concrete types. So then it crossed my mind, how would the foreign key relationships on these RelatedData objects be configured when they may be related to ConcreteCentralDesignObjectTypeA , ConcreteCentralDesignObjectTypeB, ConcreteCentralDesignObjectTypeC, etc.

Is there another approach which would be more appropriate? Is it worthwhile to try and make this change at all?

Any thoughts or recommendations on how to approach this kind of problem are appreciated.

Is it a bad practice to use python sys.exit in small command line tools? [closed]

In my group there was this idea that we should replace all sys.exit() with an exception and have a global try catch in main/entry-point function that will catch all these exceptions.

We used sys.exit() for cases when the application encountered a fatal issue and cannot continue. So in that case we logged an error message and exited the application.

Now, my colleagues are severely worried about sys.exit() usage and want to remove them by making the code, to me, more complex - less robust.

An in general Is it a bed practice to use sys.exit() in python in command line tools?

so here is what we have:

def func():
    try:
        response = get_some_google_service_response()
    except GoogleError as error:
        log.fata(f"We encountered a fatal error: {error} and cannot continue. Please contact our team here-here-here")
        sys.exit(1)

    use_that(response)
    rely_on(response)
    etc()


def main():
    func()

if __name__ == "__main__":
    main()
             

and here is what they want to change this to:

def func():
    try:
        response = get_some_google_service_response()
    except GoogleError as error:
         raise CustomGoogleError("We encountered a fatal error: {error} and cannot continue. Please contact our team here-here-here")

    use_that(response)
    rely_on(response)
    etc()


def main():
    try:
        func()
    except Exception as error:
        log.error(error)

if __name__ == "__main__":
    main()

Of course this is very simplified example and our code is 10s of files and many nested function calls and classes.

Please give me your opinion as I think what my colleagues are doing is wrong but want more words to argue this.

How to compare the pattern of row lines through pandas on excel data

enter image description here I would like to match the pattern of 'Y' and 'N' in a row wise data through pandas on excel. Please help me

I would like to match the pattern of 'Y' and 'N' in a row wise data through pandas on excel. Please help me

Provided you sample data in an image

Application architecture in scope of configuration, viewsets and dockable windows

Description

I have an C#/WPF application that uses MVVM pattern and PRISM. My app has viewsets, dockable single- and multi-instance windows. There are user settings (window size, position), workspace settings (viewsets, docking layout, column sizes, python scripts, list of entries in watch windows, logging intervals per entry, etc.) and project settings (a hierarchical list of entries with additional properties) all stored as XML files using custom serializers. App is made in a very generic manner, modules 'doesn't know' about each other, partially PRISM service locator is used and partially DI, PRISM events are tuned down to absolute minimum.

Issue

I will now consider only workspace settings - they are managed by ConfigurationManager. ViewSetManager is responsible for managing viewsets and DockingManager is responsible for serializing/deserializing window layout for selected viewset. There is additional NavigationManager that provides a wrapper for PRISM regarding getting a list of views/viewmodels and navigating considering the fact that there are multiple viewsets.

Currently ConfigurationManager exposes Loading, Loaded, Saving, Saved events. To these events is subscribed ViesetManager (in order to recreate viewsets, when new configuration is loaded) and DockingManager (to perform required serializations).

ViewSetManager has ViewSetChanged event. To that event is subscribed ConfigurationManager (to know when viewset has been added/removed/changed by user) and DockingManager (to perform required serializations). It's worth noting that ViewSetManager is an entity instantiated inside ConfigurationManager.

As you can see, this approach is quite complicated and error prone.

Question

  1. Who's responsibility is to manage all the connection between ConfigurationManager, ViewSetManager, DockingManager?
    • Should it be done with events or maybe by additional mediator or perhaps ShellViewModel?
    • How it should be ideally done?
  2. Should ConfigurationManager instantiate any complex objects that manage application or should simply provide basic properties to be used by other parts of the app?

Bonus Question

  1. Should ConfigurationManager be a single entity responsible for serialization/deserialization, watching file and providing settings or it should be divided into two separate entities - one responsible for file operations and one for settings provisioning?

Possible solutions

I am redesigning mentioned architecture. In a new approach an area that will display all the views is called ViewSetRegion - it manages viewsets and when new DockingControl is added (perhaps by ViewSetManager) it creates new dynamic DockingRegions, which can be populated with views from different part of the app. I believe this is quite clean design, however I am unsure how to connect this part of the application with ConfigurationManager.

Final note

If you could provide me at least answers to those questions or any meaningful articles on this topic or an actual application design I would be grateful :)

algorithm to sequence pattern mining

does anyone know if there is a algorithm that is able to find sequential pattern from unorganised data. Details are described below along with the screenshot.

Info : First column is my original data. there are multiple set of activity being done there most of them are in order but there are not little of them that are not in order. Final output is shown in the last column/

Question: how do I find the sequence of the activity based on the the frequent order of the activities?

current way to help finding a solution :start looking at the most frequent data and how frequent it is might be adjusted by the user(?). After getting the most frequent data, it then comes to a question of what algorithm or how do I get the rough sequence of the activities?

I am not sure if my current workaround to get into the solution is right but if there is an efficient way, then that is even much better

enter image description here

What means surrogate in context of proxy

In the gang-of-four is written

Proxy (207) Provide a surrogate or placeholder for another object to control access to it.

Is surrogate in this context just a synonym of placeholder?

or is in this context surrogate referring to surrogate model when the proxy wraps the real class and approximate methods output?

mardi 15 août 2023

Allow users to self-subscribe to SNS topic

I currently have a simple dynamoDB stream set up with an sns topic (with a lambda function in between to parse the stream output), to inform interested users on changes to the database.

As interested users grow, adding people manually through the UI is tedious.

I want to create a front-end to allow users to self-subscribe.

Here's my idea so far:

  • have users provide an email to the lambda function, by making an api call to the function from a UI

  • lambda function will use the subscribe action of the sns API and give it the user provided email as an endpoint

  • user confirms the subscription request on their email

I looked for a design pattern on AWS sns topics to provide this solution, but I did not see one for the use case of allowing users to subscribe themselves to topics on AWS's documentation.

Would this system work? Is there a more elegant way I missed?

how to organize files/folders when using Model-View-ViewModel design pattern

I've watched tons of tutorials on the Mode-View-ViewModel design pattern for Xamarin.Forms, and none of them approach the "how to organize the folder and file structure when using this design pattern" the same. Usually these tutorials are just demo-ing a little piece of functionality, so it doesn't matter as much.

However, it's important to me because I'm writing an actual app.

The way I'm approaching this has got to be wrong, but I'm not sure how I'm supposed to do this. Maybe someone could tell me what I should do?

Setup
I've just created a blank project. My folder structure is basically this:

MyWidgetApp     
    > Dependencies     
    v App.xaml            
           App.xaml.cs     
    v MainPage.xaml            
           MainPage.xaml.cs

The next step for the VMMV design pattern is to add some folders, right?

Add folders
We should add folders for the design pattern. A View folder, a Model folder, and a ViewModel folder:

MyWidgetApp     
    > Dependencies     
    > Models     
    > Views     
    > ViewModels     
    v App.xaml
          App.xaml.cs   
    v MainPage.xaml
          MainPage.xaml.cs        

Next, we create a Model, a View, and a ViewModel for the widget. I want to mess with the Widget on an entirely different page than the MainPage. The model obviously goes into the Models folder:

v Models
     Widget.cs

However, the View and ViewModel are a little more complicated. I create a new "Content Page", and it creates two files; let's call them Widget.xaml (the View), and Widget.xaml.cs (the ViewModel).

The answer seems obvious, right? Put the Widget.xaml into the View folder and put Widget.xaml.cs into the ViewModel folder. Not only that, I should put MainPage.xaml into the View folder and MainPage.xaml.cs into the ViewModel folder, right? Heck, we may as well go whole hog and do it with App.xaml/cs, too!

MyWidgetApp     
     > Dependencies     
     v Models            
          Widget.cs     
     v Views            
          App.xaml            
          MainPage.xaml            
          Widget.xaml     
     v ViewModels            
          App.xaml.cs            
          MainPage.xaml.cs            
          Widget.xaml.cs

Set up Binding
Here is where I fall off a cliff.

Before I set up the files in the "obvious" way, filename.xaml.cs was literally a child of filename.xaml. Now they're in entirely different folders, and the normal ways that I was taught to bind don't work! It almost seems like I should put every single file into root and call it a day (and have the most disorganized file structure on Earth).

How am I supposed to organize the files/folders when using the Model-View-ViewModel design pattern in Xamarin.Forms? (or anywhere, really)

lundi 14 août 2023

How can I implement a thread-safe lazy-initialized singleton in C# without using the `Lazy

I've been reading about the Singleton pattern in C# and how thread safety can be a concern, especially when it comes to lazy initialization. I'm aware of the Lazy<T> class which can be used to create a thread-safe lazy-initialized singleton. However, for educational purposes, I'd like to understand how one might implement this without relying on Lazy<T>.

Here's what I've tried so far:

public sealed class Singleton
{
    private static Singleton instance = null;
    private static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            if (instance == null)
            {
                lock (padlock)
                {
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }
}
  1. Is the above code a proper thread-safe lazy-initialized Singleton in C#?
  2. Are there potential pitfalls or performance concerns with this approach?
  3. Are there alternative methods to achieve this without Lazy<T>?

Any insights or suggestions would be appreciated!

How to design a test case that creates a lot of business entities which attributes are used on the test conditions

I'm developing a test case, in Java with Junit Jupiter, that creates a lot of business objects which attributes are used on the test conditions.
The application being tested uses data persisted in some persistent unit, using the business objects, to create some kind of result. The result's data is tightly related to the business object attributes persisted.
The code looks lie this:

MyBusinessDto myBusinessDto = new MyBusinessDto();
MyOtherBusinessDto myOtherBusinessDto = new MyOtherBusinessDto();
...
YetAnotherBusinessDto yetAnotherBusinessDto = new YetAnotherBusinessDto();

//execution, where the business dto's are persisted on some system

PersistedSystemDto persistedSystemDto = getResult();

assertThat(persistedSystemDto.someAttr())
    .isEqualTo(myBusinessDto.anAttr());
assertThat(persistedSystemDto.someOtherAttr())
    .isEqualTo(myOtherBusinessDto.otherAttr());
...
assertThat(persistedSystemDto.yetAnotherAttr())
    .isEqualTo(yetAnotherBusinessDto.yetAnotherAttr());

The problem I see is on the business object creation. There are a lot of lines on the test's body just to create the business objects and it just does not feels right.
Is there a pattern or approach to deal with this king of scenarios?

dimanche 13 août 2023

Should response handlers in Spring be interfaced?

I am designing a spring boot application and I am writing a response handling class

public class ResponseHandlerImpl extends ResponseHandler {

public ResponseEntity<Object> generateResponse( Object responseObject, String message, HttpStatus status){
        HashMap<String, Object> map = new HashMap<>();
            map.put("data", responseObject);
            map.put("message", message);
            map.put("status", status);
            return new ResponseEntity<Object>(map, status);
        }
}

The thing is, is it best practice to make the responsehandler class static or extend from an interface?

I feel like error response handlers should be static. But I'm not too sure.

Or should it extend from an interface and not be static?

Any guidance is very much appreciated. How would you code your response handler class?

Laravel: Using resolve or inject from __construct?

I'm new to Laravel, recently I've learned what Service Container can do. After some researching, I found that either using resolve method or injecting dependency from constructor, I can always mock class and test my class. So I wonder is there any benefits to inject class into constructor?

example:

class Cat 
{
    public function speak()
    {
        return 'Meow!!';
    }
}

1- using dependency injection

class PetService
{
    public function __construct(Cat $cat)
    {
        $this->cat = $cat;
    }
    

    public function testFunc()
    {
        return $this->cat->speak();
    }
}

2- using resolve method

class PetService
{
    public function testFunc()
    {
        $cat = resolve(Cat::class);
        return $cat->speak();
    }
}

in testing-

class TestContainerTest extends TestCase
{
    /**
     * A basic unit test example.
     *
     * @return void
     */
    public function test_example()
    {
        $mock = $this->mock(Cat::class, function (MockInterface $mock) {
            $mock->shouldReceive("speak")->andReturn("test");
        });


        $node = resolve(PetService::class);
        dd($node->testFunc());
    }
}

both 2 ways can print "test". It means the mock success. Using constructor to inject may lead to heavy code in constructor, instead using resolve I can call class anywhere.

What is the last value of b which breaks the loop? ( Is it -1 if I am not wrong?? )

class exp{
public static void main(String arr[]){

for(int b=3;b>=0;b--) {
System.out.println("");

for(int a=0;a<=b;a++)  {
System.out.print("*");
    }
}

    }
}

It is an asterisk pattern, I understand this code and as per my understanding that last value of b should be -1 so that the final outer loop breaks and stops the printing of the pattern. I even tried to print the value of b but understood that it won't work due to the scope limitations. Can someone please confirm me the value of final value of b here in this code.

vendredi 11 août 2023

How should I structure modules in a large python application?

I often write and participate in the development of web applications in Python together with FastAPI. I always use the same folder structure which is as follows:

enter image description here

I think the names are clear to know what is in each of them. But I want to focus on two folders: api and services. Within api are all the modules with the endpoints of the application (one module for each "Entity", for example in the module api/routers/users.py will be all the endpoints for the users. In these endpoints there is no complex logic , all the logic is in the "services" folder. So, in the module services/users.py there will be a whole class called User with the logic. In many cases that class is simply a CRUD that inherits from a BASE CRUD and doesn't even extend the class Or maybe add one or two more methods. However, in some cases, the "entity" requires much more complex logic, it is appropriate to implement some design patterns, interfaces etc. When that happens I feel overwhelmed by having to put everything in the services/users.py module. (which implies a very large file). I've even seen how other developers continue to extend the User class (it's just an example, it can be anything) with a lot of methods that have nothing to do with the class, making the code too coupled and with low cohesion. As a solution to that, I thought of creating a folder as such for each entity and not a module. Then it would be services/user and there have all the user logic distributed in more than one module if necessary. But I'm not sure I'm doing the right thing in terms of design. Am I making things more complicated? Or is it a correct strategy?

Facade design pattern over data types

I have a class named MyClass in subsystem A, and a method in subsystem B has arguments of type MyClass. My subsystems are highly coupled, so I want to make a facade for subsystem A. Should I somehow pass the MyClass type trough the facade? What is the right way?

thanks

Is it a good idea to introduce additional layer between repository and service?

I don't know if it's a good idea to decouple repository from service by introducing an additional layer.

I see these advantages:

  • Easy to add some features such load-balancing, picking a best repository, add cache and other.

  • Repository and service does not coupled to each other

Disadvantages:

  • Code harder to understand, because a lot of generic types
  • Code harder to write

It's simple example, but it describes what I created.

Entity as interface

interface Book {
    Long getId();

    String getName();
    // other fields related to book entity
}

Jpa implementation:

@Entity
class JpaBook implements Book {
    @Id     
    Long id;
     // Implement interface methods
}

Basic persistent operations that used by repository and additional layer

interface BasicBookPersistentOperations<T extends Book> {
    void save(T book);
    T findById(Long id);
// other methods
}

basic repository interface that used to call the database or use in memory database

interface BookRepository<T extends Book> extends BasicBookPersistentOperations<T> {
    String getRepositoryType(); // String for simplicity, can be JPA, IN_MEMORY, REDIS, whatever
}

Jpa book repository that use jpa spec to call the database

interface JpaBookRepository extends BookRepository<JoaBook>, JpaRepository<JpaBook, Long> {
    
}

And additional layer between repo and service is storage:

// PersistableBook is used as wrapper that does not depend on specific Book implementation
class PersistableBook implements Book {
    // Implement methods from interface
}
interface BookStorage extends BasicBookPersistentOperations<PersistableBook> {}

And then I implement BookStorage, for example, simple impl that delegates to repository

class RepositoryDelegateBookStorage implements BookStorage {
    final BookRepository<Book> delegate;
 
    public RepositoryDelegateBookStorage(BookRepository<? extends Book> delegate) {
        this.delegate = (BookRepository<Book>) delegate; // I don't think it's a good idea to cast it, but if don't do this code will become more complicated
    }

    @Override
    void save(PersistableBook persistableBook ) {
          Book book = convertBookToSpecificEntityImpl(persistableBook);
          delegate.save(book);
    }
    
    @Override
    public PersistableBook findById(Long id) {
        Book book = delegate.findById(id);
        return bookToPersistableBook(book); // Instead of internal methods can be creadted 
        // EntityConverter, but for simplicity I use internal methods
    }
}

I don't know if it's a good or no, can be this refactored to become better? Or it is a complex and should be avoided? Should entities be described using interface and then implemented by different database providers or I should use single class for every database, for example, Redis, Postgres and In memory? What patterns I can use to make code better and easy to extend?

If my question is not clear I can provide more info, thanks!

What's the name of this when using the ID and title in URL of a web resource

For example, the StackOverflow question URls look like this:

https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it

Somewhere in the code, there's a parser that does the following:

  • hash: ""
  • hostname: "stackoverflow.com"
  • pathname: "/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it"
  • port: ""
  • protocol: "https:"
  • search: ""

And take the pathname's value and parse it using this pattern: /questions/<ID>/<Title>.

When the parser runs what it matters to identify the post is basically the ID, and the title can be basically anything, test it yourself and the following URLs will redirect you to the correct URL:

  • https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it-extra-text
  • https://stackoverflow.com/questions/218384/this-is-a-different-text
  • https://stackoverflow.com/questions/218384 <-- no text at all

Does anyone have an idea what this pattern is called and have references to it?

jeudi 10 août 2023

Orchestration Service vs Choreography Service vs Workflow [closed]

I need to implement a business process that performs 4 steps e.g.

  1. An event calls Service A
  2. Use the response of Service A to Call Service B
  3. Use the response of Service B to Call Service C
  4. Use the response of Service c to Call Service D

I have implemented the above using a central Orchestration microservice in the past. Where the Orchestration Springboot microservice holds the logic and manages the E2E business process (steps 1-4).

My questions:

  1. When is the use of an orchestrator service good practice i.e. a central microservice communicating to external services and passing the output of one service as input to the next dependent service?
  2. If one or more of steps 1-4 is a messaging interaction based on pub/sub or standard queue, what will be the best approach to implement the business process 1-4?
  3. If steps 1-4 is all synchronous service call, could I still use choreography with service communication based on events pub/sub and queues?
  4. When is a workflow tool like Airflow suitable for this kind of multi-microservice interaction to realize a business process?

I want to check whether name contains any special character or number in Ruby

This is code -

def username_chk(str)
     if str.length <=20         
        if str=~/^[a-zA-Z\\s]+$/
        puts "Invalid User name"
        else
        puts str
       end  
     else puts"User name can contain Max 20 character"
     end
  end   
      username_chk("Mark ju09")  

it's not working. I also tried:

str=~/[a-zA-Z]+\\.?/

str=~/^[a-zA-Z\s]+$/ this expression working fine in java using Pattern

How to add categories to WordPress block patterns?

I'm trying to create categories for WP block patterns. So far I have:

// Custom taxonomy for wp_block post type
function register_patterns_taxonomy() {
    $labels = array(
        'name' => 'Pattern category',
        'singular_name' => 'Pattern category',
        'search_items' => 'Search Patterns categories',
        'all_items' => 'All Patterns categories',
        'parent_item' => 'Parent Pattern category',
        'parent_item_colon' => 'Parent Pattern category:',
        'edit_item' => 'Edit Pattern category',
        'update_item' => 'Update Pattern category',
        'add_new_item' => 'Add New Pattern category',
        'new_item_name' => 'New Pattern category Name',
        'menu_name' => 'Patterns categories',
    );

    $args = array(
        'labels' => $labels,
        'hierarchical' => true,
        'public' => true,
        'show_ui' => true,
        'show_admin_column' => true,
        'query_var' => true,
        'show_in_rest' => true,
        'rewrite' => array( 'slug' => 'patterns_categories' ),
    );

    register_taxonomy( 'patterns_categories', array( 'wp_block' ), $args );
}
add_action( 'init', 'register_patterns_taxonomy' );

// creating patters categories by taxonomy terms
function create_block_pattern_category_for_terms() {
    $taxonomy = 'patterns_categories'; // Zmień na nazwę swojej taksonomii
    $terms = get_terms( array(
        'taxonomy' => $taxonomy,
        'hide_empty' => false, // Pobierz wszystkie termy, także te puste
    ) );

    foreach ( $terms as $term ) {
        $pattern_category = sanitize_title( $term->name ); // Tworzenie unikalnej nazwy kategorii
        $pattern_category_exists = get_terms( 'patterns_categories', array( 'slug' => $pattern_category ) );

        register_block_pattern_category(
            $term->slug,
            array( 'label' => __( $term->name, 'wpdocs-my-plugin' ) )
        );

    }
}
add_action( 'init', 'create_block_pattern_category_for_terms' );

and that works fine, I have custom taxonomy visible in block pattern post, also I successfully created blocks pattern categories based on custom taxonomy terms.

But now, I need to add somehow these terms to blocks patterns.

My idea is using register_block_pattern() for each post in wp_block post type, and add properly: title, content and categories. So I've tried:

// trying to create patterns
$args = array(
    'post_type' => 'wp_block',
    'posts_per_page' => -1,
);

$posts = get_posts($args);

foreach ($posts as $post) {
    setup_postdata($post);

    $title = get_the_title();
    $content = get_the_content();

    // Fetch terms associated with this post
    $terms = wp_get_post_terms($post->ID, 'patterns_categories', array('fields' => 'slugs'));

    // Create block pattern
    register_block_pattern(
        'handy-options/' . $title,
        array(
            'title'       => $title,
            'description' => _x('Two horizontal buttons, the left button is filled in, and the right button is outlined.', 'Block pattern description', 'theme-slug'),
            'categories'  => $terms,
            'content'     => wp_json_encode($content),
        )
    );
}
wp_reset_postdata(); 

but I don't know is this a good way - although new block patters are created with correct title, I can't add terms and content correctly.

Any advice, idea?

ask about component structure and architecture?

I'm a newbie working as a new FE developer. I've been thinking a lot about component structure in my development lately, e.g. where to call APIs, how much separation, how much nesting and depth of components, etc.

I've been reading a lot of articles and design patterns, and personally I've been working on a project using the presentational container pattern, but now I'm starting to have doubts.

I'm using hooks to manage state in one container, so I'm not using props and the hooks are responsible for all the state.

Folder structures

Hook Code

This feels very foreign to me and I think it's adding complexity.

I'm curious to know what you guys think (I realize that my structure may feel stupid), and I'd appreciate any recommendations for component structures or design patterns.

I've looked at various blogs, official documentation, and git conventions, but I haven't found a component structure or design pattern that works best.

mercredi 9 août 2023

How to add category to reusable blocks / patterns in WordPress?

I would like to add categories to reusable blocks / patterns without any plugins. My goal is categorise these blocks patterns in modal.

I've tried to create custom taxonomy for wp_block post type but I stuck how to assign them as block pattern category.

Card Component using React MUI

I am not able to create the structure of the below card. My card Media is just not loading and no image is appearing. Please help Due to strict company policies, I cannot share the real picture of the card. I have created the dummy image for the reference card. Can someone please help me with this. I am struck for a day and none of senior cares! Can someone please send the code structure for the below image. enter image description here

I am not able to figure out how to align both image and text horizontally.

mardi 8 août 2023

How to best model a bi-directional association between two classes iny my python code

I have a numerical model that models some physical quantities. Now to analyse and administer the results of said model I am writing some python infrastructure code. The basic concepts I have are that of a model run (identified by its timestamp) and that of a quantity (identified by its name). As said each model run contains multiple quantities and a quantity can appear in multiple model runs.
My idea is thus to model the relationship between a model run and a variable by utilizing an additional class DataPoint.

The basic setup would look like this:

class ModelRun:
    def __init__(self,timestamp):
        self.timestamp = timestamp
class Quantity:
    def __init__(self,name):
        self.name = name
class DataPoint:
    def __init__(self,model_run,quantity):
        self.model_run = model_run
        self.quantity = quantity

Now like this the structure is of course not navigable. This could be solved by adding a list of datapoints to both the ModelRun as well as Quantity class like so:

class ModelRun:
    def __init__(self,timestamp):
        self.timestamp = timestamp
        self.data_points = []
class Quantity:
    def __init__(self,name):
        self.name = name
        self.data_points = []
class DataPoint:
    def __init__(self,model_run,quantity,data):
        self.model_run = model_run
        self.quantity = quantity
        self.data = data
        quantity.data_points+=[self]
        model_run.data_points+=[self]

Is this a useful pattern? From my gut feeling it is a bit strange to modify instances of Quantity and ModelRun from within the DataPoint.__init__ method. As my ModelRun and Quantity classes wil get more complex and be used in a lot of other parts of my code I am very much afraid to introduce some unnecessary mistakes at this stage.
Any suggestions appreaciated, thanks!

Design A Circuit That Can Detect 4 Consecutive 1'S. Draw State Diagram & State Table

Using the design procedure for sequential circuits, we have to design a circuit that can detect 4 consecutive 1s or more, there was a similar question but with 3 consecutive 1s or more, in that question, we had to make a state table and diagram with only 4 states (i.e: 00, 01, 10. 11), but in this question, I am confused that should i make 8 states (i.e: 000, 001, 010, 011, 100, 101, 110, 111) states or only 5 states (i.e.: 000, 001, 010, 011, 100: fifth state repeating itself when the input is 1 and return to base state when the input is 0).

My current guess is that I only need 5 states,

Present Input Next State Output

0 0 0 | 0 | 0 0 0 | 0

0 0 0 | 1 | 0 0 1 | 0

0 0 1 | 0 | 0 0 0 | 0

0 0 1 | 1 | 0 1 0 | 0

0 1 0 | 0 | 0 0 0 | 0

0 1 0 | 1 | 0 1 1 | 0

0 1 1 | 0 | 0 0 0 | 0

0 1 1 | 1 | 1 0 0 | 1

1 0 0 | 0 | 0 0 0 | 0

1 0 0 | 1 | 1 0 0 | 1

But I am confused while trying to find the equation of the 4 T flip flops using a k-map, should I include the same states with input 0 or should I just include the states with input 1 in the excitation table?

lundi 7 août 2023

Is there a benefit to having an Interface for the individual Executors?

I'm trying to work on implementing a couple of APIs for a project and have this confusion around the use of Interfaces.

Let's suppose I have three Executor classes and an Activity class as follows:

//A main RandomActivity class as follows:

@AllArgsContructor(onConstructor = @__({ @Inject }))
public class RandomActivity extends Activity {

    private final ExecutorClassA executorClassA;
    private final ExecutorClassB executorClassB;
    private final ExecutorClassC executorClassC;

    public SampleResponse randomExecuteForA(ParameterForClassA parameterForClassA) {
        executorClassA.executeSomeFunctionA(parameterForClassA);
    }

    public SampleResponse randomExecuteForB(ParameterForClassB parameterForClassB) {
        executorClassB.executeSomeFunctionB(parameterForClassB);
    }

    public SampleResponse randomExecuteForC(ParameterForClassC parameterForClassC) {
        executorClassC.executeSomeFunctionC(parameterForClassC);
    }
}

class ExecutorClassA {

    public SampleResponse executeSomeFunctionA(ParameterForClassA parameterForClassA) {
        //do something
    }
}

class ExecutorClassB {

    public SampleResponse executeSomeFunctionB(ParameterForClassB parameterForClassB) {
        //do something
    }
}

class ExecutorClassC {

    public SampleResponse executeSomeFunctionC(ParameterForClassC parameterForClassC) {
        //do something
    }
}

Now I can have a setup like above, where the different classes take in different parameters and execute some logic (which is the "do something" section).

But I can also have an implementation like below, where I can have an Interface for these Executor classes.

interface MainExecutor {

    public SampleResponse execute(Object t);
}


//And then for each of the individual classes

class ExecutorClassA implements MainExecutor {

    public SampleResponse execute(ParameterForClassA parameterForClassA) {
        //do something
    }
}

class ExecutorClassB implements MainExecutor {

    public SampleResponse execute(ParameterForClassB parameterForClassB) {
        //do something
    }
} 

class ExecutorClassC implements MainExecutor {

    public SampleResponse execute(ParameterForClassC parameterForClassC) {
        //do something
    }
}

And then the RandomActivity.class does the same thing as above. 

Is there any added benefit of designing an Interface for this separately and having the Executors implement it? I understand that an Interface enforces a contract, so by having that, the execute function is ensured, but we will be calling the execute function (or a variation of that name) in the RandomActivity class regardless, so is the Interface really required?

samedi 5 août 2023

Flutter bloc pattern

I'm learning bloc pattern. I could not understand what is the usecase of this toString function in bloc pattern. Ok I did convert the constructor to string and passed it the counter, so what?! why should I even do something like that?!

class CounterState extends Equatable {
  final int counter;

  const CounterState({
    required this.counter,
  });

  factory CounterState.initial() {
    return const CounterState(counter: 0);
  }

  // THIS FUNCTION 
  @override
  String toString() => 'CounterState(counter: $counter)';
  //

  CounterState copyWith({
    int? counter,
  }) {
    return CounterState(
      counter: counter ?? this.counter,
    );
  }

  @override
  List<Object> get props => [counter];
}

Design pattern for handling different sets of inherited variables?

I have a base class that stores all columns of one record of a database. In that class I have set and methods as well. I also have a pure virtual method named Run(). Now I wan to have three child classes that send different fields of that record to different recepients using the Run() method. But, here's the problem. Child classes inherit variables (fields of the databse record in this example) that don't use. I only want to use only common fileds in the base class, and store the others in child classes. Then how would I set the member variables of child classes using the base class pointer? None of the Child1, Child2, Child3 uses all the field1, field2, .., fieldN. If transfer the fields that each child wants into its own class, then I how would I use SetFields from parent to set different fields in different child classes?

class Interface
{
public:
int field1, field2, field3, ..., fieldN;
void SetFields(field1,field2,field3,fieldN); // --\> gets all the fields as arguments
virtual void Run() = 0;
};

class Chid1: public Interface
{
void Run() {
/// send field1, field2, field3 to recepient1
}
};

class Chid2: public Interface
{
public:
void Run() {
/// send field4, field5, field6 to recepient2
}
};
class Chid3: public Interface
{
public:
void Run() {
/// send field7, field8, fieldN to recepient3
}
};
I

need design pattern that can set child members using parent class.