lundi 31 juillet 2023

C++ Problem with handling a state between two classes in a hierarchy

Problem Description

Consider the following class hierarchy. Concrete templated class A, templated abstract class B and an interface C, with A <-- B <-- C. Consider that B has a function declaration

virtual std::optional<T> foo() const  = 0;

and c has a function declaration

virtual bar() = 0;

both of which are defined in A appropriately.

There exists somewhere in the code a list of objects B, over which we call foo(), and there exists a list of C* pointers over which we call bar().

For a minimal example:

Example and My Issue

class A <typename T> : public B <T>
{
public: 
    std::optional<T> foo() const override { /*...*/ };
    bar() override { /*...*/ };

    // ...
};

class B <typename T> : public C
{
public: 
    virtual std::optional<T> foo() const = 0;

    // ...
}

class C
{
public: 
    virtual bar() = 0;
}

The issue I am having is that I want to add a boolean state over this small hierarchy. Particularly, I have the following requirements

  1. I need a boolean state m_isInteresting over the object represented by this hierarchy.
  2. I don't want m_isInteresting state it to be in A (for decoupling reasons).
  3. I want foo() to set m_isInteresting = true;.
  4. I want bar() to set m_isInteresting = false;.

How can I achieve this?

Things I have tried

  • I tried to create a decorator wrapper around C with the m_isInteresting member and the appropriate accessors, with a method forward of bar(), in which I call C's bar() function and set the class member m_isInteresting to false, but then I can't set the member to true because foo() is down the class hierarchy.
  • I tried to move foo()'s declaration to C (while keeping it's definition in A), but this is very difficult because the function returns a std::optional<T> and well, C is not templated; a derived class's function signature must match that of the base class.
  • I have thought of making decorator classes for both B and C with m_isInteresting shared between them, but held externally, but this is getting ugly and complicated.

There must be something that I am missing here.

samedi 29 juillet 2023

Feature based approach project structure for react native app [closed]

I have some questions concerning feature based approach for structuring react native projects.

We are planning to create a car services app. The app consists of 5 tabs:

Home ,Catalog, Services, Chat and Profile

In Catalog users Can see cars available for sell.

In Services users Can Book car services there are many.

In Home screen we show some cars for sell and some services, if a service or a car is clicked then we go to its details screen.

My questions are:

Should we create a screens folder ?

Is Home a feature ? Because it contains in it some of the other features like seeing cars from Catalog tab and Services

Should we consider every service of the services a feature ?

Should we treat tabs as features or screens ? Or anything else ? Any ideas.

At the moment i'm thinking maybe every tab is a feature, but like that we are going back to types project structure approach where we have screens and all component belonging to that screen arent we ? If we divide out project to only features. How could we know which code or components belongs to which screens. I've seen in many articles that features have screens folder in it but i'm not able to imagine in our case.

Database design: How to assign different clients to varying number of films?

This is a purely design question: In my node.js app, registered clients (each having individual client_id) can buy access to: One film 10 of them 30 of them 150/all of them. The question is: how to deal with this? Using MySQL database, I am thinking what tables I should create to dealt with the fact that many clients can have different number of films assigned to them, while each film is different.

I thought of 2 solutions: first, let's make a huge table with 150+ columns, each representing individual film_id. Then, I can just 0/1 the column in a specific row to assign a film to a client, but then for 100 clients I would have 15000 cells in a single table? Quite large

Second idea was to create 4 tables, where 1st and 4th are pretty simple: If a user buys one film, assign that film's id to them, and if they buy all films, just note in the last table that they have unlimited access.

vendredi 28 juillet 2023

amazon online assessment test july 2023

A regex pattern consists of lowercase English letters and some wildcard characters (?") with any English character. Two patterns are called intersecting if the wildcard characters in the respective strings can be changed in a way to form the same string from both patterns. For example, pattern p= "?cc?" and q = "dc??" intersect as we can form s = "dccx" from both p and q. Given an array patterns of n regex strings, find the minimum number of '?' characters possible in a pattern that intersects with all the patterns. Given n=2, m = 10, patterns = [ha???rrank", "?a?ke?bank"] output-1 explanation-hacker?ank

sometimes when we give margin to container why it will go to second line?

enter image description here In this picture you are seeing that when I increase margin 100px the line is brake why?

I am IRS Web you see in this picture the navigation menu is on the end of the line . i can fix it by only css but it is not fixing tell me how to give margin to this to get no line brake . mmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm

Best Design Pattern to run Background Async Tasks

This question is about implementation and architecture of Async nature of tasks implemented via REST to improve performance.
Imagine an application which is suppose to push data from external service to different domain services. Later on, it is expected that multiple request will query previously push data from other domain service.

As an example, Consider a real-estate application which collects home/apartments/commercial-shops information from different other websites.

  • STEP-1: User logs in
    At this point it is expected that this user might query about list of apartments available for rent in whole city
    It is also expected that user might query about list of houses on Sale

  • STEP-2: User navigate from Home page to Available for Rent Menu

  • STEP-3: User clicks on Menu and services started to collect data from different other external systems/websites

Now, our goal is to run a task to collect all available houses for rent/sale as soon as User logs in which is not a problem. But the challenge is that if this job to collect data is not finished and user clicked on Available for Rent Menu, How would be block this API to respond until Background job is finished.

Please keep in mind that overall System is implemented via Microservices based on CQRS pattern.
So in total, There are four service GATEWAY, COLLECTION, RENT, SALE So when User logs in

  • Endpoint of Service gateway/EP1 will receive request which will trigger collection-service to start the data collection job.
  • Collection job is suppose to collect info and update RENT service.
  • Collection job is suppose to collect info and update SALE service.
  • Now if user clicks on Available for Rent Menu which will call gateway/EP2 and this endpoint of gateway service collects info from service RENT (which is being updated by collection service).

So Problem statement is ,How a gateway service endpoint can put on wait until one microservice updates another microservice?

Observer pattern can be a candidate here but I need experts opinion if it is best suited in above mentioned Rest microservices architecture.

Abstract classes in DTO - complex dependency beetwen layers

I have a following problem. I have two classes: AnimalService responsible for domain logic and AnimalController which is responsible for public API available to clients. AnimalServices uses domain abstract class Animal and AnimalController uses DTO objects. AnimalService is not aware of AnimalController existence, so Animal class does not know about AnimalDTO.

public abstract class Animal {
   ...
}



public class AnimalController {

   private final AnimalMapper animalMapper;

   ...
   
   public AnimalDTO createAnimal(AnimalDTO newAnimal) {
      Animal domainAnimal = animalMapper.fromDTO(newAnimal);
      Animal createdAnimal = animalService.createAnimal(domainAnimal);
      return animalMapper.toDTO(createdAnimal);
   }
}




public class AnimalService {
   
   public Animal createAnimal(Animal domainAnimal) {
      ...
   }
}

Since the Animal class may have many implementations, Im having troubles with designing AnimalDTO. Creating a new DTO for every new implementation of Animal seems like a very bad dependency, which requires changes in multiple places each and every time and a Single Responsibility principle violation.

Is there any better solution / design that I could possibly use in that case?

jeudi 27 juillet 2023

Is there a name for unremovable dead code?

Is there a term for describing a piece of seemingly vestigial/dead code that causes compilation errors when removed? e.g. TF2's Load Bearing Coconut myth

I've asked my coworkers and the consensus is we know there's a word for this, but none of us can remember it.

Best approach to define fixed data in Symfony

I need help about how to handle fixed (not changing) data in Symfony, in an API architecture.

Let's say we are doing a dices game, and we want to store the list of dices, each one having a specific range of values (e.g. one having only odd numbers from 1 to 10, another one having only even numbers from 1 to 10, and a last one having all numbers from 1 to 6), and a label.

Creating DB tables to store the different values (e.g. Dice[id,label], DiceValue[id,dice_id,value]) doesn't seem to be the right solution here, so I'd prefer to define these dices in Symfony directly.

My question is how would you define those in Symfony ?
Using a Factory ? Tagged iterators ?
I can't find any resources on the right way to do this kind of things..

Thanks!

Interface to return Generic type

I have an interface that returns a Connection. I've changed to Object, because I need to return sometimes a Connection and sometimes a MongoDatabase object from Mongo. My poor ideia was to change this method to Object, like this:

Object getConnnection(String uri);

Is a poor design? Any suggestion to improve this aproach? Thanks a lot for any suggestion.

Design UI interface similar to amazon connect but open source?

I wanted to build a system for customers to design their own flow of how the program behaves when their customers engage with our "enterprise application" we are building.

I wanted to make the UI Designer interfaces very easy to use and I'm looking for an open source/free version of something similar to this:

(**note this is not a phone application but the flow of actions is similar)

Features:

  • drag and drop
  • add components
  • connect components
  • configure components
  • different components types or basic sets of them.
  • [bonus]Not sure about this, but a plus if it converts to yaml/toml or directly to code behind the scene.
  • [bonus]Allows for export/import.

A picture is worth a thousand words: enter image description here Picture source.

The only out of the box system I can think of that is similar is blockpy or blocky

Thanks!

Instead of designing the system from scratch, I'm hoping there is something out there to build upon.

mercredi 26 juillet 2023

URL Redirection Service using AWS services

