samedi 31 décembre 2022

Is there a proper way to use a Repository class in a Domain Model class in Domain Driven Design?

I have class of Items. These items can have a parent and subitems, which can also have subitems and so on recursively in a tree structure. The price of the Items should be the sum of the prices of all descendant Items. The items at the bottom of the tree structure already have price assigned and are available through the repository.

The repository is used to access a database where the data is structured with columns (Id, Name, ParentId, ChildIds, Price), though I'd prefer not to use SQL to implement domain logic. That's why I'm looking to implement the calculation of the price in the Item class of my domain model, but to perform a recursive search to get all descendants of an item, the item object needs access to a repository Class instance.

The class currently looks like this:


public item(string id, string name, string parentId, List\<string\> childIds)
{
this.Id = id;
this.Name = name;
this.ParentId = parentID;
this.ChildIds = childIds;
}

public string Id { get; init; }
public string Name { get; init; }
public string ParentId { get; init; }
public List<string> ChildIds{ get; init; }
public int Price { get; init => CalculatePrice(this.Id) }

public int CalculatePrice(string id) {
list<Item> descendantItems = _itemsRepository.GetAllDescendants(id);

return descendantItems.Select(i => i.Price).Sum()

}

The only options I see to get access to my repository class both look pretty bad :

  • Pass an instance of the ItemsRepository class to the constructor of my Item class
  • Create a new instance of the ItemsRepository class in my CalculatePrice() method

An alternative I see is to have a field for the list of descendant items and fill it when my item is constructed but it seems like a waste to have all descendant items constructed and available in a field just because I need to assign a price to an item.

The final alternative I'm currently working on is to just get the Sum of the prices of all descendants by using a recursive SQL query in my mapper and to pass the resulting SumPrice to the constructor of the Item. This solves my problem, but it seems counter to Domain Driven Design to implement this business logic in an SQL Query in my Persistence layer.

vendredi 30 décembre 2022

OOD Hotel Management System

i´m Developing a Hotel management system, and i think my current approach about the booking process is wrong, i was wondering if someone could help me design it, so it uses good design principles. I dont feel confident about the bookRoom() method in the Client class, This is the code:

public class Client {
    private String name;
    private String surname;
    private List<Reservation> clientReservations;

    public Client(String name, String surname) {
        this.name = name;
        this.surname = surname;
        this.clientReservations = new ArrayList<>();
    }
    //Should Go Getters and Setters
  
    public void bookRoom(LocalDate startDate, LocalDate endDate, Room room) {
            Reservation reservation = room.addReservation(startDate, endDate, this);
            clientReservations.add(reservation);
    }

----------------------------------------------------------------------

public class Room {
    private String roomID;
    private Category category;
    private int price;
    private List<Reservation> reservations;

    public Room(String roomID, Category category, int price) {
       //Set the values
    }

  //Should Go Getters and Setters


    public Reservation addReservation(LocalDate startDate, LocalDate endDate,Client client){
        if (!isReserved(startDate,endDate)) {
            Reservation reservation = new Reservation(this, startDate, endDate, client);
            reservations.add(reservation);
            return reservation;
        }
        return null;
    }


----------------------------------------------------------------------


public class Reservation {
    private Client client;
    private Room room;

    private LocalDate startDate;

    private LocalDate endDate;

    public Reservation(Room room,LocalDate startDate,LocalDate endDate,Client client) {
        this.room = room;
        this.client = client;
        this.startDate = startDate;
        this.endDate = endDate;
    }

    public Room getRoom() {
        return room;
    }

    public Client getClientName() {
        return client;
    }

    public LocalDate getStartDate() {
        return startDate;
    }

    public LocalDate getEndDate() {
        return endDate;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Reservation that = (Reservation) o;
        return client.getName().equals(that.client.getName()) && room.getRoomID().equals(that.room.getRoomID());
    }

    @Override
    public int hashCode() {
        return Objects.hash(client, room);
    }


}

I tried to apply ood principles, but i am still a little bit lost about the design, i dont feel it flexible.

Observer pattern on all instances of class

I'm trying to learn about the observer pattern, and a case I had thought of is that I want to observe when any instance of a class gets updated, rather than just a singleton. An example I put together is that we have a DeliverySystem observer that wants to know when any Burger is cooked. We could try to accomplish this with the following:

class Burger {
    static observers: Observer[] = [];

    static addObserver(observer: Observer) {
        Burger.observers = Burger.observers.concat(observer);
    }

    id: number;

    constructor(id: number) {
        this.id = id;
    }

    cook() {
        Burger.observers.forEach(observer => observer.update(this));
    }
}

interface Observer {
    update: (target: any) => void;
}

class DeliverySystem implements Observer {
    update(target: any) {
        console.log("DeliverySystem got pizza " + target.id);
    }

    observe() {
        Burger.addObserver(this);
    }
}


const deliverySystem = new DeliverySystem().observe();
new Burger(12345).cook();

This generally works, but I'm not sure how to expand this so that my DeliverySystem can observe other foods. If I add a Hotdog class, what interface can Burger and Hotdog both implement that will allow me to avoid each needing to handle their observers independently? I would like to be able to write Burger like the following, but I'm not really sure how:

class Burger implements Observable /* <-- what does this look like? */ {
    id: number;

    constructor(id: number) {
        this.id = id;
    }

    cook() {
        updateObservers(this);
    }
}

Alternative to multiple instances of pseudo-singleton

I stumbled upon a pseudo-singleton class that is responsible for housing a few collections. It looks something like this:

public class PseudoSingleton {
    private List<Object> collection1;
    private List<Object> collection2;
    private static PseudoSingleton instance = null;

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

    public static synchronized void reload()  {
        instance = new PseudoSingleton();
    }

    private PseudoSingleton() {
        load();
    }
    
    private void load() {
        //parse some files from disk and fill collections
    }
}

The reason it is coded like this is that in a few places in code a comparison of collection1 before and after reload needs to be done.

However this way seems like a major code smell to me.

I tried to refactor the code slightly by making the reload() method not static:

public synchronized void reload() {
   //clear collections
   //load collections
}

In order to be able to compare collection before reload I added a method that needs to be called before reloading the collection:

public List<IfCluType> getCluInterfacesCopy() {
   return new LinkedList<>(clus);
}

However, in review I got a comment that the previous way was better and I should leave it as is. I am not convinced. Should I insist to go my way or leave it? Or is there a better way to code it?

Factory pattern causing circular dependency in typescript

I was using a factory design pattern in my typescript codebase and came across a circular dependency problem. Below is some pseudo-code that represents the problem I'm facing:

// shape-factory.ts
export function createShapeByType(type: string) {
  if (type === 'circle') {
    return new Circle();
  }
  if (type === 'triangle') {
    return new Triangle();
  }
}

// shape.ts
class Shape {
  public type = 'shape';
}

// circle.ts
class Circle extends Shape {
  public type = 'circle';

  public foo() {
    const type = 'whatever'; // imagine here's some code that returns a type string based on some conditions
    const shape = createShapeByType(type); // circular dependency
  }
}

// triangle.ts
class Triangle extends Shape {
  public type = 'triangle';
}

As you can see the foo method in Circle class depends on the factory method, and the factory file depends on Circle, which creates a circular dependency.

I was googling around and most of the answers suggest to refactor out an interface layer, and both the concrete object and the factory only depend on the interface to talk to each other. To my understanding, that solution requires me to pass in the factory implementation through constructor injection or some sort, so that the concrete itself does not depend on the actual implementation of the factory.

My question would be, is there an easier way to solve the problem, other than the solution that I mentioned above? Thank you.

jeudi 29 décembre 2022

How to call a middleware from another middleware in Express JS?

I am working on a middleware restructuring where I am not able to call a middleware from another middleware. This is to avoid messy lines of code in the router level and move them to the function or design pattern level. Below is the example of a router code:

router.post("/v1/user", jwt.auth(), common.checkBasicValidations, auth.checkRBACAccess([auth.access.user], [auth.operation.create, auth.operation.update], auth.checkDomainAccessFromUserEmail, ["email"]), auth.checkRBACAccess([auth.access.user], [auth.operation.create, auth.operation.update], auth.checkDomainAccessFromUserId, ["_id"]), auth.checkAuthorized(), users.postUser);

jwt.auth(), common.checkBasicValidations, auth.checkAuthorized() is repeating almost in every router. To get rid of the above code I did something like this:

router.get("/v1/user", policy.validatePolicies("course"), users.getLoginguserInfo);

policy.validatePolicies("course") is a function which is handling all the above functions sequentially.

const validatePolicies = (category) => async (req, res, next) => {
    try {
        // validate JWT Token
        jwt.auth();

        //fetch users info by email
        req.user = users.sessionUserInfo(req, res, next)

        // validate Payload

        //Validate RBAC Accsess
        rbac.checkRBACAccess();

        //Validate Resourse access
        resource.checkResourceAccess(category)

    } catch (err) {
        log.warn("Problem in validatePolicies: ", err);
        return next(ApiError.internal("Something went wrong")) && next(e.message);
    }
    next();
}

I don't know why jwt.auth() isn't getting call. If you have any suggestions for using a different design pattern or improving the current flow, please share them with me. 

const auth = () => (req, res, next) => {
// varify jwt token
}

module.exports = {
  auth
}

Factory DesignPattern with registering the subclasses using static blocks

I am trying to implement Factory design patter, without using reflection. The goal is, as and when subclasses of Product are added to the project, their instances should be available in the objectPool.

The code is as below : Factory Class

public abstract class ProductFactory {
  protected static final Map<String, Supplier<Product>> productSingletonObjPool = new HashMap<>();