My use case is as follows: I'm trying to create a url redirect service (with an "umbrella" hyperlink) based on a user's home country (provided by a federated identity), and looking for a solution using AWS services. I'm sure there is a relatively simple way to do this in AWS but am not familiar enough with full-stack development and the available options.

I have a lambda function that takes a user's federated identity and returns their home country as an ISO-3166 code. Based on this, I need to set up a hyperlink with a custom domain. When the user clicks on the hyperlink, the site should redirect the user to any number of other URLs based on the home country value provided by the lambda. The mappings for the redirect urls should also be stored somewhere in AWS either in a database, AppConfig, etc, and should be easily changeable.

Since the site itself has no homepage or content of it's own, I'm wondering if there is a simple way to do this in AWS.

I'm about to set up a custom domain in Route 53 and not really sure what is the best option from there. I've read about the solutions for domain redirection in Route 53 here, but since I'm new to these services I'm not sure which would fit my use case best.

I've looked into AWS Amplify hosting for URL redirects but it seems like setting up an amplify stack is excessive for the use case.

How to avoid code smells (too many if else) where each enum if condition will call different methods which are controlled by third party library?

(Understanding OpenSearch/ElasticSearch is not important for this question, but the below information provides some context). I am using the new opensearch-java (version 2.4.0) library to interact with the OpenSearch cluster. I am trying to build the TypeMapping using Builder pattern, so that I can pass these properties mapping when creating a new index in OpenSearch.

I have the following code to use the Builder pattern to build the TypeMapping.

package test;

import java.util.Map;
import org.opensearch.client.opensearch._types.mapping.Property;
import org.opensearch.client.opensearch._types.mapping.TypeMapping;
import org.opensearch.client.opensearch._types.mapping.DynamicMapping;

 
public class TypeMappingBuilder {
    private DynamicMapping dynamic;
    private final Map<String, Property> properties;

    public TypeMappingBuilder() {
        this.properties = new HashMap<>();
    }

    public TypeMappingBuilder disableDynamic() {
        this.mapping = DynamicMapping.Strict;
        return this;
    }
    
    public TypeMappingBuilder putTypeProperty(
            String name, 
            Property.Kind type, 
            boolean shouldIndex, 
            Map<String, Property> subTypeProperties) {
        this.properties.put(name, getTypeProperty(type, shouldIndex, subTypeProperties));
        return this;
    }

    private Property getTypeProperty(
            Property.Kind type, 
            boolean shouldIndex, 
            Map<String, Property> subTypeProperties) {
        if (type == Property.Kind.Text) {
// Here, in (p -> p), p is the TextProperty.Builder() provided by OpenSearch Java client
            return new Property.Builder().text(p -> p.index(shouldIndex).fields(subTypeProperties)).build();
        }
        if (type == Property.Kind.Keyword) {
// Here, in (p -> p), p is the KeywordProperty.Builder() provided by OpenSearch Java client
            return new Property.Builder().keyword(p -> p.index(shouldIndex).fields(subTypeProperties)).build();
        }
//...
//...
//... and so forth, there are more than 20 of the Property.Kind values where I can use the if condition
    }

    public TypeMapping build() {
        return new TypeMapping.Builder()
                .dynamic(dynamic)
                .properties(properties)
                .build();
    }
}

The issue is that using too many if statement here will cause code smell and also if a new type is added in the future, then I have to update getTypeProperty method to apply for the new type. Also, in this new Property.Builder().{specificType}({specificTypeBuilder}).build(), I cannot use polymorphism as there is different method names for each {specificType} and different type Builder for each {specificTypeBuilder}. I don't see any other options than to use if statements to create different Property based on a specific type. I thought of using static Map like so and access specific Property from the Map, but would only work if I didn't have subTypeProperties to put in for sub fields:

Map<PropertyHolder, Property> propertyMap = ImmutableMap.<PropertyHolder, Property>builder()
            .put(new PropertyHolder(Property.Kind.Text, true), new Property.Builder()
                    .text(p -> p.index(true)).build())
            .put(new PropertyHolder(Property.Kind.Text, false), new Property.Builder()
                    .text(p -> p.index(false)).build())
            .put(new PropertyHolder(Property.Kind.Keyword, true), new Property.Builder()
                    .keyword(p -> p.index(true)).build())
            .put(new PropertyHolder(Property.Kind.Keyword, false), new Property.Builder()
                    .keyword(p -> p.index(false)).build())
            ...
            ...
            ...
            .build();

    final class PropertyHolder {
        private final Property.Kind type;
        private final boolean index;

        private PropertyHolder(Property.Kind type, boolean index) {
            this.type = type;
            this.index = index;
        }

        public static Property getTypeProperty(Property.Kind type, boolean shouldIndex) {
            return propertyMap.get(new PropertyHolder(type, shouldIndex));
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            PropertyHolder that = (PropertyHolder) o;
            return type == that.type && index == that.index;
        }

        @Override
        public int hashCode() {
            return Objects.hash(type, index);
        }
    }

Another option that can actually work was to create my own enum and have a method defined for each enum value that returns a specific Property based on the enum value (Strategy pattern). But, that would be an abuse of enums and probably code smell. Here is what I am talking about:

public enum Type {
        TEXT {
            @Override
            public Property getTypeProperty(boolean shouldIndex, Map<String, Property> subTypeProperties) {
                return new Property.Builder().text(p -> p.index(shouldIndex).fields(subTypeProperties)).build();
            }
        },
        KEYWORD {
            @Override
            public Property getTypeProperty(boolean shouldIndex, Map<String, Property> subTypeProperties) {
                return new Property.Builder().keyword(p -> p.index(shouldIndex).fields(subTypeProperties)).build();
            }
        },
        ...,
        ...,
        ...;

        public abstract Property getTypeProperty(boolean shouldIndex, Map<String, Property> subTypeProperties);
    }

What design pattern can I use in this scenario to avoid code smell? Thank you!

Should i send socketmessages directly from client or go my through restapi-server?

I have my frontend mobile-application and my backend. I am building a chat-application and I wonder how I should structure my socketmessages. For example is a user sends a message, I call my backend to create the message in the database, but right now my backend will also send a socketmessage to my socketserver which will broadcast it to the user I sent the message to. I wonder, is it better to send the message to the socketserver directly from the frontend, so the frontend basically does two things when sending a message, calling my backend to create the message in db, and then also calling the socket to broadcast the message? Same goes for "isTyping"-state. For me it makes sense to not go via https and just directly send it to the socket, but what if I would like to also send a notification when user is typing, then it would make more sense to call the backend and let it send the info to the socketserver.

Should abstract superclass contain protected non-abstract methods which are to be used by some and not all subclasses

I have an abstract class as below -:

public class AbstractClass{
   
    private String getA(){
       return "A";
    }
    
    protected String getB(){
        return getA().concat("-B");
    }

}

Now, all subclasses will use getB() method. That is why I have made it as protected. But not all subclasses will use getA() method. Only a subset will use it. So, should I still make it protected or keep it private?

mardi 25 juillet 2023

Java DecimalFormat pattern, differences between # and 0

I have the following code:

public class Main {
    public static void main(String[] args) {
        String pattern = ".00";         // a) => |.46|
//        String pattern = ".##";       // b) => |.46|
//        String pattern = ".0#";       // c) => |.46|
//        String pattern = "#.00";      // d) => |.46|
//        String pattern = "#.0#";      // e) => |.46|
//        String pattern = "#.##";      // f) => |0.46|
//        String pattern = ".#0";       // g) => IllegalArgumentException: Malformed pattern ".#0"

    double value = 0.456;
    DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    df.applyPattern(pattern);
    String output = df.format(value);
    System.out.printf("|%s|", output);
   }  
}

Could someone explain that why in f) the zero before decimal point still displays while d) and e) don't even though they are all have a '#' before decimal point in the pattern? Also, what could be the reason for the exception in g) as it seems to me a valid pattern?

Which is best architecture and design pattern for flutter project

I decided start to learn architecture and design patter for flutter. I've little bite confusion, which architecture is best practice to learn. Because some architecture is there in this plaform like Flutter Bloc Pattern (Business Logic Component), MVVM, MVC,... so on. Anyone help, how to choose which is best one.

I decided to be work flutter project for self taught purpose. Any suggestion

Is it a bad idea to manage 1000+ alert configs in bazel?

I have something like 1000 alerts in YAML files that we parse with python and then spit out some machine readable files which are then ingested downstream by compilers. I want to update the system to be easier to work with, and I think there are benefits to be had by moving config from yaml into bazel (already used extensively by others working on the project).

I figured bazel would be good since the rules/providers would offer clear and documented inputs and we wouldnt need to invoke some kind of additional generator. A lot of people I talk to seem to think this is abusing bazel in some way, but Im confused by that. Bazel just takes pieces of data and manipulates them, similar to what a generator would do, with the added benefit of caching that data when it doesnt change. It also just integrates nicer with the rest of the build system and should allow us to do more complicated/comprehensive checks sooner.

Am I wrong for thinking I can use bazel for this? It seems to feel right.

lundi 24 juillet 2023

Switching long inheritance tree for composition / agreggation

I have a program in Java which uses a lot of inheritance, and it's making it troublesome to modify and test the final derived classes

So I'm refactoring, attempting to switch from inheritance to aggregation / composition. The design in question is similar to A isInheritedBy -> B isInheritedBy -> C isInheritedBy -> D