  static {
    /*
    //registering the sub_class-types statically. This obviously works fine.
    productSingletonObjPool.put(ProductOne.class.getSimpleName(), ProductOne::getInstance);
      productSingletonObjPool.put(ProductTwo.class.getSimpleName(), ProductTwo::getInstance);
    */
  }

  public static Map<String, Supplier<Product>> getProductSingletonObjPool() {
    return productSingletonObjPool;
  }

  public static void register(Class type, Supplier<Product> supplier) {
    productSingletonObjPool.put(type.getSimpleName(), supplier);
  }

  protected static Product getInstanceOfType(String type) {
    Supplier<Product> productSupplier = productSingletonObjPool.get(type);
    if (productSupplier != null) return productSupplier.get();
    throw new RuntimeException("No such product with name " + type + " exists");
  }
}

Abstract Product Class

public abstract class Product {


  protected static void register(Class type, Supplier<Product> supplier) {
    if (!ProductFactory.getProductSingletonObjPool().containsKey(type.getSimpleName())) {
      ProductFactory.register(type, supplier);
    }
  }

}

Concrete ProductOne

public class ProductOne extends Product {

  static {
    Product.register(ProductOne.class, ProductOne::new);
  }

  private ProductOne() {}

  protected static Product getInstance() {
    return new ProductOne();
  }
}

Concreate ProductTwo

public class ProductTwo extends Product {

  static {
    Product.register(ProductTwo.class, ProductTwo::new);
  }

  private ProductTwo() {}

  protected static Product getInstance() {
    return new ProductTwo();
  }
}

Test Class

@Test
public void testFactory() {
  Product one = ProductFactory.getInstanceOfType("ProductOne");
  System.out.println("Product One : " + one);
  Product two = ProductFactory.getInstanceOfType("ProductTwo");
  System.out.println("Product Two: " + two);
}

Problem : the Map always gets populated with ProductOne. This behaviour is same as captured in this thread: Fill a hashmap in superclass from subclass constructor in Java However, My code is different than the code from this thread, though it encounters the behavior mentioned in there i.e. map always getting populated with one Supplier (in my case, its ProductOne::new).

I would like to know :

  1. The reason behind this behavior
  2. Any solution for this?

I believe the static blocks get executed when classes are loaded. I expected that static blocks of both ProductOne and ProductTwo be executed and have the productSingletonObjPool map populated with their Suppliers. This didn't happen though...map only got populated with ProductOne's supplier, as if, JVM only looked for 'a' class that extended the abstract Product class and then stopped loading additional classes which extend Product class. I also tried to debug this, but breakpoints on static blocks are skipped by debugger.

I looked into these threads, as prompted by stackoverflow, but didn't find solution to my problem :

Design pattern to return an internal table of various types

The documentation states: return parameters of functional methods have to be fully typed.

I'm trying to dance around that prerequisite in the following case:

I have a program where the user picks an object on screen 1000 and can make various changes to it on screen 2000. The objects that the user can pick are of varied types. The object is presented on screen 2000 in an ALV, where the columns depend on the object's type. The program handles the user actions in mostly the same way no matter the object type.

The way the program is laid out is: an abstract class defines the default behaviour for all object types, then a child-class for each object type redefines methods where needed.

The class handling the object's data has the method get_data_ref(). This method returns a reference to a private internal table from the subclass, that contains an object's data. This internal table is declared in each subclass with a different row type.

An abstract method get_fieldcatalog() returns the fieldcatalog for the given object type. This method is redefined in each of the subclasses.

To display the ALV, I get the table reference from get_data_ref(), assign a field symbol to it and pass the field symbol to the ALV using method SET_TABLE_FOR_FIRST_DISPLAY() along with the fieldcatalog.

It works. But it is wrong.

  • It gives direct access to a private attribute of my class by referencing it. The private internal table can be altered from outside of the class, which is against the abstraction principle.
  • Is it safe ? Could the internal table be freed from memory while a pointer to it still existed ?

Is there a better way to do this ?

How is this drawer effect called?

I'd like to reproduce this drawer effect for scanning barcodes in my app:

Drawer

The drawer:

  • opens as a small preview
  • can be swiped up to cover the whole screen
  • can be swiped down to make it disappear

Is there a name for this pattern?

(video recording of the Yuka app)

Error parsing custom _id type in go mongodb project

I'm building a go project using mongodb as a database.

In order to make the code easily maintainable, i created a mongo provider package that is the single point of contact between my project and mongo-driver/mongo. That way I only use my own implementations in the rest of the project.

I wrapped the whole native driver with my own implementations. The only problem I encounter is with the primitive.ObjectID type.

Obviously, my structures are stored in an internal models package like this :

type StoredUser struct {
     Id       my_mongo_driver.Id `bson:"_id,omitempty"`
     Username string             `bson:"username"`
}

As you see, the models package does not have any contact with the native mongo-driver/mongo package. This is what I want.

In the my_mongo_driver package, I tried reimplementing the Id type by two different ways :

  • type Id primitive.ObjectID
  • type Id struct {primitive.ObjectID}

In both cases, I get an error when parsing the database results :

  • First approach : error decoding key _id: cannot decode objectID into an array
  • Second approach : error decoding key _id: cannot decode objectID into a my_mongo_driver.Id

How can I properly isolate my packages if my models need to use the exact native type for the parsing to work ?

Python Backend Server Design Patterns: Managing multiple databases through one server

I am relatively new to Python design patterns, and would like to ask for input from more experienced developers, on some possible pattern options for managing two independent databases through one backend server.

DB 1 and DB 2 are entirely independent, but there requires certain aspects where data from DB 2 is processed in the backend and used to update parts of DB 1.

I currently have a working singleton pattern which manages the connection for DB 1, but I am reading that a singleton approach is not recommended in most Python development circles.

So, I am considering implementing a few tweaks to the current singleton for DB 1 and making the connection a reserved pool - But this is where the question arises of how to implement DB 2 into the mixture.

Just from a workload and ease of implementation perspective, the simplest solution would be to just create another singleton connection object for DB 2 and just making sure the two connections are separately managed. But from the reading I am doing, it seems this would be bad engineering.

So I would like to ask what are some acceptable ways to design a backend server when managing multiple databases. Any and all directional guides, or simple pointers to factors I should consider would be greatly appreciated.

Thank you much in advance.

End Product

mercredi 28 décembre 2022

How to deserialize to map or array class where map structure varies in Java?

I need to deserialize the response of an external REST API which is usually a JSON object but if an error occurred it will be an array of JSON objects. The API is lacking in documentation so the way I determine if error occurred or not is by the HTTP Status of the response. The problem is that non-error responses have different structure per API route (user response, product response etc.). Another problem is in my application we use an abstract class for external API response with such fields as error, hasError. I solved the problem as follows:

 public abstract class AbsractApiResponse {
  public abstract String getError();
  public abstract void setError(String error);
  public abstract String getDescription();
  public abstract void setDescription(String error);
}

public class ErrorResponse {
  private String errorCode; // getters/setters

  private String message; // getters/setters
}

public class UserResponse extends AbsractApiResponse {

  private String error; // getters/setters
  private boolean hasError; // getters/setters
  private boolean description; // getters/setters
  private String userName;
  private String userEmail;
}


public <R extends AbsractApiResponse> R deserializeResponse(
    String apiResponse, Class<R> responseType, boolean isHttpError)
    throws JsonProcessingException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
  R response;
  Object deserialized = objectMapper.readValue(apiResponse, Object.class);

  if (isHttpError && deserialized instanceof List) {
    TypeReference<List<ErrorResponse>> errorResponseType = new TypeReference<>() {};
    List<ErrorResponse> responseErrors = objectMapper.convertValue(deserialized,
        errorResponseType);
    Constructor<R> constructor = responseType.getDeclaredConstructor();
    response = constructor.newInstance();
    ErrorResponse firstError = responseErrors.get(0);
    String errorDescription = responseErrors.stream().map(ErrorResponse::toString).collect(Collectors.joining());
    response.setError(firstError.getMessage());
    response.setDescription(errorDescription);
  } else {
    response = objectMapper.convertValue(deserialized, responseType);
  }
  return response;
}

With this approach I would have to add fields like error/hasError etc. to every class which represents a response which isn't that bad I guess. Another red flag for me is the use of reflection (responseType.getDeclaredConstructor()) and the 4 checked exceptions that go with it. I'm wondering, if there's a better way to solve this?

Can't implement the command pattern at all in Unity game project

I have been trying to implement a command pattern in my Tennis game unity project, I have tried this for a couple weeks to no avail. First I obviously have my original gamescript that connects to my Player gameobject (Character.cs), then I tried first by implementing am interface (Command.cs), then I created the keycommands (RightCommand.cs, LeftCommand.cs) that extend to said interface, then I created an invoker (invoker.cs) that store the keycommands and implements them, then I tried to use the ivoker and keycommands in my Character.cs class but when I ran it, nothing happened when trying to move left. Here's my code to get a better picture.

Command.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public interface Command 
{
    void Execute();
}

RightCommand.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class RightCommand : Command
{
    Vector3 position;
    float speed = 3f;

    public RightCommand(Vector3 vector)
    {
        position = vector;
    }

    public void Execute()
    {
        position.x -= speed * Time.deltaTime;
    }
}

LeftCommand.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LeftCommand : Command
{
    Vector3 position;
    float speed = 3f;

    public LeftCommand(Vector3 vector)
    {
        position = vector;
    }

    public void Execute()
    {
        position.x += speed * Time.deltaTime;
    }
}

Invoker

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Invoker 
{
    Stack<Command> mCommands;

    public Invoker()
    {
        mCommands = new Stack<Command>();

    }
    public void Execute(Command command)
    {
        if (command != null)
        {
            mCommands.Push(command);
            mCommands.Peek().Execute();
        }
    }
}

Character.cs - here I tried to implement the LeftCommand and invoker to see if it would work with the left arrow key, but it ended up not working for some reason.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Character : MonoBehaviour
{
    public Leftmove left;
    float speed = 3f;
    float force = 10;
    bool hit;
    public Transform target;
    public Transform Tennisball;
    Animator animator;
    private Invoker minvoker;
    // Start is called before the first frame update

  

    void Start()
    {
        minvoker = new Invoker();
        animator = GetComponent<Animator>();
        
    }

    // Update is called once per frame
    void Update()
    {
        Vector3 position = transform.position;
        Vector3 positiont = target.position;

        if (Input.GetKeyDown(KeyCode.F))
        {
            hit = true;
        }
        else if (Input.GetKeyUp(KeyCode.F))
        {
            hit = false;
        }

        if (Input.GetKey(KeyCode.LeftArrow) && hit == false)
        {
            Command command = new LeftCommand(position);
            minvoker.Execute(command);
            
        }

        if (Input.GetKey(KeyCode.RightArrow) && hit == false)
        {
            position.x -= speed * Time.deltaTime;
        }

        if (Input.GetKey(KeyCode.UpArrow) && hit == false)
        {
            position.z -= speed * Time.deltaTime;
        }

        if (Input.GetKey(KeyCode.DownArrow) && hit == false)
        {
            position.z += speed * Time.deltaTime;
        }


        if ((hit == true) && (Input.GetKey(KeyCode.LeftArrow)))
        {

            positiont.x += speed * Time.deltaTime;


        }

        if ((hit == true) && (Input.GetKey(KeyCode.RightArrow)))
        {

            positiont.x -= speed * Time.deltaTime;

        }

        if ((hit == true) && (Input.GetKey(KeyCode.UpArrow)))
        {
            positiont.z -= speed * Time.deltaTime;

        }

        if ((hit == true) && (Input.GetKey(KeyCode.DownArrow)))
        {
            positiont.z += speed * Time.deltaTime;

        }

        transform.position = position;
        target.position = positiont;


       
      
    }

    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Tennis ball"))
        {
            Vector3 dir = target.position - transform.position;
            //Vector3 horizo = transform.position;
            //horizo.y = speed * Time.deltaTime;
            other.GetComponent<Rigidbody>().velocity = dir.normalized * force + new Vector3(0, 10, 0);
            Vector3 side = Tennisball.position - transform.position;
            if (side.x >= 0)
            {
                animator.Play("backhand play");
            }

            else
            {
                animator.Play("forehand play");
            }
            //animator.Play("forehand play");

        }

    }


}

Singleton Pattern Template C++

First thing: I m trying to create a Template class at the beginning and its working well. After I wanted to use the singleton design pattern for many reasons, one of the main reason is because i want to try for a project. But I know that this pattern is to be avoided.

Come back to my issue. I show you the code

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/config.hpp>
#include <iostream>
#include <stdexcept>

template<typename TK, typename TV>
class MultiContainer{
  
  private:
  
  using value_type = std::pair<TK, TV>;
  
  static MultiContainer<TK, TV>* _singletonCacheServer;
  unsigned int _capacity;
  boost::multi_index_container<value_type,boost::multi_index::indexed_by<boost::multi_index::sequenced<>,  boost::multi_index::hashed_unique<boost::multi_index::member<value_type,TK,&value_type::first>>>> _container;
  
  MultiContainer(const MultiContainer&) = delete;
  MultiContainer& operator=(const MultiContainer&) = delete;

  int capacityOut(){
      if( _capacity == 0 || _container.size() < _capacity ) {
        return 0;
      }
      int cnt = 0;
      while(_container.size() > _capacity) {
        _container.pop_back();
        ++cnt;
      }
      return cnt; 
  };

  public:
  
  MultiContainer(int icapacity) : _capacity(icapacity){};
  virtual ~MultiContainer() = default;
  MultiContainer();

  static MultiContainer<TK, TV>* getInstance() {
    if (!_singletonCacheServer) {
        _singletonCacheServer = new MultiContainer;
        return _singletonCacheServer;
    }else{
        delete _singletonCacheServer;
        _singletonCacheServer = nullptr;
    }
  }

  int size(){
    return _container.size();
  };
  bool empty(){
    return _container.empty(); 
  };
  void clear(){
    _container.clear(); 
  };

  bool contains(const TK& key){
    const auto& lookup = _container.template get<1>();
    return lookup.find(key) != _container.template get<1>().end(); 
  };

  void remove_key(const TK& key){
    auto& lookup = _container.template get<1>();
    auto it = lookup.find(key);
    if(it != lookup.end()){
      lookup.erase(it);
    }
  }

  void put(const TK& key, const TV& val){
    auto& lookup = _container.template get<1>();
    auto it = lookup.find(key);
    if( it != lookup.end() ) {
      lookup.modify(it,[&](value_type& x){ x.second = val; });
    }
    else{
      it=lookup.emplace(key, val).first;
    }
    _container.relocate(_container.begin(),_container.template project<0>(it));
    capacityOut();
  };

  std::list<std::pair<TK, TV>>getItems(){
    return {_container.begin(), _container.end()};
  };

  const TV& get(const TK& key){
    const auto& lookup = _container.template get<1>();
    const auto it = lookup.find(key);
    if( it == lookup.end() ) {
      throw std::invalid_argument("Key does not exist");
    }
    return it->second;
  }
};

int main()
{

  //MultiContainer<std::string, std::string>* a1 = MultiContainer<std::string, std::string>::instance();
  auto cache  = MultiContainer<std::string, std::string>::getInstance();
 
}

The error I got was this: a nonstatic member reference must be relative to a specific object

I tried to declare the function using for the singleton as static to solve the problem but it didn't work too well

I came to ask myself if I could use the singleton with templates, I saw several answers, yes and no so no sure.

I would like to have your opinion on my class so that I can succeed in using it. Because its really something i want to try.

ps: I've also seen posts of people using a different class to implement a singleton and putting in that singleton class, the class we want to turn into a singleton. which gives a kind of class in the middle that makes the connection

mardi 27 décembre 2022

Using info from backend in JS

I'm wondering about getting variables from the Express backend into the JS part of a website. I find myself doing the following a lot:

  • Pass some variable I want to use into res.render
  • Put the variable into the HTML as an invisible element with the template engine, ex. in EJS something like <span id="username" style="display: none;"><%= user.username %></span>
  • Get the variable out in the JS with JQuery, ex: const username = $("#username").text();

But I am wondering if there is a better way...I mean you can't just put anything into the HTML, and I'd prefer to put less just in case...

For example I was making a study course and I wanted to make one call to the DB to get lesson content. But I don't want to put all the lesson content on the page in a hidden element, and I don't want to query the DB for every question. And I don't want to reload the page for every question either, so I'd like to use JS to change the questions...is there some design pattern or common solution for this situation?

How does compiler know if a variable is spilled in code generation?

I am implementing a compiler using visitor pattern.

Here is the general algorithm I use.

regs gives the number of registers needed and top give the next free register.

generate(T,n) =
    if T is a leaf write ``load top(), T"
    if T is an internal node with children l and r then
    if regs(r) = 0 then { generate(l); write ``op top(), r" }
    else{
        generate(l,n)//Stored in Rn
        generate(r,n+1)//Stored in Rn+1
        write "op Rn, Rn+1" // rresult is stored in Rn
        push(R) }

But in the case where there's not enough registers, we need to spill variables. Suppose we use a greedy allocator that spills the last used register. It means that, when we generate(r) if there's no register left to store the result, we push Rn to the stack and store result in Rn and then retrieve spilled variable to compute the operation.

The complete schema become:

generate(l,n)//Stored in Rn
push Rn // push to stack
generate(r,n)//Stored in Rn 
mov Rn R0 // move
pop Rn // retrieve from stack
write ``op Rn, R0" // result is stored in Rn

What I tried is to modifty the function top to make it return a register if any available and push last register before returning it if no-one is available so when generating r children, we can save to stack if there's no space...

generate(l,top())//Stored in Rn
generate(r,top())//Spill if no space and store in Rn 
mov Rn R0 <--- my problem is here
pop Rn <--- my problem is here
write ``op Rn, R0" <---my problem here

But after generation of l and r, how does the operation knows that it needs to unspill* some variable (if it has to) ?

My question is :

Programmatically, how can I implement it in the compiler to make it oblivious to operation code.

Ideally ... code should look like:

generate(l,something())//Stored in Rn
generate(r,something())
write ``op somethingelse(), againsomethingelse()" <--- taking into account when space is available or not

lundi 26 décembre 2022

Can't configure spring-boot test with @DataJpaTest

I have below a simple test. I want to run this one with an embedded database H2 but I have an exception. This expeption happens because context checks connection to a production database and I don't want the context to do it because it's unnecessary. The context tries to connect to a database which doesn't even exist. This database in GCP. I have this exception "com.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: Permission denied on resource projectcom.google.api.gax.rpc.PermissionDeniedException: io.grpc.StatusRuntimeException: PERMISSION_DENIED: Permission denied on resource project".

I've already tried to user @ActiveProfiles and properties in application-test.yml but it didn't work.

So, how can I avoid calling my production database?

@DataJpaTest
//@ActiveProfiles("test")
class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    void getAll() {

    }
}
    <dependencies>
        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter-sql-postgresql</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter-secretmanager</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <version>2.4.2</version>
        </dependency>
        <dependency>
            <groupId>com.google.api-client</groupId>
            <artifactId>google-api-client</artifactId>
            <version>1.32.1</version>
        </dependency>
        <dependency>
            <groupId>com.google.firebase</groupId>
            <artifactId>firebase-admin</artifactId>
            <version>7.1.0</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>com.nimbusds</groupId>
            <artifactId>nimbus-jose-jwt</artifactId>
            <version>9.8.1</version>
        </dependency>

        <!--Test-->
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2020.0.6</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.google.cloud</groupId>
                <artifactId>spring-cloud-gcp-dependencies</artifactId>
                <version>2.0.11</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