My problems are:

  • Calling functions from derived classes instances that the base classes don't have, while still having access to the base classes functions. There is often a need to call things like d.methodNotInBaseClasses() that calls functions from the base classes
  • Calling overridden functions through the derived class instances, so calling d.methodFirstDefinedInA() that can call the same method from instances of C, B and A
  • I need to maintain polymorphic behavior to minimize the required changes to the rest of the code. Currently there is a lot of A a = new D()
  • I need to have loose coupling between base and derived classes

The best design I've thought of for class creation is:

Assume that classes A,B,C and D exist, where B to D are coupled to the previous class by constructor dependency injection

class Builder {
    public A createInstanceOfA(){
        return new A();
    }

    public B createInstanceOfB(){
        return new B(createInstanceOfA());
    }

    public C createInstanceOfC(){
        return new C(createInstanceOfB());
    }

    public D createInstanceOfD(){
        return new D(createInstanceOfC());
    }
}

This seems fine for me. However for polymorphic behavior behavior from base classes I'm defining interfaces that each derived class implements for its base classes:

interface InterfaceForA {
    void doSomething();
}

interface InterfaceForB {
    void doMore();
}

interface InterfaceForC {
    void doEvenMore();
}

interface InterfaceForD {
    void doTheMost();
}

And now you can see the problems of duplicated functions:

Sidenote: I'm aware @Override is not required for interface implementations, I added those for clarity

class A implements InterfaceForA {
    public void doSomething(){
        System.out.println("A did something");
    }
}

class B implements InterfaceForB, InterfaceForA {
    private A a;

    B(A a){
        this.a = a;
    }

    @Override
    public void doSomething(){
        a.doSomething();
    }

    public void doMore(){
        a.doSomething();
        System.out.println("B did more");
    }
}

class C implements InterfaceForC, InterfaceForB, InterfaceForA {
    private B b;

    C(B b){
        this.b = b;
    }

    @Override
    public void doSomething(){
        b.doSomething();
    }

    @Override
    public void doMore(){
        b.doMore();
    }

    public void doEvenMore(){
        b.doMore();
        System.out.println("C did even more");
    }
}

class D implements InterfaceForD, InterfaceForC, InterfaceForB, InterfaceForA {
    private C c;

    D(C c){
        this.c = c;
    }

    @Override
    public void doSomething(){
        c.doSomething();
        System.out.println("D did something");
    }

    @Override
    public void doMore(){
        c.doMore();
    }

    @Override
    public void doEvenMore(){
        c.doEvenMore();
    }

    public void doTheMost(){
        c.doEvenMore();
        System.out.println("D did the most");
    }
}

All for being able to do these:

class App {
    public static void main (String[] args) {
        Builder builder = new Builder();
        D d = builder.createInstanceOfD();

        // Allows functions the base classes don't have, yet have access to the base classes functions
        d.doTheMost();
        System.out.println("---");

        // Allows calling overriden functions of the base classes directly
        d.doSomething();
        System.out.println("---");

        // Allows calling overriden function from base classes interfaces
        InterfaceForA a = d;
        a.doSomething();
    }
}

If this already seems too complex, consider also that the entire dependency tree consists of about 90 classes, with the deepest ones maybe with 6-8 base classes

I also tried the Strategy pattern, with dependencies inverted like A dependsOn InterfaceForB, B dependsOn InterfaceForC, C dependsOn InterfaceForD and D having no dependencies, but I couldn't wrap my head around it. I had to make Builder more complicated, I could only call A methods from D by making D depend on A, and to either:

  • Keep references to the instance of each base class and call each instance function separatedly. The client code from the 13 lines in main() grew to 28
  • Use getters in base clases to get the interface to their strategy. The client code grew from 13 to 20, and the entire code grew from 129 to 148

Thoughts?

How can I use `ThenInclude` in generic class in UnitOfWork

I have generic Repository in my project.

I want to use ThenInclude() in Search method of unitofwork

how can i do it?

I use this method but ThenInclude does not work

 public async Task<IEnumerable<TEntity>> FindByConditionAsync(
                                         Expression<Func<TEntity, bool>> filter = null,                                              
                                         Func<IQueryable<TEntity>,IOrderedQueryable<TEntity>> orderBy = null, 
                                         params Expression<Func<TEntity, object>>[] includes)
 {
     IQueryable<TEntity> query = dbSet;
     foreach (var includ in includes)
     {
         query = query.Include(includ);
     }

     if (filter != null)
     {
         query = query.Where(filter);
     }

     if (orderBy != null)
     {
         query = orderBy(query);
     }

     return await query.ToListAsync();
 }

Clean Code Architecture with transitive gateways - best practice

I am trying to refactor my project to match the Clean Code Architecture by Robert C. Martin Clean Code Architecture.

What is the best practice to use multiple gateways which depend on another gateway. Since all the instantiation should be done in an outer layer or the same layer, how should gateways communicate with other gateways?

  • Shouldn't we use multiple gateways at all?
  • Should the External System instantiate all gateways, work with them and just pass the first one to the use case?
  • Should the main just instantiate the first gateway and pass it to the use case, so every other gateway is instantiated by the gateways itself?

This is an example from my code:

  • main function which belongs to the External System and is the starting point.
  • DashVisualizer which plots a Plotly Dash Application and therefore is also an External System
  • Bunch of STL files as a Repository, so it's also an External System
  • BuildJob class which is an Entity
  • Part class which is also an Entity

So far everything is straight forward. The following is my attempt to categorize the transitive gateways and use case.

  • I have an STLFilesFinder class which searches for every STL file in the repository and creates a Dictionary of them. I assume it's a gateway.
  • Then I have a PartLoader which takes that Dictionary from STLFilesFinder and converts it to Part Entities. I don't want the STLFilesFinder to do that because it has already too much code in the class. So This must be also a gateway.
  • Last but not least I have the BuildJobLoader which takes all the Part entities and creates a Build Job Entities. This is also a gateway. To be clear: a Build Job consist of multiple Parts.

The Main functions has the configurations and creates every instance of these gateways and passes the output to the next gateway. The result (a dictionary) and the DashVisualizer object is passed to the BuildJobVisualizer (use case).

Specification pattern for commands

I am writing an asp.net web api and I am using a cqrs pattern with mediator, repository pattern + unit of work, and now I want to add a specification pattern, I already implemented the pattern like this (showing a part of each class):

public abstract class BaseSpecification<T> : ISpecification<T>
    {
        protected BaseSpecification(Expression<Func<T, bool>> criteria)
        {
            Criteria = criteria;
        }
        protected BaseSpecification()
        {

        }
        public Expression<Func<T, bool>> Criteria { get; }
        public List<Expression<Func<T, object>>> Includes { get; } = new();

        protected virtual void AddInclude(Expression<Func<T, object>> includeExpression)
        {
            Includes.Add(includeExpression);
        }
    }

Specification to include related entities:

public MediaIncludePeopleAndGenres(int mediaId) 
            : base(x => x.MediaId == mediaId)
        {
            AddInclude(x => x.MediaGenres);
            AddInclude(x => x.MediaPeople);
        }

Specification extension class for entity framework context

public static IQueryable<T> Specify<T>(this IQueryable<T> query, ISpecification<T> spec) where T : class
        {
            var resultWithIncludes = spec
                .Includes
                .Aggregate(query, (current, include) => current.Include(include));

            return resultWithIncludes.Where(spec.Criteria);
        }

Method in repository class:

public Task<Media?> GetMediaByIdAsync(int id)
        {
            return _context.Media
                .Specify(new MediaIncludePeopleAndGenres(id))
                .FirstOrDefaultAsync();
        }

It works just as I expected, but I didn't find a similar approach for commands (like post or put), what functionality should I put in the specification? Can I please get an example according to my approach? Now I am calling post media method like this: repository class

public void AddSingleMedia(Media media)
    {
         _context.Media.Add(media);
    }

P.S: I didn't show commands or queries handlers, because I only do mapping there, and calling the repository methods.

Interface vs Abstract class in Builder design pattern

In the context of the builder pattern, What is the most correct way to make the builder template?

With the interface is no able to specify the access permissions (public, protected and private), that means there may be a mismatch in the classes that implement it.

On the other hand, I think it is unnecessary to use an abstract class when all methods are going to be overwritten.

Here´re the exmaples:

Interface

// Builder
interface PizzaBuilder {
    pizza: Pizza;
    resert(): void;

    setTomamto(): this;
    setParmesano(): this;
    setPepper(): this;

    build(): Pizza;
}

🆚

Abstract class

// Builder
abstract class PizzaBuilder {
    protected pizza: Pizza = new Pizza
  
    protected abstract reset(): void;
    public abstract setTomamto(): this;
    public abstract setParmesano(): this;
    public abstract setPepper(): this;

    public abstract build(): Pizza;
}

samedi 22 juillet 2023

what is the architecture used in telegram ios project for source code structure

I've been trying lately to read source code in telegram ios project and I'm wondering: What's the architecture used in here? Is it MVC? MVVM? VIPER? or so on.

Breaking up the rules to call a strategy from the strategy algorithm

So let's say I have this class


var intItems = new List<int> { 200, 2, 3 };
var stringItems = new List<string> { "Hello", " ", "World!" };
var intItems2 = new List<int> { 10, 2, 3 };

var consolidator = new Consolidator();
var s = consolidator.ConsolidateToString(intItems);
Console.WriteLine(s);