application-test.yml

spring:
  profiles:
    active: test
  jpa:
    database: h2
    show-sql: true
    hibernate:
      ddl-auto: create-drop
  datasource:
    url: jdbc:h2:mem:testDb
    driver-class-name: org.h2.Driver
  h2:
    console:
      enabled: true

Best react design patterns for code reuse [closed]

I am working on a project and I am trying to decide on the best react design pattern for code reuse .. please suggestions, pros and cons for your desired pattern .

The render props, react hooks and higher order component patterns are all beautiful patterns for code sharing..in your opinion which is best and why ?

dimanche 25 décembre 2022

which design pattern is appropriate for reading data from api and updating to data bases?

net core application. I have list of ids which I need to pass to multiple api as input parameters which then returns values which i need to update in multiple tables. In short

lets consider I have list with ids 1,2,3 List list = new List(){1,2,3}

foreach(int data in list)
{
 here pass 1 to multiple apis
 1. api1(with input parameter 1) which returns data
    update to table
 2. api2(with input parameter 1) which returns data
    update to table
}

Here my list may contains 5000 ids in total and which may need to call 3 apis to fetch data and update in table. I am looking for best design pattern which suits to this requirement. I had gone through CQRS pattern not sure that will work here appropriately. can anyone suggest me best design pattern? Any help would be appreciated. Thank you

samedi 24 décembre 2022

WAP to print the given pattern in python

the pattern is - 1 2 9 3 8 10 4 7 11 14 5 6 12 13 15 try to get the above pattern using loops..

I personally tried the above pattern but wasn't able to find a accurate logic that can be used to solve the given pattern..

Singleton pattern. what can replace it? [closed]

I use a singleton in my project, as it is convenient for use in other classes.

But more and more I see that people do not like him

what is it connected with? And if it's so bad, what can replace it?

ok, I'll ask in a different way, what do you replace singleton with?

    class A {
        constructor() {
             this.context = new B().GetContext()
        }   
        ...
    }

    class B {
        constructor() {
             if(B.inst)
                return B.inst
             B.inst = this
             this.context = 'context'
        } 
        GetContext(){
          return this.context
        }
    }

    class C {
        constructor() {
             this.context = new B().GetContext()
        } 
       ...
    }

// and more class use B.GetContext()

Scoping Microservices

Dears,

we build two microservices the first is a notification microservice that is responsible for sending and handling notifications like SMS, Email, and App notification ...etc and the second is a service catalog to define the information and configuration of services like service name, description, activation status active or not and ...etc.

My question is if I have configuration about service like allowed notification types that can be used by the service for example service A can send only SMS, and Serivice B Can send Email & SMS.

what is the proper service to define this configuration?

set this configuration as metadata in the service catalog or set in the notification as configuration

vendredi 23 décembre 2022

How to implement inheritance,polymorphism, abstraction and interface in a program? [closed]

beginner here. I'm doing a restaurant sale system, where i can manage the stocks and input order from the customer. I understood all the basic principles of OOP above, but i don't know how to implement them in this program. Can anyone explain briefly to me?

How do I design an Actor model?

I am trying to implement an Actor model in Java.

I have started with the following class diagram.

As you can see, the ActorRunner created in the ActorContext is responsible for controlling the life cycle of the actors: it has the message queue and it calls the process() method of the actor for each received message in its loop (run()). Actors simply implement the Actor interface with the single process() method.

Now, I want to add a decorator (Decorator pattern) and be able to decorate the send() and process() methods. However, since the Actor interface does not have the send() I cannot decorate it and spawn a decorated actor with ActorContext.spawnActor().

How can I modify the design to suit my needs?

Is there ready-made solution to get css styles of any website? [closed]

Can you recommend online services/libraries/tools/programs to get the style of any site? By site style, I mean: fonts, font colors, logo, main color for the site and other design elements. Roughly speaking, get the CSS component.

I have seen many guides that describe how to do it manually. But I would like to use a ready-made solution.

Overridable struct of params

I'm trying to find the most optimal way of doing the following. I have a big hierarchical structure of heterogeneous parameters like this (just as an example)

struct ServiceParams {
    struct FilterParams {
        bool remove_odds;
        bool remove_primes;
    }
    size_t length;
    std::optional<float> threshold;
    FilterParams filter_params;
}

The service which uses these parameters fills the values from a config file while starting, and then the service allows a user to provide their own parameters via request:


class Service {
    ServiceParams default_params;
    bool HandleRequest(Data data, std::optional<ServiceParams> user_params) {
         return DoSomeStuff(data, user_params.value_or(default_params))
    }
}

So the question is: what is the best way of allowing user to specify only some part of user_params and use other params stored in default_params.

What I did consider so far:

Dynamic structure like std::map<std::string, std::any>

I could use std::map<std::string, std::any> for parameters and just loop (recursively) through user provided key-value store and override all the parameters which were specified.

The main drawback is: hard to read and understand the code and static code analysers wouldn't show me the places where a certain parameter is used. And I need to provide getters for each of the parameters.

Make all the params to be std::optional
struct OptionalServiceParams {
    struct OptionalFilterParams {
        std::optional<bool> remove_odds;
        std::optional<bool> remove_primes;
    }
    std::optional<size_t> length;
    std::optional<std::optional<float>> threshold;
    std::optional<OptionalFilterParams> filter_params;
}

Drawback: but I don't want the inside implementations be bothered by these std::optional-s. It's not their job to extract contained values all the time.

Use both: the current and with std::optional-s

I can create the above optional structure for user's requests and user the current params structure for the inside implementation.

Drawback: I need to override all the parameters manually one by one

auto params = default_params;
if (user_params.length.has_value()) 
    params.length = user_params.length.value();
if (user_params.threshold.has_value()) 
    params.threshold = user_params.threshold.value();
if (user_params.filter_params.has_value()) {
    if (user_params.filter_params->remove_odds.has_value())
        params.filter_params.remove_odds = user_params.filter_params->remove_odds.value();
    if (user_params.filter_params->remove_primes.has_value())
        params.filter_params.remove_primes = user_params.filter_params->remove_primes.value();
}

It's easy to make a bug and it's hard to maintain and scale. And of course it's a lot of code duplication.

Make the above two structures as one but template

We could make it as (truncated, the question becomes too long)

template <template <typename ValueType>, typename...> typename Container = std::type_identity_t>
struct ServiceParams {
    Container<size_t> length;
    Container<std::optional<float>> threshold;
}

and use it like this

ServiceParams<> default_params;
ServiceParams<std::optional> user_params;

Now I can use default_params just as is (inside implementation) and there is no code duplication. Drawback: it doesn't solve the problem with manual overriding all the params. And in contrast with the previous approach it's almost impossible to support designated initialisers here.

Resume

The other languages (e.g. python) provides reflection and I can treat a structure as a key-value store without a need of making getters. Plus static code analysers shows me the places where a certain parameter is used.

I'm 100% sure some classic approach exists but I failed to find it online.

jeudi 22 décembre 2022

How would you create a sticky drawer/bottom drawer/slide-out component with MUI?

I'm using MUI v5, and I'm not entirely sure what this type of UI is called (where there's a drawer-like/slide-out component in the bottom right hand of your screen):

Twitter messages drawer example another drawer example

Name of component aside, how would I build this with MUI? Would it be best to use the <Drawer /> component, or some other UI element for it?

Desktop app design pitfalls in WPF and other subsystems [closed]

Have you experienced any recurring pitfalls novice developers fall into in how they design their desktop applications on a higher level, that make it hard for more senior developers to interact with their markup or code-behind, which you would like to share? What are their consequences?

These could be examples of directly misapplying or misinterpreting design patterns, principles and methodologies, or other issues you find insightful and that are remediable if beginners become conscious of them.

Very interested in WPF, but all universal examples applicable to desktop development are welcome.

[Redux/Ngrx][Design-pattern][Good practise] Do a get after each update/delete?

I'm faced with a problem for which I couldn't find documentation on good practise.

I have a list of items which can be updated or deleted and I'm using a store to manage it.

When updating/deleting an item, should I remove it from the store's list on backend sucessfull response, or should I do a full get to populate my store with the actualised list ?

If you have some pertinents links for me I'm all ears :)

Thanks !

mercredi 21 décembre 2022

Good practises when designing a C++ application that may run a GUI [closed]

I would like to be sorry before anything, since this question is probably solved but I can't get to a concise answer since I'm not sure what exactly to search and English is not my first language.

I'm building an app in C++ which works reasonablly well, however since the beginning I knew that I would like to add a GUI to it so I started developing both "front-end" and "back-end" at the same time. (The GUI I have chosen actually is a command-line GUI named FTXUI) Although the GUI was not mandatory I did add it to get my feet wet since this is my first GUI ever developed.

I quickly realized that all problems scalated quickly like a snowball, mostly related to parse the app data to the GUI and vice-versa, and keeping control of program flow jumping from one page to another. That is why I was wondering how this is normally designed. I do not mean exactly program or code, but approaches and design methods to propper communication between them efficiently.

Just as an example, I've made a page meant to be a "Login" page. The whole page is executed as a function with two pointers as parameters. Those pointers are where I dump the user's inputs as std::string once the user clicks a "Login" labeled button, the program returns to the main program, processes those strigns and calls for the next page (Which is also a whole function...) This is working as intended, but something is yelling and I'm not sure what. If I need to access a lot of bytes of data (Which I actually need in another page) I ended up building a class to hold that data and parse that instance (as reference) to the page to later format needed data on screen.

I've read in another post about a concept like "Server-Client", where the GUI is executed on the client and exchanges data with the server where the actual program is running. I found it interesting, and that's what I am asking for I guess. Design patterns for GUI's.

  1. When starting a project like this, should GUI and main program developed independently? How Can I "connect" them afterwards? How can a GUI page access to the main program data in C++ without parsing everything?

  2. Which side of the application should be developed with preference, the main program or the GUI?

  3. Can I add a GUI to an already working project?

  4. Should a program like this work either with a GUI or exclusively command line at the same time? I mean, should it be designed to work without a GUI (Despite knowing that this GUI will eventually exist)?

  5. At the moment my GUI and its pages are held in a class called MyGUI. This class has an attribute called _currentPage which holds an enum type called pages. All GUI pages return the next page to be shown and store it in _currentPage (f.e., LOGIN_PAGE, MAIN_MENU...) Another method of this class called show just have a switch-case statment with said variable calling the corresponding page function. As I said, I can see the problem here but I'm not sure how this "page management" is normally handled.

  6. Talking about pages, a GUI is supposed to have a unique page for every possible case? I mean, show "Login Page", then show "Main Menu Page", where you can go to (for example) "Settings page"... each one of them as a different entity with its own implementation.

Thanks in advance and again, sorry for the long question.

I'm expecting to have not a fancy and nice-looking GUI (That's a different topic) but a nice, clean, scalable and maintainable code to newbie-GUI's. I'm guess that the language here is not that critical since is not a problem about code, but design.

How to create an interface in C that can work on two identical structs with differently named fields

Question Background

Consider a scenario in which I have two structs. Both consist of three fields for doubles. The only difference is the names used to refer to these fields. The first struct is for non-descript Tuples and the components are to be named x, y, and z. The second struct is for RGB values and the components are to be named red, green, and blue. Both of these structs need to have an interface defined for them such that operations such as vector/componentwise addition and scalar multiplication can be performed.

The Question

The problem? It seems terribly inelegant to copy and paste identical code for both of these structs only to change the naming scheme (x vs. red, y vs. green, z vs. blue). Ideally it would be possible in the interface function definitions to reference the fields of the struct (x or red) without having to name the field. Is this possible? If not then what other options are avaiable to me without changing the requirements? I include the struct definitions below along with some examples of their desired use with the possibly impossible interface I describe in this question.

Non-descript Tuple Struct

typedef struct
{
    /** The first coordinate */
    double x;

    /** The second coordinate */
    double y;

    /** The third coordinate */
    double z;

} Tuple;

RGB Tuple Struct

typedef struct
{
    /** The first coordinate */
    double red;

    /** The second coordinate */
    double green;

    /** The third coordinate */
    double blue;
} Tuple;

Example Usage

Tuple * genericTuple = createVector( 1, 2, 3 ); // create a generic Tuple
printf("%lf", genericTuple->x); // should print 1

Tuple * rgbTuple = createColor( 1, 2, 3 ); // create an rgbTuple
printf("%lf", rgbTuple->red); // should also print 1

What should I do when I want a heavy method executed in constructor?

I have a heavy method to run before any other methods in the class, because I need to initialize something (e.g: getting some data from a database and initialize some fields in the class).

I have Provider1 class like this :

public class Provider1
{
    private readonly string _connectionString;
    private readonly List<string> _data;
    private bool _isInitialized;

    public Provider1(string connectionString)
    {
        _connectionString = connectionString;

        // Nothing else to do here 
        // And the caller should to know to call the `Initialize` method him/herself
        // If he/she forgot to Initialize, then I will throw an exception
    }

    public void Initialize_HeavyWorkButItMustBeExecutedBeforeAnyOtherMethods(params string[] tableNames)
    {
        // _data = filling _data from a database

        // 
        _isInitialized = true;
    }

    public void Method_WorkWithData()
    {
        // At this point, I want to be sure that `_data` already populated
        // what should I do?

        // e.g: using a field to determine the initlization:
        if (_isInitialized)
        {
            // Do some works
        }
        else
        {
            throw new Exception("You have to initialize first");
        }
    }
}

And I have Provider2 class as below:

public class Provider2
{
    private readonly string _connectionString;
    private readonly IEnumerable<string> _tableNames;
    private readonly List<string> _data;

    public Provider2(string connectionString, params string[] tableNames)
    {
        _connectionString = connectionString;
        _tableNames = tableNames;

        // call initialize method here in constructore, so the caller don't need to call it seperately
        Initialize_HeavyWorkButItMustBeExecutedBeforeAnyOtherMethods();
    }

    private void Initialize_HeavyWorkButItMustBeExecutedBeforeAnyOtherMethods()
    {
        // _data = filling _data from a database
    }

    public void Method_WorkWithData()
    {
        // Do some works
    }
}

And this is the caller's class:

void Main()
{
    // 1 :
    var theProvider1 = new Provider1("....");

    // The caller have to call this Initialize method before any other methods: 
    theProvider1.Initialize_HeavyWorkButItMustBeExecutedBeforeAnyOtherMethods("table1", "table2", "table3");

    theProvider1.Method_WorkWithData();

    // 2 :
    var theProvider2 = new Provider2("....", "table1", "table2", "table3");
    
    // The caller don't need to initialize anything, because everything happened in one place (constructor)
    // and he/she can call the business method
    
    theProvider2.Method_WorkWithData();
}

What is the best way to initialize a complex object before calling any other methods in the class?

Test Report Generation [closed]

I have a use case to write code to test some functionality and then generate report in a File. To do this i have an api exposed which will take some inputs(string) and then should return the downloadable result file. Am using API Gateway + Lambda for this use case. Now after running tests , am pushing the collected information(pass/fail, error message, req and response) in the string list.

My question is how should i push all those collected information in a file(text or pdf) and then return that as an api response.

Thanks in advance!

mardi 20 décembre 2022

How write a compiler to handle operations using interpreter design pattern?

I am writing a simple compiler using the interpreter design pattern. My problem is how to handle how variables are stored in the compiler.

The syntax tree is compiled recursively using the method compile having the compiler as context to provide registers and spill used registers if necessary.

Let's take an example (the function compile of the class Add representing an addition)

def compile(compiler):
    this.leftOperand.compile(compiler) #compile left operand 
    this.rightOperand().compile(compiler) # compile right operand 
    compiler.add(ADDINSTRUCTION(valueleft,valueright))

The use cases are:

  • both the left and right operand are complex instructions thus stored in registers
  • left operand is a simple value (float or int) and not saved in register but used directly
  • there's not enough registers left for "right operand" so left operand result is spilled and retrieved later for for addition

My question is:

Is there an elegant scheme to apply so that the compiler should know what are valueleft and valueright (taking into account those use-cases) ? I am looking for the data structures I must use either in expressions themselves or the compiler.

The solutions I thought about are :

#1

make compile return where (in which register) the computation has been stored. But this doesn't work in case a previously stored computation is spilled to the stack (then unspilled in R0).

#2

Saving the two most recent used registers (it would take into account unspilling) but I doubt this scheme would last.

ex:

valueright = compiler.lastUsedRegister 
valueleft = compiler.beforelastUsedRegister 

but I doubt this scheme will last.

Is there some elegant solution for this problem ?

Implementing the decorator pattern in C#