s = consolidator.ConsolidateToString(stringItems);
Console.WriteLine(s);

s = consolidator.ConsolidateToString(intItems2);
Console.WriteLine(s);


public class Consolidator
{
    public string ConsolidateToString<T>(IEnumerable<T> items)
    {
        ArgumentNullException.ThrowIfNull(items);
        string consolidatedString = string.Empty;

        if (items is IEnumerable<int> subtract && subtract.Any(i => i > 100))
        {
            consolidatedString = subtract.Aggregate((total, value) => total - value).ToString();
        }
        else if (items is IEnumerable<int> intItems)
        {
            consolidatedString = intItems.Aggregate((total, value) => total + value).ToString();
        }
        else if (items is IEnumerable<string>)
        {
            consolidatedString = string.Concat(items);
        }
        else
        {
            throw new ArgumentException("No valid consolidation found.");
        }

        return consolidatedString;
    }
}

I get the results

195
Hello World!
15

This design works but has issues. For one, hard to test and it can become pretty complex with many if conditions. It will also become a maintenance hell once you start adding pieces.

So strategy 2

var intItems = new List<int> { 200, 2, 3 };
var intItems2 = new List<int> { 10, 2, 3 };
var stringItems = new List<string> { "Hello", " ", "World!" };
var consolidationStrategies = new List<IConsolidator> { new SubtractIntConsolidator(),  new IntConsolidator(), new StringConsolidator() };

var consolidatorStrategy = consolidationStrategies.FirstOrDefault(cs => cs.CanHanldeType(intItems));
if (consolidatorStrategy is null)
{
    throw new Exception("No valid consolidation found.");
}

var s = consolidatorStrategy.ConsolidateToString(intItems);
Console.WriteLine(s);

consolidatorStrategy = consolidationStrategies.FirstOrDefault(cs => cs.CanHanldeType(stringItems));
if (consolidatorStrategy is null)
{
    throw new Exception("No valid consolidation found.");
}

s = consolidatorStrategy.ConsolidateToString(stringItems);
Console.WriteLine(s);

consolidatorStrategy = consolidationStrategies.FirstOrDefault(cs => cs.CanHanldeType(intItems2));
if (consolidatorStrategy is null)
{
    throw new Exception("No valid consolidation found.");
}

s = consolidatorStrategy.ConsolidateToString(intItems2);
Console.WriteLine(s);


public interface IConsolidator
{
    bool CanHanldeType<T>(IEnumerable<T> items);

    string ConsolidateToString<T>(IEnumerable<T> items);
}

public class IntConsolidator : IConsolidator
{
    public bool CanHanldeType<T>(IEnumerable<T> items)
    {
        return items is IEnumerable<int>;
    }

    public string ConsolidateToString<T>(IEnumerable<T> items)
    {
        var intItems = items as IEnumerable<int>;
        return intItems.Aggregate((total, value) => total + value).ToString();
    }
}

public class StringConsolidator : IConsolidator
{
    public bool CanHanldeType<T>(IEnumerable<T> items)
    {
        return items is IEnumerable<string>;
    }

    public string ConsolidateToString<T>(IEnumerable<T> items)
    {
        var intItems = items as IEnumerable<string>;
        return string.Concat(items);
    }
}

public class SubtractIntConsolidator : IConsolidator
{
    public bool CanHanldeType<T>(IEnumerable<T> items)
    {
        return items is IEnumerable<int> intTypes && intTypes.Any(i => i > 100);
    }

    public string ConsolidateToString<T>(IEnumerable<T> items)
    {
        var intItems = items as IEnumerable<int>;
        return intItems.Aggregate((total, value) => total - value).ToString();
    }
}

The results

195
Hello World!
15

Awesome, it works and has a much better design.

The next day another person runs the program and gets

205
Hello World!
15

Oh no, they switched the arrays from

var consolidationStrategies = new List<IConsolidator> { new SubtractIntConsolidator(), new IntConsolidator(), new StringConsolidator() };

to

var consolidationStrategies = new List<IConsolidator> { new IntConsolidator(), new SubtractIntConsolidator(), new StringConsolidator() };

This seems to be a really fragile design. The other issue is the logic to call the strategy is hidden inside the strategy itself. So anyone creating a new strategy would need to look at each strategy to see if their strategy overlaps with any current ones. If it does, you would need to have the arrays in the correct order. I think this makes it a bit hard to troubleshoot and leaves too much room for error.

So strategy 3

var intItems = new List<int> { 200, 2, 3 };
var intItems2 = new List<int> { 10, 2, 3 };
var stringItems = new List<string> { "Hello", " ", "World!" };

var consolidatorFactory = new ConsolidatorFactory();
var consolidatorStrategy = consolidatorFactory.GetConsolidator(intItems);

var s = consolidatorStrategy.ConsolidateToString(intItems);
Console.WriteLine(s);

consolidatorStrategy = consolidatorFactory.GetConsolidator(stringItems);
s = consolidatorStrategy.ConsolidateToString(stringItems);
Console.WriteLine(s);

consolidatorStrategy = consolidatorFactory.GetConsolidator(intItems2);
s = consolidatorStrategy.ConsolidateToString(intItems2);
Console.WriteLine(s);

public class ConsolidatorFactory
{
    public IConsolidator GetConsolidator<T>(IEnumerable<T> items)
    {
        IConsolidator consolidator = null;
        if (items is IEnumerable<string>)
        {
            consolidator = new StringConsolidator();
        }
        else if (items is IEnumerable<int> intTypes && intTypes.Any(i => i > 100))
        {
            consolidator = new SubtractIntConsolidator();
        }
        else if (items is IEnumerable<int>)
        {
            consolidator = new IntConsolidator();
        }
        else
        {
            throw new ArgumentException("No valid consolidation found.");
        }

        return consolidator;
    }
}

public interface IConsolidator
{
    string ConsolidateToString<T>(IEnumerable<T> items);
}

public class IntConsolidator : IConsolidator
{
    public string ConsolidateToString<T>(IEnumerable<T> items)
    {
        var intItems = items as IEnumerable<int>;
        return intItems.Aggregate((total, value) => total + value).ToString();
    }
}

public class StringConsolidator : IConsolidator
{
    public string ConsolidateToString<T>(IEnumerable<T> items)
    {
        var intItems = items as IEnumerable<string>;
        return string.Concat(items);
    }
}

public class SubtractIntConsolidator : IConsolidator
{
    public string ConsolidateToString<T>(IEnumerable<T> items)
    {
        var intItems = items as IEnumerable<int>;
        return intItems.Aggregate((total, value) => total - value).ToString();
    }
}

The results

195
Hello World!
15

Awesome, it works. However, we're back to a class with a complex if condition, which is not great when it comes to maintainability.

So the question is, is there a better approach?

Thanks, Michael

vendredi 21 juillet 2023

coordinator like pattern for state management in iOS swift/objc/c++ based app

Trying to come up with a solution to manage the states of different components within the app. Have multiple software, and hardware components some of which are written in C++, others in Objc, and yet others in Swift. Very close to coordinator pattern where I would want commands to be processed through this object in the future, but for now it just needs to be aware of all the different states of all the objects in the system and be able to report on the state of the system at any given time. Leaning towards using observer/notifications where all components register together with their state through notifications. Where an object (struct) implements some protocol, or perhaps userInfo has key-value pairs but then there is no type checking. Obviously, the alternative is for an object in the notification to be a reference to an actual object but then there is an issue of thread safety.
An alternative is to register delegates and query for the state as needed, but then there is an issue with thread safety and access to objects and their states. Can anyone point out to proposed pattern/solution with multi-treading in mind and given requirements, the pros/cons of notifications vs delegation?

Example of a relatively large open source codebase/application that is written in Procedural style as opposed to OOP style