i'm trying to implement the decorator pattern in C#. I'm creating a notification system that decorates the notification to be sent at runtime. I have this classes : `

namespace NotificationHub.Domain.Hubs
{
    public interface INotificationHub
    {
        public Task SendMessage(Notification notification);
    }
}

and it's implemented by 4 classes : BasicNotificationHub

namespace NotificationHub.Domain.Hubs
{
    public class BasicNotificationHub : INotificationHub
    {
        public async Task SendMessage(Notification notification)
        {
            await Task.FromResult(0);
            Console.WriteLine($"Basic Notification Behavior Called for {notification.ProductID}");
        }
    }
}

SignalR

   public class SignalRDecorator : INotificationHub
    {
        private readonly IHubContext<ProductNotificationHub, INotificationHub> _signalrNotificator;

        private readonly INotificationHub _notificationHub;

        public SignalRDecorator(IHubContext<ProductNotificationHub, INotificationHub> hubContext, INotificationHub notificationHub)
        {
            _signalrNotificator = hubContext;
            _notificationHub = notificationHub;
        }


        public async Task SendMessage(Notification notification)
        {
            await _notificationHub.SendMessage(notification);

            await _signalrNotificator.Clients.Group(notification.ProductID).SendMessage(notification);
        }
    }

SmsNotification

    public class SmsDecorator : INotificationHub
    {
        private readonly IUserService _userService;

        private readonly INotificationHub _notificationHub;

        public SmsDecorator(IUserService userService, INotificationHub notificationHub)
        {
            _userService = userService;
            _notificationHub = notificationHub;
        }

        public async Task SendMessage(Notification notification)
        {
            List<string> phoneNumbers = await _userService.GetUserPhonenNumbersSubscribedToProduct(notification.ProductID);

            await _notificationHub.SendMessage(notification);

            await SendMultipleSms(phoneNumbers, notification.ProductID, notification.ProductName);
        }

        private async Task SendMultipleSms(List<string> phoneNumbers, string productID, string productName)
        {
            foreach (string phoneNumber in phoneNumbers)
            {
                await SendSms(phoneNumber, productID, productName);
            }
        }

        private async Task SendSms(string phoneNumber, string productId, string productName)
        {
            await Task.FromResult(0);
            Console.WriteLine($"Sending Sms to {phoneNumber} about product {productId} {productName}");
        }
    }

And Mailing

    public class MailDecorator : INotificationHub
    {
        private readonly IUserService _userService;
        private readonly INotificationHub _notificationHub;

        public MailDecorator(IUserService userService, INotificationHub notificationHub)
        {
            _userService = userService;
            _notificationHub = notificationHub;
        }

        public async Task SendMessage(Notification notification)
        {
            List<string> mailsList = await _userService.GetUserMailsSubscribedToProduct(notification.ProductID);

            await _notificationHub.SendMessage(notification);

            await SendMultipleEmailAsync(mailsList, notification);
        }

        private async Task SendMultipleEmailAsync(List<string> mailsList, Notification notification)
        {

            foreach (string mailAdress in mailsList)
            {
                await SendEmailAsync(notification, mailAdress);
            }
        }

        private async Task SendEmailAsync(Notification notification, string mailAdress)
        {
            await Task.FromResult(0);
            Console.WriteLine($"Mail sent for product {notification.ProductID} to user {mailAdress}");
        }

    }

`

And the decoration happens in my service : `

    public class InMemoryProductService : IProductService
    {

        private readonly List<Product> _products;
        private IServiceProvider _serviceProvider;

        public InMemoryProductService(IServiceProvider serviceProvider)
        {
            _products = new List<Product>
            {
                new Product
                {
                    ProductId="P01",
                    ProductName="Cool Product",
                    Description="World coolest Product",
                    Price=9.99m,
                    Stock=10,
                    OnSale=false
                },
                new Product
                {
                    ProductId="P02",
                    ProductName="Cool Expensive Product",
                    Description="World coolest expensive Product",
                    Price=999.99m,
                    Stock=0,
                    OnSale=false
                }
            };

            _serviceProvider = serviceProvider;
        }

        public Task<List<Product>> GetProducts()
        {
            return Task.FromResult(_products);
        }

        public async Task UpdateProduct(Product product)
        {
            var foundProduct = _products.FirstOrDefault(x => x.ProductId == product.ProductId);

            if (foundProduct != null)
            {
                INotificationHub notificationHub = GetNotificationHubs(product, foundProduct);
                await notificationHub.SendMessage(new Notification
                {
                    ProductID = product.ProductId,
                    ProductName = product.ProductName,
                    Message = "i did it"
                });
            }
        }

        private INotificationHub GetNotificationHubs(Product product, Product foundProduct)
        {
            INotificationHub notificationHub = new BasicNotificationHub();

            if (product.Stock > foundProduct.Stock)
            {
                notificationHub = new SignalRDecorator((IHubContext<ProductNotificationHub, INotificationHub>)_serviceProvider.GetService(typeof(IHubContext<ProductNotificationHub, INotificationHub>)), notificationHub);
            }

            if (product.Price != foundProduct.Price)
            {
                notificationHub = new MailDecorator((IUserService)_serviceProvider.GetService(typeof(IUserService)), notificationHub);
            }

            if (product.OnSale != foundProduct.OnSale)
            {
                notificationHub = new SmsDecorator((IUserService)_serviceProvider.GetService(typeof(IUserService)), notificationHub);
            }

            return notificationHub;
        }
    }

`

Is this a good way to do it ? I'm doubting the part where i return the INotificationHub i don't like the fact that i call _serviceProvider.GetService().

If this is not good do you have any suggestions ?

Is there a combination of state and template design patterns?

I was wondering, if there is a way to combine state and template design patterns with each other?

So that you are able to change the possible states by property. For example a testing algorithm with multiple test states and different characteristics of them based on the guidelines of each country.

Does a pattern exists for that purpose? Does that make sense in any way? Is it easy to combine them?

lundi 19 décembre 2022

How can I efficiently dequeue custom table view cells in CellForRowAt function to avoid break Open-Closed Principle?

I am using a tableview having 8-10 custom tableview cells currently, In Future, we are planning to add more cells. Currently my CellForRowAt Function Looks like this

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
          let cell = tableView.dequeueReusableCell(withIdentifier: "firstCell", for: indexPath) as! FirstCell
            cell.configure(data: self.firstCellData)
            return cell
        } else if indexPath.row == 1 {
           let cell = tableView.dequeueReusableCell(withIdentifier: "secondCell", for: indexPath) as! SecondCell
            cell.configure(data: self.secondCellData)
            cell.productSpecificationsTableViewHeight.constant = cell.productSpecificationsTableView.contentSize.height
            return cell
        } else if indexPath.row == 2 {
        }.... 


and so on.. upto 10 Cells. is there any Software Engineering principle to do this in an efficient way without modifying view controller code.

I am thinking of creating a model for each Cell and pass indexPath.row and Custom Table View Cell in that class but still I have to use if-else blocks in that model too. Is there any other efficient way to do it without continuous use of if-elseif blocks and breaking OCP.

PHP cast object in simple ORM

I would like to make a simple ORM in PHP for standard CRUD interaction with my db, I also want make it work in php5 for legacy compatibility.

I've written some classes to do this and it works, but not completely as I would.

This is the idea. I have an abstrac class called ModelBase which has a property (tableName) and some metods like select, insert, update and delete, plus has an abstract method, getData, that will be implemented by the classes that will be implement ModelBase and should return object of correct type.

So, for example, I could have a class Users which implements ModelBase and one another class UserData which is the model with the property.

Here is the code:

abstract class ModelBase{
   private $tableName;

   public function __construct($tableName) { 
        $this->tableName = $tableName;
   }

   public function select{
       // make select query to db and retreive data
       // ...

       $resData = [];
       while($dataRow = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
           $resData[] = $this->getObjectData($dataRow); // implemented in child class
       }
       return $resData;
   }

   public function insert(){ /* ... */}
   public function update(){ /* ... */}
   public function delete(){ /* ... */}
   abstract function getObjectData($data); // maps the results
}

class UserData {
   public $id;
   public $name;
   public $surname;
   public $email;
   // other fields

   public function __construct() {}
}

class User implements ModelBase {
    private $tableName = 'users';

    public function __construct() { 
        parent::__construct($this->tableName);
    }

    public function getObjectData($dataRow) {
        $o = new UserData ();

        // mapping dataRow to object fields
        $o->id = $dataRow['ID'];
        // ....

        return $o;
   }
}

So I use my classes in this way:

$users = new Users();
$u = users->select();
$firstUser = $u[0]; // I get my user if exists

In $firstUser I'll get my object with property and correct data but I would like to have that also my IDE (vsCode in this case) would recognize the object type in order to suggest the correct properties. So if I write $firstUser-> I would like to see field suggestions (id, name, surname, ...) from UserData and for other xyzData classes as well.

What I should do to improve my classes in order to see property suggestions when I use my objects, also in php5?

Is there an interface "ISingleton" I could use for creating a singleton class? [duplicate]

As mentioned in this other question, I'm looking for a way not to create always another instance of a class. I know this can be done, using a singleton.

As I've seen that quite some design patterns are handled by C# libraries, I believe this should be the case for the singleton design pattern, but I don't find an ISingleton interface, which I could implement.

Does anybody know in which library using which_library; I can find an ISingleton interface or should I create a singleton class from scratch?

dimanche 18 décembre 2022

Best way to decouple project from packages that I use as trait

I have a model in my project called Employee and it has a hierarchical structure(each employee may has some superior or inferior employees).

So I use a package that implement this hierarchical structure by utilizing nested set model.

The Employee model must use this package as trait(NodeTrait). But it may be needed to change the algorithm and so the package I currently use, in the future.

What's the best way to decouple this model from the package I use for implementing hierarchical structure?

This is current code:

class Employee
{
    use NodeTrait;

    public function addChild(Employee $child){
        $this->appendNode($child);
    }

}

In this code appendNode is a method of NodeTrait but I want to write a code that doesnt depend on NodeTrait methods, instead have an interface with some methods such as addChild and call those methods in methods of Employee class.

How should I build the methods of a Director class following the principles of SOLID

I'm studying creational design patterns. In the code below is the CommandDirector class. Following the builder design pattern, its only function is to set the processes it must execute to the command object's builder.

public class CommandDirector {

    public void createAddCommand(CommandBuilder builder) {
        builder
            .addProcess(new Process1())
            .addProcess(new Process2())
            .addProcess(new Process3());
    }
    
    public void createRemoveCommand(CommandBuilder builder) {
        builder
            .addProcess(new Process1())
            .addProcess(new Process3());
    }
    
    public void createUpdateCommand(CommandBuilder builder) {
        builder
            .addProcess(new Process1())
            .addProcess(new Process2());
    }
    
    public void createListCommand(CommandBuilder builder) {
        builder
            .addProcess(new Process2())
            .addProcess(new Process3());
    }
    
}

My question is whether this implementation follows the principles of SOLID. Because it also ends up having the function of creating the objects of the processes. Should I delegate the function of creating Process objects to a Process Factory?

Adaptor pattern in golang

Trying to create adaptor pattern in Golang, Not sure where I am doing wrong. My client.go showing an error
c.broker.placeOrder undefined (type exchange.Exchange has no field or method placeOrder)

main.go

package main

import (
    "context"
    "oms/consumer"
)

func main() {
    ctx := context.Background()
    consumer.Consumer(ctx)
}

consumer.go

package consumer

import (
    "context"
    "fmt"
    "oms/broker"
)

func Consumer(ctx context.Context) {
    broker.Execute()
}

client.go

package broker

import (
    "oms/broker/exchange"
)
type Client struct {
    broker exchange.Exchange
}

func (c *Client) SetBroker(broker exchange.Exchange) {
    c.broker = broker
}

func (c *Client) placeOrder(id string, quantity, price int) {
// I am getting error here
    c.broker.placeOrder(id, quantity, price)
}

broker.go

package broker

// create a Client and set its broker to Paytm
import (
    "oms/broker/paytm"
)

func Execute() {
    client := &Client{}
    client.SetBroker(paytm.Paytm{ /* fields */ })
    client.placeOrder("order1", 10, 100)
}

exchange.go

package exchange

type Exchange interface {
    placeOrder(id string, quantity, price int)
}

paytm.go

package paytm

import "oms/broker/exchange"

type Paytm struct {
    // fields
}

func (p Paytm) placeOrder(id string, quantity, price int) {
    // implementation for Paytm's placeOrder method
}

samedi 17 décembre 2022

How to make generic object to accept two different class models

I want to have 2 very similar classes that will have some common behavior, but different properties, so I need to make these two classes Invoice and CreditNote to be under "one generic object" in this case called model

I was thinking to implement a inteface which will be having input object type like:

public interface IInvoice<T>
{
    T InvoiceType { get; set; }
}

But Im not quite sure if this is the way for this. Ultimately, I would like instancing these classes from interface: IInvoice = new Invoice();

Here is an example:


//380-invoice
if(Convert.ToInt32(invoiceType) == InvoiceTypeCodeEnumDto.Invoice.Id)
{
    Invoice model = new Invoice();
    model.RequestId = request.CorrelationId;
    model.SendToCir = "Auto";
}

//383-creditNote
if (Convert.ToInt32(invoiceType) == InvoiceTypeCodeEnumDto.CreditNote.Id)
{
    CreditNote model = JsonConvert.DeserializeObject<CreditNote>(request.Content)!;
    model.RequestId = request.CorrelationId;
    model.SendToCir = "Auto";
}

model.Name = "foo"; // not accesible

vendredi 16 décembre 2022

Alternative to Thread.sleep() for for better performance

I have developed a REST service. The service have one Api endpoint: v1/customer. This Api does two things:

  1. It executes the business logic in main thread
  2. Spawns a child thread to perform the non critical DB writes. The main thread returns response to client immediately, whereas the child thread write to DB asynchronously.

As both of the these operations Step 1 and 2 are not synchronous, it is becoming increasingly challenging to test both of these scenario. Let's say when I try to test the API. I am testing two things (api response and DB writes) As the DB writes happen async fashion. I have to use a Thread.sleep(2000). This process is not scalable and doesn't yield right result. Soon I might have 1000 test cases to run and the total time to run all these testcases will increase enormously. What design technique shall I use to test the DB writes keeping performance and execution time in mind.

How to solve a dependency between Base and Derived class data

So I have this class kind of class:

class Base
{
public:
Base() { task_ = std::thread(&DexHandlerBase::running_task, this); }
virtual ~Base(){ /*send signal to task_ to stop then */ task_.join();}

protected:
virtual int some_check(int) = 0;

private:
void running_task() { some_check(123); }
std::thread task_;

}

class Derived
{
protected:
int some_check(int) override; //here I use my_data

private:
std::string my_data = "test";
}

An exception spawn up sometimes when the program close.

My guess is that the default Destructor of derived is called, Derived default destructor run and then my_data get destructed. Then the Base class destructor is called and it signal the thread that its going to be destroyed and wait. But the thread is running a task that is a call to a virtual function , this function use my_data that no longer exist.

So there is a dependency from the Base class to the Derived class data. I dont want to move data up, and the function has to be virtual. Shall I override the destructor in each derived class so it closes the thread or is there a better design for this ?

From where do I call different services (controller or directly in the service)?

I have an architecture question about my Laravel application. I have the entity post. Then I use the spatie package "spatie/laravel-tags":"^4.3". When I want to create a post I send my request against the Laravel interface. The route forwards to the controller. The controller forwards the request body (the form data) to the PostService. The PostService forwards the data to the PostRepository. The repository creates the new post and returns it to the service. Now I want to attach the tags to the post. My question. Do I call the TagService in the PostService? Or should the PostController do that?

jeudi 15 décembre 2022

Best practice to avoid function's parameter manipulation

I have the following abstract code snippet:

// definitions
    MyClass1 mc1 = new MyClass1();
    MyClass2 mc2 = new MyClass2();
    List<String> elements = new ArrayList<>();

// some black magic...

// setters
    mc2.setElements(elements);
    String id = saveMyClass2(mc2)
    mc1.setMc1Id(id);

// Some other black magic on mc1 

I'm using the setters flow in multiple parts of my code. I wanted to elaborate this by a wrapper function like this:

void doSettings(MyClass1 mc1, MyClass2 mc2, List<String> elements) {
        mc2.setElements(elements);
        String id = saveMyClass2(mc2)
        mc1.setMc1Id(id);
}

But I am doing a parameter manipulation in this function which I want to avoid. Also cloning the classes is not an option, they are 3 layers deep and it takes too much effort to create deep copy.

So do you know any best practice or coding pattern which helps to avoid code duplication?

Why is the Interpreter design pattern not applicable when efficiency is a critical concern?

In the book Design Patterns, written by the Gang of Four, the following is stated in the 'Applicability' section of the Interpreter pattern:

efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines.

  • Why is interpreting parse trees directly not efficient?
  • How do state machines help in improving this efficiency?
  • Are state machines more efficient then an Abstract Syntax Tree for 'interpretation' of a sentence? If so, why?

I viewed AST and state machine articles on the internet:

Unfortunately, I wasn't able to find the answer to the questions stated in the problem section. The reason for that could be that I don't fully comprehend the 'Applicability' section of the Interpreter pattern. As a result not formulating the right questions.

What frameworks and design patterns support self-defined and customizable sequence of actions? [closed]

A sequence of actions are, for example, listening to a topic/channel in message queue , read some info by calling APIs, do some type conversion , and then call another APIs for write. What framework/design patterns supports defining and customizing a sequence of actions like these while keeping the repeated part generic and reusable? I will most likely use Java. I'm looking for a direction to dive into. I'm not looking for a complete solution.

Distributing execution design change for AWS

Currently we have system deployed on-premises. Our target is to deploy to AWS using EKS or ECS. So we want to optimally use cloud resources and hence we are thinking about design change. The code is running in .NET Core and written in C#.

My problem statement is as - Currently, user selects multiple accounts and runs different processes on them. This processing happens on background thread(ThreadPool). So user can select 100 accounts (it can be 2000-3000 also) and 20 processes as example. So we divide this work such that we split this into multiple threads with each thread processing one process and one or more accounts. So all this processing happens as part of UI trigger from user executing API call on the server to which load balancer routes the request. So this work currently is not split up between multiple servers if they are idle at the same time. Now I want to design this such that I am able to split my work between multiple pods and containers instead of single node doing all the work. Is this what can be achieved by Kubernetes configuration or what design pattern I can apply to split work between multiple nodes?

One approach could be to expose the method which executes process and one or more accounts as a separate http endpoint which will be triggered as part of initial api call and load balancer routing request to multiple nodes and doing the split. But this might not efficiently utilize idle nodes.

How to properly override a method in Scala?

I'm exercising the decorator design pattern in Scala. I have the following implementation of a "Player".

// interface for the player
trait Player {
  def jump(): Unit
  def swim(): Unit
}

// a beginner player can't jump nor swim
class Beginner extends Player {
  def jump(): Unit = throw Error()
  def swim(): Unit = throw Error()
}

// movement decorator abstraction
abstract class MovementDecorator(my_player: Player) extends Player {
}