I've been a professional game programmer for more than 10 years, and a programmer for more than 14. For this entire time, I've been coding in OOP style and, as a senior programmer, I have extensive knowledge in OOP best practices. I just finished watching a video arguing against OOP and the issues revolved around it (overengineered classes, a lot of state to be managed, the complexity of class relationships and encapsulation etc) (https://www.youtube.com/watch?v=QM1iUe6IofM). I certainly understand where the author is coming from, and there are best practices to address those issues, which I won't go into right now. However the author argues procedural programming, with many free, pure functions, with very few classes and a reduced amount of state is the superior way of programming. On paper, they present a compelling argument.

However, I would like to see an example of procedural programming applied successfully to a relatively large codebase with multiple contributors. I tried to find an example and I could not. The proof is in the pudding, as they say. Can anyone provide some example(s)?

How do I decouple lamp from button using the dependency inversion principle?

As per figure 5 in DIP I wrote the following code. How do I write it to conform to figure 6 in the same document?

class Lamp:
    def __init__(self):
        self.state = "off"
    def turn_on(self):
        self.state = "on"
    def turn_off(self):
        self.state = "off"

class Button:
    def __init__(self, lamp):
        self.lamp = lamp
        self.state = "off"
        self.lamp.state = "off" 
    def on(self):
        self.state = "on"
        self.lamp.turn_on()
    def off(self):
        self.state = "off"
        self.lamp.turn_off()

lamp = Lamp()
button = Button(lamp)
assert lamp.state == "off"
button.on()
assert lamp.state == "on"

I am thinking of using the bridge pattern, but I am not sure how to write it.

jeudi 20 juillet 2023

Business Rules Engine implementation on PHP

I'm looking for business rules engines in PHP that include the ability to store decision maps in a database or YAML/JSON format. Would be grateful for the suggestions.

design pattern to avoid deadlock with mutex in golang

What would the appropriate design pattern to avoid deadlock when several functions use the same mutex ?

It is quite easy to forget what method uses the lock and so it happens that you call a function that do a mutex.Lock() inside a function that already locked the mutex --> deadlock.

For example in the following code, it is not explicit right away that the setToNextEvenNb() is a deadlock. You have to look in nested functions. And it would be even worse if the Lock was in function called 2 or 3 level behind the setToNextEvenNb().

package main

import (
    "fmt"
    "sync"
)

type data struct {
    value int
    mutex sync.RWMutex
}

func (d *data) isEven() bool {
    d.mutex.RLock()
    defer d.mutex.RUnlock()
    return d.value%2 == 0
}

func (d *data) setToNextEvenNb() {
    d.mutex.Lock()
    defer d.mutex.Unlock()
    if d.isEven() {
        d.value += 2
    }
    d.value += 1
}

func (d *data) set(value int) {
    d.mutex.Lock()
    defer d.mutex.Unlock()
    d.value = value
}

func main() {
    var d data
    d.set(10)
    fmt.Println("data", d.value)
    fmt.Println("is even ?", d.isEven())
    d.setToNextEvenNb()
    fmt.Println("data", d.value)
}

When you have a large code base, this can happen quite easily. I feel that there should be a design pattern to avoid this sort of scenario and I was looking for any advice on this ?

C++ Replace enum with instances of class. Avoid heap allocation

I want to replace this enum: enum{ eTagA, eTagB,...}.

With instances of classes. This allows to append new tags, without modifying the enum.
I've got following code:

#include <memory>
#include <list>

struct TagBase {
    bool operator== (const TagBase& other) const {
        return typeid(*this) == typeid(other);
    }

    bool operator!= (const TagBase& other) const {
        return !(*this == other);
    }
    
    virtual ~TagBase() = default;
};

bool operator== (const std::unique_ptr<TagBase>& lhs, const TagBase& base) {
    return base == *(lhs.get());
}

class Namespace {
public:
    template<typename T>
    void AddTag() {
        tags.push_back(std::unique_ptr<T>(new T()));
    }
    
    bool HasTag(const TagBase& tag) const {
        return std::find(std::begin(tags), std::end(tags), tag) != tags.end();
    }

private:
    // using of std::unique_ptr is the only way?
    std::list<std::unique_ptr<TagBase>> tags;
};

struct TagA: public TagBase {};
struct TagB: public TagBase {};
struct TagC: public TagBase {};

int main (int argc, const char* argv[])
{
    Namespace nm;
    
    nm.AddTag<TagA>();
    nm.AddTag<TagB>();
    
    assert(nm.HasTag(TagA{}));
    assert(nm.HasTag(TagB{}));
    assert(nm.HasTag(TagC{}) == false);
}

It works, but I have some thoughts about:

  1. Using "typeid" in this context is appropriate? Is this portable?
  2. I can't use raw TagBase class in "std:list" because of slicing. Can I avoid to use "unique_ptr" because of heap allocation?
  3. Maybe there is a better pattern to do this?

I also tried to do this with intense use of templates(std::is_same ... etc) but haven't got proper solution.

How to avoid circular imports when using Python type hints

I'm trying to figure out what would be the best solution to avoid circular imports in a situation where I'm using Protocol and type hints. The problem is the following:

I have some storage targets that in the push method receives and Event.

from typing import Protocol

from event import Event


class StorageProtocol(Protocol):
    def push(self, event: Event):
        ...

class StoragePostgres(StorageProtocol):
    def push(self, event: Event):
        """pushes Event to Postgres"""
        pass

class StorageS3(StorageProtocol):
    def push(self, event: Event):
        """pushes Event to S3"""
        pass

And I have some event that has a function to store itself in something that implements the Protocol StorageProtocol.

from dataclasses import dataclass
from storage import StorageProtocol

@dataclass
class Event:
    id: str
    start_datetime: str
    end_datetime: str
    
    def push(self, storage: StorageProtocol):
        storage.push(self)

This results in a circular import error because the storage.py imports Event and event.py imports StorageProtocol.

I'm aware of using some approaches like the following

  1. from __future__ import annotations
  2. from typing import TYPE_CHECKING
  3. Importing only within the class
  4. Using same if statements to avoid import at run time
  5. Remove type hint
  6. Using type hints in quotes

But none of them seem like a good way to keep the code clean. What am I missing to not figure out how to make this simple example clean?

mercredi 19 juillet 2023

Laravel DDD Pattern (Repository and Service)

I'm working on the laravel pattern, I will have questions in a few places.

I am doing a simple insert operation

PostController

 public function store(StorePostRequest $request): JsonResponse
  {
    return $this->postService->store($request);
  }

PostService

public function store(StorePostRequest $request): JsonResponse
    {
        DB::beginTransaction();

        try {

            $post = new Post();
            $post->uuid = Str::uuid();
            $post->title = $request->input('title');
            $post->description = $request->input('description');
            $post->status_id = $request->input('status_id');
            $post->created_by_user_id = Auth::id();

            $this->postRepository->store($post);

            DB::commit();

            return response()->json(['status' => true, __('service.the_operation_was_successful')]);
        } catch (Exception $exception) {
            DB::rollBack();
            return response()->json(['status' => false, __('service.error_occurred_during_operation')], 500);
        }
    }

PostRepository

public function store(Post $post): Post
 {
   $post->save();

   return $post;
 }

My main question is: Should I move the try cacth block to the controller side? To make the service side look cleaner. If I move, how can I do DB::beginTransaction() transactions, can you help and share your ideas?

Service Aggregator In N Tier Architecture Pattern

I develop an N Tier Architecture application

You can see at this link

At there I have an question.

As we know that in classic n tier architecture each service layer consist of many public and private class like that I shared below

enter image description here

This structure can be very complex when project begin to grow.

I implement Service Aggregator to fix this problem. According to this idea this service's each public class can be moved to separate class and cs file.

For example in the given example at above ;

I divided each public class to a different .cs file and I used "ITripServiceAggrigator" in controller side.

enter image description here

And I aggregate this services under ServiceAggregator via interfaces and dependency injection like below.

enter image description here

My question is that Is this approach true or false? Can I implement any different structure at there?

C++17 Singleton Implementation with Inline variable [duplicate]

I recently came across this article: https://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf I'm curious to know if the problems discussed in the article are still relevant when considering the introduction of C++17's inline variable feature.

As C++17 brought new features and improvements, particularly the ability to declare inline variables, I wonder if some of the issues addressed in the 2004 article have been mitigated or changed by this enhancement.

Additionally, I am interested in implementing the Singleton design pattern in C++17 and want to ensure that I follow the best practices and leverage the latest language features. Could someone provide insights into how C++17's inline variables might affect the problems presented in the 2004 article?

Furthermore, I would appreciate guidance on the most efficient and robust way to implement the Singleton pattern in C++17. Since inline variables are now available, I'm curious if they can play a role in the Singleton implementation for better performance and thread safety.

Any help, clarifications, or code examples related to both C++17's inline variable and Singleton pattern implementation would be highly valuable. Thank you in advance!

Singleton* Singleton::instance () {
    Singleton* tmp = pInstance;
    ...                            // insert memory barrier
    if (tmp == 0) {
         Lock lock;
         tmp = pInstance;
         if (tmp == 0) {
             tmp = new Singleton;
             ...                  // insert memory barrier
             pInstance = tmp;
         }
    }
    return tmp;
}

Azure queue binding to Azure function to process message synchronously

What is the ideal method to design a synchronous queue for an Azure function to prevent parallel processing? The function would execute the next queue request after the current one is finished.

Thanks, Saurabh

Service Aggregator Pattern would work in this situation?

A health related web app that has its own local database to save/retrieve patient's and their appointments information. On other end hospital has its own in-house desktop application to create patient's and their appointments.

In web-app if I need to keep the information from both end. local and hospital's in-house.

One microservice is to retrieve information from hospitals. and other microservices ( patients, appointments, doctors ) for web-app.

How to aggregate or keep local database be updated with the hospital's data? Every time when user see the appointment calendar it should show both the appointments.

Any solution?

mardi 18 juillet 2023

Python design for calling functions with different signatures

Suppose I have a parent class P with a method main that implements the core functionality of the class. main itself calls a function defined in another module called parent_function, with signature parent_function(x, y).

e.g.

from my_module import parent_function

class P:
    def main():
        # do something
        x = P.calc_x()
        y = P.calc_y()
        z = P.calc_z()

        # execute `parent_function`
        parent_function(x,y)
        
        # do more things

Now suppose I have a child class C which differs from P by calling child_function, with signature child_function(x,y,z), instead of parent_function(x,y). To call child_function with its different signature, I have to rewrite the whole of the main method, changing just one line

e.g.

from my_module import child_function

class C(P):
    def main():
        # do something
        x = P.calc_x()
        y = P.calc_y()
        z = P.calc_z()

        # execute `child_function`
        child_function(x,y,z)

        # do more things

This is a violation of the DRY principle.

How can I redesign the code to avoid rewriting the whole main method?

Some ideas:

  • Turn parent_function, child_function into methods of P / C, set z as an instance variable so the signatures of the two methods can be the same. I dislike this solution as in my case it does not make sense for z to be an instance variable.

  • Store the output (x,y,z) into a dictionary, change the signature of parent/child_function to accept **kwargs, and ignore unused kwargs in parent_function.

Is DTO necessary for enterprise Laravel projects

Does anybody use DTO in Laravel? What pros and cons had you noticed, since you applied the pattern? Could you explain the importance of it for a person who's more than fine with Illuminate\Support\Collection which can be retrieved by calling collect() inside my Controller

$params = $request->safe()->collect();
$this->anyService->callAnyMethod($params);

lundi 17 juillet 2023

Design Notification Service using factory pattern

I designed a notification send service using factory design pattern. Now the problem is for a single input I have to send email , sms and push notification. How can I modify the existing factory methods to achieve the same.

There are different implementation classes created like SMSNotify, EmailNotify,PushNotify.

How to develop a Image template editor, that can be used to create templates with text/images and generate images

I want to develop a Image template editor and embed into web app, that can be used to create templates with text/images and generate images dynamically based on your inputs. There are many saas providers apitemplates.io placid.app usestencil.com but are expensive to integrate their white label editor.Web app is developed in react and able to embed drag and drop image editors, but not that can create template and generate images later. Any inputs on how to develop this create custom templates and generate images?

I could not find any inputs on web.

dimanche 16 juillet 2023

command design pattern and projectreactor.io reactive framework with spring webflux

I am having a springboot webflux application using reactive framework and the requirement is to use command design pattern. However, as per my understanding with reactive framework and subscribe approach, I am assuming it might be difficult or not worth using command design pattern with reactive. I developed a lot of non reactive springboot apps with command design pattern, but could not see it fit for webflux reactive.

Can I get some examples for webflux reactive with command design pattern

samedi 15 juillet 2023

How to better approach a cart design with a circular dependency

I am using Laravel and building a shopping cart.

Consider the following:

CartService:

public function __constructor(public ShippingService $shippingService)
{}

// Various standard cart methods such as add() etc
...

protected function getItems()
{
    return $this->store->items;
}

protected function getShippingOptions()
{
    return $this->shippingService->getOptionsForCart();
}

ShippingService

public function __constructor(public CartService $cartService)
{}

protected function getOptionsForCart()
{
    if($this->cartService->getItems() === X){
        return ['option1', 'option2'];
    }

    return ['option2'];
}

This will break because there is a circular dependency. CartService relies on ShippingService and vice versa, yet it does seem logical that these would depend on each other....

I could do something like

CartService:

public function __constructor(public ShippingService $shippingService)
{}

// Various standard cart methods such as add() etc
...

protected function getItems()
{
    return $this->store->items;
}

protected function getShippingOptions()
{
    return $this->shippingService->getOptionsForCart($this);
}

ShippingService

public function __constructor()
{}

protected function getOptionsForCart(CartService $cartService)
{
    if($cartService->getItems() === X){
        return ['option1', 'option2'];
    }

    return ['option2'];
}

But this feels messy.

Is there a design pattern to deal with this particular kind of scenario?

Rule Engine design with multiple predicates

I am trying to implement Rule engine desing pattern in my use case but not able to fit the pieces in the right place.

RuleEngine is where all rules are validated for a transaction before making it approved

public class RuleEngine {
    private Predicate<Transaction> predicates;

    private Transaction transaction;

    public void setTransaction(Transaction transaction){
        this.transaction = transaction;
    }

    public void addRules(Predicate<Transaction> predicates) {
        this.predicates = predicates;
    }

    public void executeRules() {
        if(predicates.test(transaction)) {
            // all rules are valided - payment success
        }
    }
}

Below Payments class is invoked by parent where transaction and its type are provided.

Then based on transaction, rules are added which is the difficult part.

Because of transactionUtils - hard dependency required to autowired, causing predicate chaining looks very ugly and seems not the correct way.

@Component
public class Payments {

    @Autowired
    PredicateHelper predicateHelper;

    public void process(Transaction transaction, String type) {
        RuleEngine ruleEngine = new RuleEngine();
        ruleEngine.setTransaction(transaction);

        switch (type) {
            case "card" :
                ruleEngine.addRules(getCardRules());
                break;
            case "cash" :
                ruleEngine.addRules(getCashRules());
                break;
            default : log.error("Invalid case");
        }
        ruleEngine.executeRules();
    }

    private Predicate<Transaction> getCardRules(){
        return predicateHelper.rule1
                .and(predicateHelper.rule2)
                .and(predicateHelper.rule3);        // Predicate chaining 
    }

    private Predicate<Transaction> getCashRules(){
        return predicateHelper.rule1
                .and(predicateHelper.rule4)
                .and(predicateHelper.rule5);        // Predicate chaining
    }
}
@Component
public class PredicateHelper {

    @Autowired
    TransactionUtils transactionUtils;      // hard dependency - in house library

    public Predicate<Transaction> rule1 = transaction -> "rule1".equals(transactionUtils.getName(transaction));
    public Predicate<Transaction> rule2 = transaction -> "rule2".equals(transactionUtils.getName(transaction));
    public Predicate<Transaction> rule3 = transaction -> "rule3".equals(transactionUtils.getName(transaction));
    public Predicate<Transaction> rule4 = transaction -> "rule4".equals(transactionUtils.getName(transaction));
    public Predicate<Transaction> rule5 = transaction -> "rule5".equals(transactionUtils.getName(transaction));
}

Is there a ways to have better predicate chaining with this solution. Thanks in advance.

vendredi 14 juillet 2023

What could be the good way to check if N optionals returning from different functions all have values

Let say I have a code like that

#include <string>
#include <optional>
#include <charconv>

std::optional<int> get_1(const std::string& s) {  return s == "A" ? 1 : std::optional<int>{}; }
std::optional<const char*> get_2(const std::string& s) {  return s == "A" ? "2" : std::optional<const char*>{}; }
std::optional<double> get_3(const std::string& s) {  return s == "A" ? 3.0 : std::optional<double>{}; }
std::optional<int64_t> get_4(const std::string& s) {  return s == "A" ? -10000000000 : std::optional<int64_t>{}; }
std::optional<std::string> get_5(const std::string& s) {  return s == "A" ? "5" : std::optional<std::string>{}; }
// ..... more functions like that

struct S {
    int a1;
    const char* a2;
    double a3;
    int64_t a4;
    std::string a5;
private:
    int AGR_INIT_IS_NOT_ALLOWED{0};
};

std::optional<S> getS() {
    S s;
    // Now I'd like to return std::nullopt if any of the following calls return std::nullopt
    // The naive way to do that is smth like that

    if (auto val = get_1("A"); val) {
        s.a1 = *val;
    } else {
        return std::nullopt;
    }

    if (auto val = get_2("A"); val) {
        s.a2 = *val;
    } else {
        return std::nullopt;
    }

    if (auto val = get_3("A"); val) {
        s.a3 = *val;
    } else {
        return std::nullopt;
    }

    if (auto val = get_4("A"); val) {
        s.a4 = *val;
    } else {
        return std::nullopt;
    }

    if (auto val = get_5("A"); val) {
        s.a5 = *val;
    } else {
        return std::nullopt;
    }
    
    return s;
}

int main()
{
    return !getS();
}

Now my question is, can anyone advice on how to get rid of code replication inside getS function? Any pattern or smth that would work here?

The first obvious "solution" is instead of returning an optional just throw an exception inside get_* and then catch it in getS

#include <string>
#include <optional>
#include <charconv>
#include <exception>

int get_1(const std::string& s) {  return s == "A" ? 1 :throw std::exception{};}
const char* get_2(const std::string& s) {  return s == "A" ? "2" : throw std::exception{}; }
double get_3(const std::string& s) {  return s == "A" ? 3.0 : throw std::exception{}; }
int64_t get_4(const std::string& s) {  return s == "A" ? -10000000000 : throw std::exception{}; }
std::string get_5(const std::string& s) {  return s == "A" ? "5" : throw std::exception{}; }
// ..... more functions like that

struct S {
    int a1;
    const char* a2;
    double a3;
    int64_t a4;
    std::string a5;
private:
    int AGR_INIT_IS_NOT_ALLOWED{0};
};

std::optional<S> getS() {
    S s;
    try {
        s.a1 = get_1("A");
        s.a2 = get_2("A");
        s.a3 = get_3("A");
        s.a4 = get_4("A");
        s.a5 = get_5("A");
    } catch (const std::exception&) {
        return std::nullopt;
    }
    return s;
}

int main()
{
    return !getS();
}

I can't use exceptions, so it's not a solution at all (not to mention it is silly to refactor all these methods). Though, for now to me it looks like the best option it terms of avoiding boilerplate.

The second "solution" I was thinking about is to put all the optionals into tuple first, check if all them hold values and then assign from the tuple like that:

#include <string>
#include <optional>
#include <tuple>


std::optional<int> get_1(const std::string& s) {  return s == "A" ? 1 : std::optional<int>{}; }
std::optional<const char*> get_2(const std::string& s) {  return s == "A" ? "2" : std::optional<const char*>{}; }
std::optional<double> get_3(const std::string& s) {  return s == "A" ? 3.0 : std::optional<double>{}; }
std::optional<int64_t> get_4(const std::string& s) {  return s == "A" ? -10000000000 : std::optional<int64_t>{}; }
std::optional<std::string> get_5(const std::string& s) {  return s == "A" ? "5" : std::optional<std::string>{}; }
// ..... more functions like that

struct S {
    int a1;
    const char* a2;
    double a3;
    int64_t a4;
    std::string a5;
private:
    int AGR_INIT_IS_NOT_ALLOWED{0};
};

std::optional<S> getS() {
    auto t = std::make_tuple(get_1("A"), get_2("A"), get_3("A") ,get_4("A") ,get_5("A"));
    if (!std::apply([](auto&&... vals){ return ([](auto&& v){ return v.has_value(); }(vals) && ...);}, t)) {
        return std::nullopt;
    }

    S s;
    s.a1 = *std::get<0>(t);
    s.a2 = *std::get<1>(t);
    s.a3 = *std::get<2>(t);
    s.a4 = *std::get<3>(t);
    s.a5 = *std::get<4>(t);
    return s;
}

int main()
{
    return !getS();
}

That's not nice as we've got to execute all the get_* functions, even if the first one alrede returned std::nullopt (I also don't like to use std::get here)

And here I pretty much ran out of any good ideas how to achieve "exception based approach" w/o any exceptions.

jeudi 13 juillet 2023

Dynamic Provider in Nest JS

Today I have a payment service based on Nest JS.

I have 3 payment methods: PIX (brazilian payment), Boleto (brazilian payment) and credit card.

These payment methods are linked to a payment gateway (PagSeguro (Brazilian), PayPal etc.)

So I created a service like: createPixCharge, createBoletoCharge, createCreditCardCharge. These services communicate with the payment gateway API.

To make the code clean and scalable, I used the repository pattern. So, there is an abstract repository with methods like: createPixCharge (which returns a code that the customer will pay in his Brazilian bank - this code is universal)

I did this because today I use API 1, tomorrow I can switch to another platform.

Therefore, what could I do to, according to the chosen payment method, inject the desired repository dependency?

For example:

if customer chooses payment method X, it will inject API dependency 1. If client chooses payment method Y, it will inject API dependency 2

As I said, I created a service like createPixCharge, createBoletoCharge and createCreditCardCharge, which when invoked, depending on the payment method, will call the repository that integrates with the API.

But I don't know how to relate it all.

mercredi 12 juillet 2023

Proxy design pattern adding overhead when new APIs introduced

Im using proxy pattern to solve lazy loading problem. Trying to lazy initialize my class when member functions are invoked. I observe that if new api exposed in IOrder Interface, proxy class need to implement it and have initialization check which seems to be in-efficient, is there a better way to implement lazy initialization.

In text book example there is only one method which is considered to be doing heavy lifting task but in real time there could be many api which does heavy lifting so is there elegant way to check if realClass is initialized and forward the request to real class from proxy ?

class IOrder {
public:
    virtual OrderDetails get() = 0;
    virtual bool set(OrderDetails od) = 0;
}

class ProxyClass: public IOrder {
public:
    shared_ptr<RealClass> m_realClass;
    
    bool set(OrderDetails od) {
        if (nullptr == m_realClass) {
              m_realClass = std::make_shared<RealClass>();
              m_realClass->initialize();
        }
        m_realClass->set(od); // or by std::invoke
    }

    ...
}

class RealClass: public IOrder {
public:
    OrderDetails get() { ... }
    bool set(OrderDetails od) { ... }
    bool initialize() { ... }
}

Assume that if IOrder interface is exposed by some other library, if there is new api update then clients (proxy & real class) need to override it. Im looking for way to avoid proxy to override this. proxy bypass to real object if real object initialized.

Could not able to find results from google search for proxy design pattern lazy init issues.

What happens to the extrinsic state when using the Flyweight Design Pattern?

I am currently researching software design patterns and have been somewhat perplexed with the flyweight design pattern's implementation.

As far as I understand, the pattern works by separating the shared/constant intrinsic data from the unique, changing extrinsic data. The intrinsic data is kept in a set of objects that are managed by a factory class to prevent duplicate intrinsic data objects. This I understand.

What I don't get is what I do with the extrinsic data. In the examples I've seen which have mostly been about drawing shapes for some reason, the extrinsic data is just brought up to a higher level where it is passed into a method in the intrinsic object. Is this always the case or is this just a result of everyone using the shapes example?

One thought I had is to use composition to add a reference to the intrinsic object into an object with the extrinsic data. The only additional space in the object is the size of the reference. Would this work as a good example of the flyweight design pattern?

Thanks!

Using flat structure vs wrapper

We have a function with the below contract, we have data as a wrapper and all user details are inside that other option where data is without wrapper. I would love your view which option would you prefer and why?


export interface IContactSource {
  id: string;
  type: string;
}

export interface IContactSearchAttempt {
  firstName: string;
  lastName: string;
  email: string;
  title: string;
  accountName: string;
  linkedinUrl?: string;
  source: IContactSource;
}

export enum ISearchAttemptOperation {
  "CONTACT_PROFILE" = "CONTACT_PROFILE",
  "ACCOUNT_PROFILE" = "ACCOUNT_PROFILE",
}


// first:
export interface ISearchAttemptBody {
  operation: ISearchAttemptOperation;
  data: IContactSearchAttempt;
  attempt?: number;
}

// second:
export interface ISearchAttemptBody {
  operation: ISearchAttemptOperation;
  firstName: string;
  lastName: string;
  email: string;
  title: string;
  accountName: string;
  linkedinUrl?: string;
  source: IContactSource;  
  attempt?: number;
}

Project Generator [closed]

I am gonna build my own project generator with my own code style for Laravel using stubs files.

But at general i have some questions about the best pattern for something like this, also the best approach for implementing the generator .

The main reason for building this generator is practicing and revision OOP & design patterns concepts.

Also i wanna know what i should recover while building the generator.

I have idea like get data for modules from JSON file or from GUI, but i dont know if this is the optimal approach.

mardi 11 juillet 2023

Correct design pattern for invalidating cache after service bus event

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

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

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

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

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

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

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

using System;

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

    interface IPrintable {
        void Print();
    }

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

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

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

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

and a more traditional approach

// Traditional Approach

using System;

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

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

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

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

Thanks in advance!

lundi 10 juillet 2023

Two-Column Layout with Spanning Header

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

<div>
   Article Header
</div>

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

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

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

How to implement a generic type member of a class?

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

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

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

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

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

and use it like this?

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

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

dimanche 9 juillet 2023

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

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

#include <iostream>

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

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

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

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

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

Is there an alternative way to do this?

lottiefiles vs SVGs vs GIFs in flutter

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

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

How to create singleton classes dynamically in python

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

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

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

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


class TopicA(GTopic):
    instance = None

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

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

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

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

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


class TopicB(GTopic):
    instance = None

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

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

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

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

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

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

class GQueue:

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


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

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


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

    # Now I want to do something like :

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

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

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

Center the text widget inside transform scale in Flutter

How can we edit the children of this widget in a widget that we use transform scale?

Expected

Code:

Transform.rotate(
              angle: math.pi / 4,
              child: Container(
                height: 100,
                width: 100,
                color: const Color(0xff565758),
                child: const Text("Lorem ipsum"),
              ),
            ),

Problem

Tried transform, transform.scale, FittedBox widgets. And the result is as in the picture above.

Solve:

Stack(
          children: [
            Transform.rotate(
              angle: math.pi / 4,
              child: Container(
                height: 100,
                width: 100,
                color: const Color(0xff565758),
              ),
            ),
            const Positioned.fill(child: Align(alignment: Alignment.center, child: Text("Lorem ipsum")))
          ],
        ),

samedi 8 juillet 2023

Which design pattern is best suited for approval process?

Which design pattern is best suited for approval process workflow? For example: A user raises a request for access to a particular application. The request has to go through 3 level of approvals L1, L2, L3. These approvals can be by a person/user or a group of users(i.e., group is an entity like SecurityGroup which has 4-5 members assigned). The design should be flexible enough to include another level of approval if required. Also, there can be scenarios where only L1 and L3 approval is required or only L2 and L3 approval is required. If you could provide a pseudo code that will be good.

Pattern API Gateway for MSA

We design our system based on micro service architecture. I have a question: how do I go from my backend_1 (InformationSystem_1) to the backend_2 (InformationSystem_1). Do I need to make a api gateway(API_outside on image) for communicating with external systems, or is it possible to go from backend_1 to backend_2 directly?There are no security requirements, but the backend_2 is done by another team. Which pattern is better to apply?

It seems to me that you need to make a separate service for going outside (API_outside) to hide all the insides of the backend. But how justified is this? enter image description here

vendredi 7 juillet 2023

swiftui: How to create custom shape?

This might not be the best post, with the most detail and the most programming related. But I hope you will give some pointers anyway.

I am specifically asking about the indents in the backgrounds. And even more so, how to layer the "tabs" on top of each other.

Thanks.

I am trying to create something like this:

jeudi 6 juillet 2023

Using a dictionary dispatch with a tuple - facing issues with args

from collections import defaultdict
#I have over 15 such functions
def sub_scenario_J_Conf(data):
    if data["cnt"] == "J" and data["data_class"].lower() == "conf":
        if data["cnt"] == "J" or data["person"] > 50 or data["person_no"] >= 500:
            return "A"
        elif data["cnt"] != "J" or data["person"] < 50 or data["person_no"] <= 500:
            return "B"
        else:
            return "F"
    else:
        return "Invalid option"

def sub_scenario_W_Conf_misdirected(data):
    if data["cnt"] == "W" and data["data_class"].lower() == "conf" and data.get("inc") == "diff":
        if data["person"] > 50 or data["person_no"] >= 500:
            return "A"
        elif data["person"] < 50 or data["person_no"] <= 500:
            return "B"
        else:
            return "F"
    else:
        return "Invalid option"

cases = defaultdict(lambda: lambda data: "Invalid option", {
    ("J", "Conf"): sub_scenario_J_Conf,
    ("W", "Conf", "diff"): sub_scenario_W_Conf_misdirected,
})

#fails here
data = {
    "cnt": "J",
    "data_class": "Conf",
    "person": 60,
    "person_no": 1000
}
#works here
data2 = {
    "cnt": "J",
    "data_class": "Conf",
     "data_diff":"diff",
    "person": 60,
    "person_no": 1000
}

sub_scenario_func = cases.get((data["cnt"], data["data_class"], data.get("inc", "")))
if sub_scenario_func:
    result = sub_scenario_func(data)
else:
    result = "Invalid option"

print(result)

data.get("inc", "") I am facing an issue with this, as it is unable to handle conditions where some functions take an input of two, while some take 3 or 4. How do I fix this? Also, if there is a better way to deal with the if conditions, do let me know, it would be of great help .

Feature grouping with NestJS

We are developing a multi-tenant application but I'm running into a situation where I need to use forwardRef quite often which would indicate a code smell as mentioned in the docs of NestJS. Example of modules in this applications are: app, auth, company, paymet, projectc, survey, search, tenant and user (there are more in reality).

Each module has their own service (aka provider), model, etc. We are using Prisma so we don't have a separate file for the typical crud methods and they are located inside the service itself.

Example of why forward ref is needed

Tenant module

@Module({
    imports: [PaymentModule],
    providers: [TenantService],
})
export class TenantModule {}

Tenant service

@Injectable()
export class TenantService {
    async get(tenantId: number) {
        return prisma.tenant.findFirst({ where: { id: tenantId } });
    }

    async create(data) {
        // ... logic
        const tenantId = generateId();
        await PaymentService.createCustomer(tenantId)
        // ... logic
    }
}

Payment module

@Module({
    imports: [TenantModule],
    providers: [PaymentService],
})
export class PaymentModule {}

Payment service

@Injectable()
export class PaymentService {
    async createCustomer(tenantId) {
        // ... logic
    }

    async charge(tenantId: number) {
        const tenant = await this.tenantService.get(tenantId);
        // ... logic
    }
}

Question

My question is how should we adjust our structure to be more "feature grouping". Currently for example we are using the tenant service in a lot of the other modules and I don't see how it would be a "feature". Any guidance, tips, links, documents that would help are highly welcome. I don't really see another way of doing this and can't find good examples either.

Extract pattern from Machine learning model

have created an ML model for a sports betting dataset, and its accuracy is 90%. The dataset contains the following column names:

python Copy code ['League', 'Time', 'Hour', 'Minute', 'TeamA', 'TeamB', 'Result', 'Result_FinalTime', 'Result_HalfTime', 'Odds', 'Odd', 'FirstTeamToScore', 'LastTeamToScore', 'Winner_HT_FT', 'Result_HalfTime_Odd', 'Id', 'timedelta', 'timestamp', 'Data', 'HomeTeamWin', 'AwayTeamWin', 'Day', 'BothTeamToScore', 'BothTeamToNotScore', 'BothTeamToScoreAndOver2.5', 'under_1_5', 'under_2_5', 'under_3_5', '2GoalsExactly', '3GoalsExactly', '5GoalsOrMore', 'BothTeamsToScoreHalfTime', 'Over1.5HalfTime', 'DrawFinalTime', 'HomeTeamWinsHalfTime', 'AwayTeamWinsHalfTime', '1-1FinalTime', 'DrawHalfTime', 'HomeTeamWin2-0', 'AwayTeamToScore', 'over_1_5', 'over_2_5', 'over_3_5', 'under_0_5', 'total_gols', 'ambas_marcam_odd', 'over_1_5_odds', 'over_2_5_odd', 'over_3_5_odd', 'Home', 'Away', 'team1_score', 'team2_score', 'y'] I want to create patterns based on the following conditions:

Over 3.5 (more than 3 goals):

Sample: 3404 Successful: 764 Unsuccessful: 2640 Martingale needed: 2 times (Maximum 2) Success rate: 22.444183313748532% Description: After a match with more than 3 goals, place a bet on Over 3.5 goals. Under 1.5 (1 or fewer goals):

Sample: 3404 Successful: 754 Unsuccessful: 2650 Martingale needed: 2 times (Maximum 2) Success rate: 22.150411280846065% Description: After a match with 1 or fewer goals, place a bet on Under 1.5 goals. Under 2.5 (2 or fewer goals):

Sample: 3404 Successful: 1669 Unsuccessful: 1735 Martingale needed: 2 times (Maximum 2) Success rate: 49.030552291421856% Description: After a match with 2 or fewer goals, place a bet on Under 2.5 goals. Martingale can be from 0-2. I have prepared the feature matrix X and the target variable y as follows:

python Copy code import pandas as pd from sklearn.model_selection import train_test_split

Prepare the feature matrix X and the target variable y

X = data[['League', 'Hour', 'Minute', 'HomeTeamWin', 'AwayTeamWin', 'over_1_5', 'over_2_5', 'over_3_5', 'under_1_5', 'under_2_5', 'under_3_5']] # Adjust the column names as per your dataset y = data['y']

Split the dataset into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Initialize the XGBoost classifier

model = XGBClassifier() # Replace with the appropriate classifier

Fit the model on the training data

model.fit(X_train, y_train)

Evaluate the model on the training set

train_success_rate = model.score(X_train, y_train) * 100

Evaluate the model on the test set

test_success_rate = model.score(X_test, y_test) * 100

print(f"Training Success rate: {train_success_rate}%") print(f"Test Success rate: {test_success_rate}%")

I want to find patterns in the dataset using this model. Can anyone please help me with this?


python Copy code ['League', 'Time', 'Hour', 'Minute', 'TeamA', 'TeamB', 'Result', 'Result_FinalTime', 'Result_HalfTime', 'Odds', 'Odd', 'FirstTeamToScore', 'LastTeamToScore', 'Winner_HT_FT', 'Result_HalfTime_Odd', 'Id', 'timedelta', 'timestamp', 'Data', 'HomeTeamWin', 'AwayTeamWin', 'Day', 'BothTeamToScore', 'BothTeamToNotScore', 'BothTeamToScoreAndOver2.5', 'under_1_5', 'under_2_5', 'under_3_5', '2GoalsExactly', '3GoalsExactly', '5GoalsOrMore', 'BothTeamsToScoreHalfTime', 'Over1.5HalfTime', 'DrawFinalTime', 'HomeTeamWinsHalfTime', 'AwayTeamWinsHalfTime', '1-1FinalTime', 'DrawHalfTime', 'HomeTeamWin2-0', 'AwayTeamToScore', 'over_1_5', 'over_2_5', 'over_3_5', 'under_0_5', 'total_gols', 'ambas_marcam_odd', 'over_1_5_odds', 'over_2_5_odd', 'over_3_5_odd', 'Home', 'Away', 'team1_score', 'team2_score', 'y'] I want to create patterns based on the following conditions:

Over 3.5 (more than 3 goals):

Sample: 3404 Successful: 764 Unsuccessful: 2640 Martingale needed: 2 times (Maximum 2) Success rate: 22.444183313748532% Description: After a match with more than 3 goals, place a bet on Over 3.5 goals. Under 1.5 (1 or fewer goals):

Sample: 3404 Successful: 754 Unsuccessful: 2650 Martingale needed: 2 times (Maximum 2) Success rate: 22.150411280846065% Description: After a match with 1 or fewer goals, place a bet on Under 1.5 goals. Under 2.5 (2 or fewer goals):

Sample: 3404 Successful: 1669 Unsuccessful: 1735 Martingale needed: 2 times (Maximum 2) Success rate: 49.030552291421856% Description: After a match with 2 or fewer goals, place a bet on Under 2.5 goals. Martingale can be from 0-2. I have prepared the feature matrix X and the target variable y as follows:

python Copy code import pandas as pd from sklearn.model_selection import train_test_split

Prepare the feature matrix X and the target variable y

X = data[['League', 'Hour', 'Minute', 'HomeTeamWin', 'AwayTeamWin', 'over_1_5', 'over_2_5', 'over_3_5', 'under_1_5', 'under_2_5', 'under_3_5']] # Adjust the column names as per your dataset y = data['y']

Split the dataset into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Initialize the XGBoost classifier

model = XGBClassifier() # Replace with the appropriate classifier

Fit the model on the training data

model.fit(X_train, y_train)

Evaluate the model on the training set

train_success_rate = model.score(X_train, y_train) * 100

Evaluate the model on the test set

test_success_rate = model.score(X_test, y_test) * 100

print(f"Training Success rate: {train_success_rate}%") print(f"Test Success rate: {test_success_rate}%")

I want to find patterns in the dataset using this model. Can anyone please help me with this?