// concrete decorator
class Swim(player_x: Player) extends MovementDecorator(player_x) {
  def jump(): Unit = throw new Error("I can't jump")
  override def swim(): Unit = println("I swam!")
}

// concrete decorator
class Jump(player_x: Player) extends MovementDecorator(player_x) {
  override def jump(): Unit = println("I jumped!")
  def swim(): Unit = throw new Error("I can't swim")
}

A concrete Player (i.e. Beginner) can't have moves such as jump() or swim(). But I can decorate aka wrap the object with the Swim and/or Jump classes to give the Beginner that capability.

However, when I run the main method, I get the outputs shown with comments.

@main
def main(): Unit = {
  val swimmer = Swim(Beginner())
  swimmer.swim() // "I swam!"

  val jumper = Jump(Beginner())
  jumper.jump() // "I jumped!"

  val swimmer_jumper = Jump(Swim(Beginner()))
  swimmer_jumper.jump() // "I jumped!"
  swimmer_jumper.swim() // Exception at Jump.swim: I can't swim
}

I want to keep the following to create my object

val swimmer_jumper = Jump(Swim(Beginner()))

Is there a specific way of overriding methods that I'm missing? I thought when you override a method it overrides any other method of the object -- and it becomes the preferred one.

Any help would be appreciated!

Maintenance of code that generate CSV files in C

I'm looking for an easier way to maintain a code that generate CSV file.

Currently, each line in the CSV file is written in the following way:

fprintf(pCsvFile,"%s,%s,%d,%d,%d",param->a, param->b, param->c, param->d, param->e);

In reality I have around 20 different values from different types that I'm writing in every CSV file row, and as you can guess its start getting really difficult to maintain the code (adding or removing parameters).

Is there any clever way to do it in C language? Thanks.

VHDL (Hardware Description Language)

enter image description here Please can someone who understands vhdl help with the vhdl code to run this circuit?

  1. A(t+1)=Ax+Bx
  2. B(t+1)=A'x 3.y=(A+B)x'

mardi 13 décembre 2022

One vs several objects - which is better OOP approach?

I am not sure if this question should be here or on another community on stackexchange. I have some problem regarding design. Here it is an simplified example of my code.

class Data:
store = {
    'key':[]
}
def __init__(self):
    self.arg1 = 'value'
    self.arg2 = 'value'
def add_to_store(contents):
   self.store['key'] += contents

Arguments arg1 and arg2 will always be the same while initializing object of class Data (not that important). Only store will change depending on contents of a file.

My dilemma is:

is it better to initialize an object in a for loop and each time working on the new one:

for file_content in files_contents:
   d = Data()
   d.add_to_store(file_content)

or should I create only one object and add method that will clear my dictionary?

d = Data()
for file_content in files_contents:
   d.add_to_store(file_content)

Which is better practice? or it depends and both are correct?

Template Pattern how to update each method status in Main Method c# Windows App

Template Pattern how to update each method status in Main Method c# Windows App


using System; namespace TemplateMethodDesignPattern { public abstract class HouseTemplate { // Template method defines the sequence for building a house public void BuildHouse() { BuildFoundation(); BuildPillars(); BuildWalls(); BuildWindows(); Console.WriteLine("House is built"); }

    // Methods to be implemented by subclasses
    protected abstract void BuildFoundation();
    protected abstract void BuildPillars();
    protected abstract void BuildWalls();
    protected abstract void BuildWindows();
}

}

on Main method i wanted to show each method status/output based on progress in listbox c#

tried with delegates but didn't succeeded.

What is the best way to handon the Clean Architecture for Swift iOS? [closed]

I wanted to get hands-on practice with Clean Architecture for Swift programming on the iOS platform. What I know is - Clean is NOT the same as VIPER.

lundi 12 décembre 2022

Error, does not name a type in State design pattern [closed]

Im relatively new to C++. I'm applying the State design pattern for an IoT application that simply polls a sensor every 15 secs, then if its still connected online, send the data somewhere, and if its not, then save it to an array. However I've been at this code for a few days now and I'm stuck at a part where when I added a TransitionTo in OfflineState I get errors. From my understanding it is because TransitionTo(new OnlineState), OnlineState is declared after I try to use the function, however if I change the order of declaration I'll get an error in TransitionTo(new OfflineState). Coming from C, I expected to just do something similar to adding a prototype, in this case I tried Forward declaring the states classes, but it didn't work. I would like to understand why is it wrong OOP-wise and how to fix it.

#include <iostream>
#include <typeinfo>
#include <WiFi.h>
#include <WiFiClientSecure.h>
// The base State class declares methods that all Concrete State should
// implement and also provides a backreference to the Context object, associated
// with the State. This backreference can be used by States to transition the
// Context to another State.
const char *ssid = "XXX";
const char *password = "XXX";
unsigned long lastTime = 0;
const unsigned long timerDelay = 15000;
int flag = 0;
const TickType_t connectionDelay = 1500 / portTICK_PERIOD_MS;

WiFiClientSecure client;

class State
{
  // @var Context
protected:
  Context * context_;

public:
  virtual ~ State ()
  {
  }

  void set_context (Context * context)
  {
    this->context_ = context;
  }

  virtual void Connect () = 0;
  virtual void CheckConnection () = 0;
  virtual void setMyAttribute (float x) = 0;

};

// The Context defines the interface of interest to clients. It also maintains a
// reference to an instance of a State subclass, which represents the current
// state of the Context.

class Context
{
  // @var State A reference to the current state of the Context.
private:
  State * state_;

public:
  float sensorData = 0;

    Context (State * state):state_ (nullptr)
  {
    this->TransitionTo (state);
  }
   ~Context ()
  {
    delete state_;
  }

  // The Context allows changing the State object at runtime.
  void TransitionTo (State * state)
  {
    Serial.println ("Transitioning");
    if (this->state_ != nullptr)
      delete this->state_;
    this->state_ = state;
    this->state_->set_context (this);
  }

  // The Context delegates part of its behavior to the current State object.
  void Connect ()
  {
    this->state_->Connect ();
  }
  void CheckConnection ()
  {
    this->state_->CheckConnection ();
  }

  void setMyAttribute (float x)
  {
    this->state_->setMyAttribute (x);
  }

};

// Concrete States implement various behaviors, associated with a state of the Context

class OfflineState:public State
{
public:
  virtual void Connect () override
  {
    Serial.println ("connect from offlineState called");
    WiFi.begin (ssid, password);
    Serial.print ("Connecting to wifi...");
    for (int i = 0; i < 10; i++)
      {
    if (WiFi.status () != WL_CONNECTED)
      {
        Serial.print ('.');
        vTaskDelay (connectionDelay);
      }
    else
      {
        i = 10;
        Serial.println ();
        Serial.println ("Connected !");
        this->context_->TransitionTo (new OnlineState);
      }
      }
  }

  void CheckConnection () override
  {

    Serial.println ("Check connection from offlinestate called");
  }

  void setMyAttribute (float x) override
  {
    CheckConnection ();
  }

};

class OnlineState:public State
{
public:
  void Connect () override
  {
    Serial.println ("Already connected");
  }

  void CheckConnection () override
  {
    Serial.println ("Check connection from onlineState called");
    if (WiFi.status () != WL_CONNECTED)
      {
    Serial.println ("Disconnected!");
    this->context_->TransitionTo (new OfflineState);
      }
  }

  void setMyAttribute (float x) override
  {
    CheckConnection ();

  }

};

Context *context = new Context (new OfflineState);

void
setup ()
{

  WiFi.mode (WIFI_STA);
  lastTime = millis ();
  Serial.begin (115200);
  context->Connect ();
  context->CheckConnection ();
}

void
loop ()
{
  if (millis () > (lastTime + timerDelay))
    {

      context->CheckConnection ();
      lastTime = millis ();
    }
}

I've tried making Connect() virtual void so it's declared after both states.

void OnlineState::Connect() {
{
std::cout << "OnlineState: Already connected.\n";
}
}

But I still get errors since in the class declaration, the class appears to be abstract.

How to populate CRM Contact data to another Microservice?

Situation:

I have a Spring Boot application that stores Project Entities with associated Announcement Entities. This Announcement Entities have 1 to N Contact Entities.

The Contact table has fields like: first name, last name, e-mail, mobile, and so on.

If we create a project and an announcement, we must specify at least one contact. Previously, the contact was created in the database using text input fields.

Now it is a requirement to get the contact data from our CRM system. At the same time, it should also be possible to trace which contact is assigned to which Project in the CRM System.

Problem:

Unfortunately, I don't have much experience with software architecture. Whatever my supervisor wants me to work out a solution for this. I would be very grateful if you could help me a little and give me a direction to go.

My idea:

At first, This bidirectional relation between the CRM System and my service sounds redundant to me. I would suggest to fetch the contact data from an CRM Endpoint by company name (a company can create a project) and provide the found contacts as dropdown or autocomplete textfield. If a contact not exist, a new contact will be created about another CRM Endpoint. Next, I would persist the project-announcement-contact relationship in my service. In the CRM system I would only create a new contact if needed. For the CRM system I would create an endpoint that returns projects/announcements by contacts. this is a bit weird, but that's how I understand the requirement.

Second Problem:

What if a contact changes in the CRM system. I have to reflect that somehow in my service. Should i use event driven design here and a message broker?

I would be very grateful if someone with experience could give me some hints and tips.