mercredi 31 août 2022

What is the name of that pattern in java?

What is the name of that pattern in java? Please see the implementation of RedirectAdultUserHandler1 and RedirectAdultUserHandler2 classes.

public class Main {

    public static void main(String[] args) throws Exception {
        new Main().run();
    }

    private void run() {
        final List<User> users = Arrays.asList(
            new User("john", 1),
            new User("jeff", 22),
            new User("jack", 333)
        );
        UserHandler handler1 = new RedirectAdultUserHandler1(new UserHandler());
        UserHandler handler2 = new RedirectAdultUserHandler2();
        handler1.processAll(users);
        handler2.processAll(users);
    }

}

class User {
    private final String name;
    private final int age;

    User(final String name, final int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public String toString() {
        return "User{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
    }
}

class UserHandler {
    public void processAll(List<User> users) {
        users.forEach(user -> process(user, "users"));
        System.out.println();
    }

    public void process(User user, String tableName) {
        System.out.printf("%s stored into %s%n", user, tableName);
    }
}

class RedirectAdultUserHandler1 extends UserHandler {
    private final UserHandler original;

    public RedirectAdultUserHandler1(final UserHandler original) {
        this.original = original;
    }

    @Override
    public void processAll(final List<User> users) {
        original.processAll(users);
    }

    @Override
    public void process(final User user, final String tableName) {
        if (user.getAge() >= 18) {
            original.process(user, "adult_users");
        }
        original.process(user, tableName);
    }
}

class RedirectAdultUserHandler2 extends UserHandler {
    @Override
    public void process(final User user, final String tableName) {
        if (user.getAge() >= 18) {
            super.process(user, "adult_users");
        }
        super.process(user, tableName);
    }
}

The RedirectAdultUserHandler1 is a decorator, but what about the RedirectAdultUserHandler2 one? Is there some name for that?

How to restrict access privilege between two classes in java?

I have two classes Player and Game

public class Player {
    private List<String> cards;

    public Player(){
        cards = new ArrayList<String>();
    }
}
public class Game {
    List<Player> players;

    public Game(List<Player> players){
        this.players = new ArrayList<Player>();

        for(Player player: players){
            this.players.add(player);
        }

    }

    private void distributeCards(){
        ...

    }

    public void start(){
        distributeCards()
        ...

    }

}

the distributeCards method of Game class needs to modify the cards attribute of a Player object. If I declare a public or protected method in the Player class for that, other classes in the same package will have the privilege as well but I don't want that. In this situation what can I do?

Let me know if I'm breaking any rules of design principles or design patterns.

How do I track users in my database without affecting response times?

I'm designing a big (for me) backend API with users and I want to try when users were last seen, and what IPs they are seen with (all of them).

The usual way I do this is with a simple middleware - the middleware checks if they are authenticated. If they are, it simply updates a database entry with the current time. Then the middleware just continues to the requested function.

However, I'm dealing with more data and I want this to be done as smoothly as possible - I want the middleware to finish ASAP with no blocking database operations. I have some ideas:

  1. I use FastAPI's background tasks to do this. I don't know how much overhead they induce, and given that they would be ran on EVERY route, this seems inefficient to be creating a background task just to update a timestamp in a database. If I want this to scale, I'd have to use celery or something, which might be even slower.

  2. Redis. This seems most likely; I could simply store the timestamp and IP keyed by their address. On an interval (15-60s), I could have the API look at all the entries and update the database accordingly. This should make the requests as fast they could be, no overhead, very scalable, and the true disk database would be updated in a period that is roughly 'real time'. I like this solution, but I worry it may be classified as premature optimization.

To be clear, the requirements I'm looking for are

  • Scalable. This has to work when 10,000 users are hitting my API simultaneously, otherwise I have to drop the feature.

  • Responsive - The design is probably going to use a middleware of sorts, and this has to exit instantly. I cannot have a working waiting on something like a DB transaction to go through. The response time must not be hindered by this feature.

  • Relatively Real-time - The database has to have these IPs and User IDs usable in less than 60 seconds. I could get fleixble with this requirement, but I'd rather not be waiting too long before things can be queried.

mardi 30 août 2022

Improving Polymorphism and Decorator pattern in Go

I'm working through a design patterns book and trying to apply the patterns to Go as a way to learn both.

Currently I have reached the decorator pattern and I ran into a scenario I was curious about.

Here is some sample code:

type Beverage interface {
    getDescription() string
    cost() float64
}

type HouseBlend struct{}

func (hb *HouseBlend) getDescription() string {
    return "House Blend Coffee"
}

func (hb *HouseBlend) cost() float64 {
    return .89
}

type Mocha struct {
    b Beverage
}

func (m *Mocha) getDescription() string {
    return m.b.getDescription() + ", Mocha"
}

func (m *Mocha) cost() float64 {
    return m.b.cost() + .20
}

What is the difference between

var hb Beverage = &HouseBlend{}

//This works since hb is an interface type
hb = &Mocha{
    b: hb,
}

And

hb := &HouseBlend{}

//This assignment fails since Mocha is not type HouseBlend
hb = &Mocha{
    b: hb,
}

This also works

hb := *new(Beverage)

    hb = &Espresso{}

    hb = &Mocha{
        b: hb,
    }

Is there a shorthand way of giving my variable hb the interface type or does it need to be explicit in order to be able to "decorate" my struct and reassign the variable to different types?

Any suggestions on improving the decorator pattern here and achieving clean polymorphism are welcome. Thank you!

Class that one of his members is object

Lets say I have class called Connection. One of his members is object that is instance of another class, class VerificationCode.

The class VerificationCode has 2 members: code and expiresAt.

Should I keep the VerificationCode and associate it with the member, or should I associate the 2 members code and expiresAt directly to the Connection class?

What are the advantages or disadvantages in terms of design/modeling?

Example:

Option 1:

Class VerificationCode{
code: string;
expiresAt: number;
}

Class Connection{
a: string;
verificationCode: VerificationCode;
}

Option 2:

Class Connection{
a: string;
code: string;
expiresAt: number;
}

C++: Access to element modifies object state

I have the case where i would like to be able to work on cartesian points (assumme 2d, double), with possibility of translation cartesian coordinates to polar coordinates.

I would also like to be able to override one-type point with other-type point, safely, and not to worry wheter it was performed or not. I was thinking of separate object storing two coresponding vectors, guarding access.

struct CartesianPoint
{
    double x, y;
};

struct PolarPoint
{
    double r, phi;
};

class Polar2Cartesian
{
public:
    Polar2Cartesian(const std::vector<CartesianPoint>&);
    void GetPolar(std::vector<PolarPoint>&) const;
// accessing vector of points in selected coordinates system, after modifications
    void GetCartesian(std::vector<CartesianPoint>&) const;
private:
    std::vector<CartesianPoint> cartesianPoints; // gets initialized in constructor by copying
    std::vector<PolarPoint> polarPoints; // gets initialized in constructor by recalculation
}

I wish i could perform operation of overriding points in both formats by changing one only. Here is example.

int main()
{
    std::vector<CartesianPoint> cp;

    // fill in vector
    ...
    ...

    Polar2Cartesian p2s{cp};
    
    int i; // just index
    i = ... //setting value (assume is in valid range do reverence elements of cp)

    p2c[i] = PolarPoint{1.0, 2.0}; // updates i-th point in both Polar and Cartesian coordinates
    // or
    p2c[i] = CartesianPoint{3.0, 4.0}; // updates i-th point in both Polar and Cartesian coordinates
    ...
    // some other work
    ...
    
    std::vector<PolarPoint> pp_after{};
    std::vector<CartesianPoint> cp_after{};

    p2c.GetPolar(pp_after);
    p2c.GetCartesian(cp_after);

    // have to vectors of SAME points in different coordinate systems
}

I am having hard time searching for simple solution of this problem. I will be happy to hear any sugesstion.

lundi 29 août 2022

Making sense out of PyArrow

I am browsing the tutorials and the documentation of PyArrow. I see some redundancies, for example, when reading a parquet Dataset (or folder) I could either

type1 = pyarrow.parquet.ParquetDataset("Pqfolder/", use_legacy_dataset=False)
# or
type2 = pyarrow.dataset.dataset('Pqfolder/', format='parquet')

What are pyarrow.parquet and pyarrow.dataset? Are they modules of the pyarrow package? Where do I find the docs? It looks like pyarrow.dataset is explained in https://arrow.apache.org/docs/python/api/dataset.html and pyarrow.parquet in https://arrow.apache.org/docs/python/parquet.html So i wonder why it is not pyarrow.api.dataset...

From what I understood the API (pyarrow.dataset) also allows you to filter the data with the scanner method, while with pyarrow.parquet I can only do the filtering when I read the file/s with filters but after that I can only read without filtering. Also, filtering is richer thanks to expressions... So, what's the point of having pyarrow.parquet if it can only do a subset of what pyarrow.dataset does (using a different notation)?

The issue here is that I have understood all this by guessing, trials and errors. Is this the standard way in which one learns about new libraries or did I miss some docs? I think I am missing some basics in software design. I was wondering if anyone could point me to some reference about this.

Observer pattern-observable is not present beforehand while initialising the observer

Is there any alternative or other way of implementing observer pattern to handle the case when observable is not present beforehand while initialising the observer. I want to make an object observer at later stage when observable object is created.

dimanche 28 août 2022

What is the best design pattern for handling same condition across multiple functions/classes

I have various functions that take user input and "construct a component" across multiple functions/classes. There will always be a core set of logic that gets executed regardless of the user input conditions, but recently, I found the need to add a configuration input and when it is set to true, additional logic will get executed. I feel like it is poor design to be passing this configuration flag around to various functions/classes, and it will also create a maintainability nightmare. What design pattern can I use to create a clean set of logic to handle this condition?

This is for a java desktop application.

Thanks

Different return values for use case

I have a structural problem in my PHP code which I want to get rid of, but I don't know how I can solve this in a clean matter (using a design pattern or whatever).

Imagine you have the following classes:

abstract class Person
{
  // return 0 = create, 1 = update, -1 error
  public function createOrUpdatePerson(string $firstname, string $lastname): int;
}

class DBPerson extends Person
{
  // overwrite
  public function createOrUpdatePerson(string $firstname, string $lastname): int;
}

class SessionPerson extends Person
{
  // overwrite
  public function createOrUpdatePerson(string $firstname, string $lastname): int;
}

Now, this functions are old and used by a frontend, which you don't want to touch. It expects you deliver an integer back. Now, you want to reuse this function in an API - but in this use case you want to return the id of the person instead of the operation code.

How would you handle that? I don't want to add an additional parameter (like isAPI or something like that) to respond with a different return type. For now, in case I'm in the API context, I call createOrUpdatePerson and afterwards try to fetch the item separately.

UsersService or PostsService should create post for user?

I have PostsRepository where I handle the process of post creation for user. But where "PostsRepository.create" method should be executed? In UsersService or PostsService?

How do I write a Python program to print the pattern? [closed]

How do I write a Python program to print the pattern? 543210 432105 321054 210543 054321 543210

Maintain the status of events in multithreading

I want to read records (1000k) from 1 table and push them to some service.

So I have clubbed 200 records(based on the service limitations) in 1 event and used the executor framework and have created 10 executors. 10 events will be processed (i.e. 10*200 records) parallelly.

Now I want to maintain the status of these events, like statistics on how many were processed successfully and how many failed.

So I was thinking of

Approach 1: Before starting the execution, writing each event id + record id with status

event1 + record1 -> start

and on completion

event1 + record1-> end

And later will check how many have both start and end in the file and how many do not have end.

Approach 2 : Write all record ids in one file with status pending and writing all successful records in another file

And then check for the missing in the successful file by using pivot

Is there a better way to maintain the status of the records?

vendredi 26 août 2022

Design problem when a base client uses a base class as input and derived client uses a derived class as input

My goal is to have a base client use a base class as an input. I would like to be able to extend the implementation of the base client through a derived client that takes a derived class as an input.

struct Base
{
    int a, b, c;
    ...
};

struct Derived: public Base
{
    int d, e;
    ...
};

class BaseClient
{
public:
    BaseClient(const Base& b) : b(b)
    {}
    void processA(){...}
    void processB(){...}
    ...

private:
    Base b;
};

class DerivedClient : public BaseClient
{
public:
    DerivedClient(const Derived& d) : BaseClient(d), d(d)
    {}
    void processD(){...}
    void processE(){...}
    ...

private:
    Derived d;
};

The bulk of the implementation is done in the BaseClient so taking advantage of that is a must. The problem I am having is that the Base class can get accessed in two different ways in the DerivedClient class. Once through the BaseClient and another through the Derived class data member. What is the best design practice in this situation?

Pattern based string parsing

I have below string as input

string input = "{A.0a,100,0002_VL}{=}{A.0a,0400,0001_VL}{+}{A.0a,0410,0002_VL}{+}{A.0a,0420,0003_VL}"

I want below output as string array

string[] output 

output[0] = "A.0a,100,0002_VL"
output[1] = "="
output[2] = "A.0a,0400,0001_VL"
output[3] = "+"
output[4] = "A.0a,0400,0002_VL"
output[5] = "+"
output[6] = "A.0a,0410,0003_VL"

I want to use RegEx.Split function but unable to identity a pattern. Is it possible to use? Kindly help me.

Thank you!

Paresh

How to reduce the number of variables in the signature of method in child class? Java refactoring

I have an abstract class A which does the main work, and also there are classes B and C which extend class A and implements the method doTheFinalMove().

public abstract class A {

    public Object aMethod() {
        Integer var1 = calculateVar1();
        String var2 = calculateVar2();
        Boolean var3 = calculateVar3();
        Object var4 = calculateVar4();
        Object var5 = calculateVar5();

        return doTheFinalMove(var1,
                var2,
                var3,
                var4,
                var5
        );
    }

    protected abstract Object doTheFinalMove(Integer var1,
                                             String var2,
                                             Boolean var3,
                                             Object var4,
                                             Object var5);

}

public class B extends A {

    @Override
    protected Object doTheFinalMove(Integer var1,
                                    String var2,
                                    Boolean var3,
                                    Object var4,
                                    Object var5) {
        return doMyStaff(
                var1,
                var2,
                var3,
                var4,
                var5);
    }
}

public class C extends A {

    @Override
    protected Object doTheFinalMove(Integer var1,
                                    String var2,
                                    Boolean var3,
                                    Object var4,
                                    Object var5) {
        return doMyStaff(var1, var2);
    }
}

So, class C unlike class B needs only two of the five variables to do its job, but in order to keep the inheritance of the class A, I should use all the five variables in the signature of doTheFinalMove() in A and C classes. I would like to refactor this code in the way that class C keep in its signature only those variables that it really needs (var1 and var2). I want to avoid using Object... args stuff, so I thought about wrapping these variables into an Object(I mean some inheritance like BasicParams and ExtendedParams) and then using an AbstractFactory or smth like that, but I don't know how to do it properly. I would be grateful for any advice.

jeudi 25 août 2022

Looping through all functions in a namespace in c++

My goal is to iterate over all functions of the namespace until a function returns me a valid strategy(enum). Each function can take different arguements.

enum class strategyType
{
    Strategy1,
    Strategy2,
    Strategy3,
    Strategy4,
    Strategy5,
    InvalidStrategy
}

namespace allFunctionStrategy
{
   strategyType algorithmMl(int v1,int v2);
   strategyType algorithmHeuristic(int v3,string s1);
   strategyType algorithmHeuristic(string s1,string s2);
   ... n such function's
}

class strategyContext
{
    int v1,v2,v3;
    string s1,s2;

/*i want to add iterator logic here*/
}

counting the number of consecutive repetitions

I have a list of elements :

list = ['green','green','red','blue','red','blue','yellow','white','black','yellow','white','black','red','green','yellow','black']

I want to group the consecutive repetitions, no matter what size they are. meaning that this is my desired output.

['green x2','red-blue-x2','yellow-white-black x2','red,'green','yellow','black']

I was able to achieve only a part of it with js, here's the code:

let repetition_count = 1
let repetition_list = []
list.forEach(element => {
    let prev_elem = list[index-1]
    if(element == prev_elem)
        {
            repetition_count++
            repetition_list.push(element)
        }
    else if(repetition_count>1){
            if(str.endsWith(repetition_list[0]+"-")){
                str = remove_last_word(str)
            }
            str+= repetition_list[0] + "x"+repetition_count+"-"
            repetition_count = 1
            repetition_list = []
        }
        str+= element+"-"
        index++;
    }
    

with some tweaks to the above code it produced the following output :

['green x2','red','blue','red','blue','yellow','white','black','yellow','white','black','red,'green','yellow','black']

now I don't know how to check more than one element for repetition.

I tried list comprehension with groupby (itertools) in python but it didn't work.

any suggestions?

mercredi 24 août 2022

How to use specific functions in specific classes that are all declared inside one protocol in swift?

I have a protocol declared in one class say 'Class MainClass', that protocol has 2 functions, e.g.:

protocol Test {
    func Cat()
    func Dog()
}

In Class A, I am implementing both the methods from the protocol eg:

Class A: Test {
func Cat(){
   print("I am cat")
}

func Dog{
  print("I am dog")
}

}

,but inside Class B I want to implement only Cat(). Xcode is not allowing me to add only one function from the Test protocol. How do I implement only one function from the same protocol, I dont want to create another protocol that has only Cat() in it. Please help. Thanks in advance.

How can I include design pattern in my class diagram

I'm creating a cinema ticket booking system. For that, I have to draw the class diagram first. But I don't know to draw the class diagram with my selected design pattern for my application.

I want my design pattern also included in my class diagram. How can I do that?

mardi 23 août 2022

What is the best way to achieve Smart Enum design-pattern in C#?

I was using Ardalis.SmartEnum package from Nuget.org.

I actually don't find it usefull when used in the following class hierarchy:

LicenseEdition class inside LibraryA.dll

public abstract class LicenseEdition : SmartEnum<LicenseEdition, byte>
{
    public static readonly LicenseEdition Empty = new EmptyLicenseEdition();
    protected LicenseEdition(string name, byte value) : base(name, value)
    {
    }

    private class EmptyLicenseEdition : LicenseEdition
    {
        public EmptyLicenseEdition() : base("Empty", 0)
        {

        }
    }
}

MyLicenseEdition class inside LibraryB.dll

public sealed class MyLicenseEdition : LicenseEdition
{
    public static readonly MyLicenseEdition Trial = new MyLicenseEdition( nameof(Trial), 1);
    public static readonly MyLicenseEdition Full = new MyLicenseEdition(nameof(Full), 2);

    public MyLicenseEdition(string name, byte value) : base(name, value)
    {
    }
}

Now everything is good. But https://www.nuget.org/packages/Ardalis.SmartEnum package itself leaks access to List of enums that inside LibraryA.dll

If I call MyLicenseEdition.List from Console App. (It returns empty List) Why? Because Ardalis.SmartEnum doesn't collect SmartEnum classes in LibraryB that depend on base SmartEnum<LicenseEdition> class in LibraryA. So the LibraryB sub-classes of LicenseEdition should be kept with LicenseEdition in LibraryA. (I can't do that Because I must have two libraries for my reasons I may have...).

After read many posts about Smart Enums (in Term). People found Smart Enum (Term itself I don't mean Ardalis Lib) is anti-pattern way itself..

Heres one: https://dev.to/entomy/smart-enum-what-jon-skeet-got-wrong-16m4

I don't find static/const members is advanced way to achieve (Smart Enums...) Its not made for that.

Back to my Problem I need to achieve this things.

  1. I don't need to use System.Enum, Because I need inheritable enums. (LicenseEdition is base for child Smart Enums).
  2. With normal System.Enum If I need provide my abstract/custom implmenetation I should provide a Generic to my Class: i.e:

So the only way to do this trick is that:

 public enum MyEdition
    {
        Standard,
        Full
    }

 public abstract class LicenseEntity<T> where T : Enum
    {
        public abstract T LicenseEdition { get; set; }
    }

    public class MyLicenseEntity : LicenseEntity<MyEdition>
    {
        public override MyEdition LicenseEdition { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
    }

Back to Questions:

  1. What do you think about above code?
  2. What patterns you should/good for smart enums pattern (Which doesn't exist in .NET by default).
  3. Do you find it usefull? Or we should just stuck on (non-mature System.Enum pattern? (Click for reasons - Image included))

Thank you all

Simple Java Builder Pattern Multiple Classes

Imagine we have 2 classes like this

class Foo{
   private Bar bar;

   ....
}

class Bar{
   ....
}

If we use Builder pattern for this, FooBuilder should have a Bar field or a BarBuilder field?

In the second case

//Constructor in Foo
public Foo(FooBuilder builder){
  ...
  this.setBar(builder.barBuilder.build());
}

lundi 22 août 2022

How to use Kotlin Singleton class in Java

I've both Kotlin and Java files in my project. I converted a Java Singleton class in Kotlin using object MySingletonClass. But still this is being used by many java classes so added the fun like this to use in Java

 @JvmStatic
    fun getInstance(): MySingletonClass{
       return this@MySingletonClass
    }

but when I compile the project get below error in all Java files Cannot access class 'MySingletonClass'. Check your module classpath for missing or conflicting dependencies

http request - How to implement fallback layer, if one authenfication way fails

I have created a program in C#.NET that also fires http queries and runs entirely on the intranet. These queries use NTLM authentication, which in rare cases may not work. For this case I would like to implement some kind of fallback layer that uses Basic Authentication with a stored default user. This default user has very limited rights, but this is usually sufficient. Nevertheless, my code should then send a mail to an internal distribution list, so that we get the problem.

What is the best way to implement such a fallback layer?

As a standalone class with the Chain of Responsibility pattern?

Basic structure:

  • Client wants to fire a http query
  • Handler checks if the NTLM authentication works
  • If the NTLM authentication does not work (401), it uses the basic authentication with the stored default user
  • Info mail goes to internal distribution list
  • If Basic authentication does not work either (401), an error is issued and info mail goes to internal distribution list

Essential Java Design Patteren for Kafka Souce and Sink Connectors Development

I am in the phase of pursuing my career as kafka connector developer for real-time analytics and data acquisition. I have been through so many courses either beginners or advance level from udemy.After learning i landed on some conclusion that more or less in all types of maven artifacts for source and sink connectors the build logic is same. Like creation of Final constants , configDefination, source-connectors, sink-connectors, data-model, schema-registry web-client-api , TaskClass etc. in seperate java classes. I want to know the following question from technical geeks of confluent or kafka developer regarding this type of implementation:

  1. From which java design pattern strategy it really belongs to Creational, Structural, Behavioral or Architectural Design Pattern?
  2. Let suppose if it is creational than why not it could be structural, or if it is structural than why it cannot be Behavioral and so on?
  3. Which Exactly sub-design pattern kafka developer and confluent community love to adapt in most of the different kind of scenarios?

I dont know whether the above questions really makes sense? If somene want to catch the fish on his own how one can write its own code following any GoF(Gang of Four) design pattern and contribute in the community of kafka and Confluent. Looking for detailed answer with reference material. Thank you

dimanche 21 août 2022

functional programming in php (file structure)

I've been reading a lot about functional programming and really want to dive in. The only thing I can't find resources for are file structure. I'm assuming MVC (being oop) is probably not the right architecture?

I saw another post on here that mentioned 'View First' structure but there was no elaboration.

Thanks in advance for your insight!

API Search Protocol, single or multilist on attribute ids

We are doing an attribute search on Products, and creating a search API.

The Product API, has attributes in its Request including VendorId (who sell the product), and LocationId (of where its sold). Below, is it best to make Vendor and LocationId an Array , instead of single? The front end search only allows single select dropdown. However what is best API practice of back end, to make it multiid search, in case of future requirements? I don't want to couple back end with front end.

public class GetProductRequest {
    private String productName;
    private Integer locationId;
    private Integer providerId;

    private String sortField = "ProductName,desc";
    private int pageNumber = 0;
    private int pageSize = 10;
}

What's the best way to write classes that are only different in some attributes?

public interface I {
    // ...
}

public class A {
    String name = "A";

    public String toString() {
        return "It is " + name;
    }

    // other methods... (might be different)
}

public class B {
    String name = "B";

    public String toString() {
        return "It is " + name;
    }

    // other methods... (might be different)
}

Like the example above, I have 2 identical class that are only different in the name attribute (and maybe some other methods). I want to extract the toString method to an interface or an abstract class and give it a default implementation. How can I do that?

samedi 20 août 2022

Global Environment Pattern CPP

I have a global environment object that contains some objects that can be accessed from many parts of the project (the members of the environment are io_context, logger and so on). That's why I have to pass this object to the constructors of almost all classes in the project (and store them as GlobalEnvironment&). Is it a normal architecture of the project or something better can be used?

P.S. I can not use Singletons because there can be several different environemts

How to perform action or render component before/after every http request in React?

I want to know if there is a way to create a kind of middleware in React?

What i want is to have an alert component show if there is a failing result for an http request.

Right now, i am making http request on login,registration,etc and i am importing my alert component in every page and setting the Alert component props like type, message, visibility everywhere i need the component, but i think maybe there is a better way of doing this.

Here is my code:


...imports

export const RegisterPage = () => {

  const [alertConfig, setAlertConfig] = useState({
    type: "",
    message: "",
    show: false,
  });

...code

const onSubmitHandler = async (e) => {
    e.preventDefault();
    if (!isFormValid()) return;

    const formData = new FormData();

    formData.append("password", formValues.password);
    if (formValues.provider.startsWith("8")) {
      formData.append("contact", formValues.provider);
    } else {
      formData.append("email", formValues.provider);
    }

    setIsLoading(true);
    try {
      const response = await fetch(
        `${process.env.REACT_APP_API_URL}/auth/register`,
        {
          method: "POST",
          body: formData,
        }
      );

      const data = await response.json();

      if (data.status === "success") {
        const { token, user } = data.data;

        dispatch(setCurrentUser(user, token));

        navigate("/choose-actor");
      } else {
        setAlertConfig({
          type: "warning",
          message: data.message,
          show: true,
        });
      }
    } catch (error) {
      console.log(error);
      setAlertConfig({
        type: "danger",
        message: "Ocorreu algum erro",
        show: true,
      });
    } finally {
      setIsLoading(false);
    }
  };
return 
    ...html
        {alertConfig.show && <Alert {...alertConfig} />}
    ...more html

As you can see, i am changing the configuration for the alert inside inside the function that executes the http request, and i have to do the save for every page that performs this action.

I looking for a design patter where i dont have to repeat myself.

Hope my question is clear.

vendredi 19 août 2022

Advice on small public API design. Builder pattern?

I have the following use case, and I don't have enough experience to know how this is usually handled:

I am reading a file which contains some messages; these messages are divided into chunks. A Chunk is:

pub struct Chunk {
    device_id: u32,
    channel_id: u8,
    chunk_id: u16,
    payload: Vec<u8>,
}

The payload is a slice of the actual message, the chunk_id sets the position of the payload within the message. All chunks with the same device_id and channel_id form a single message.

Then a Message is:

pub struct Message {
    device_id: u32,
    channel_id: u8,
    total_payload: Vec<u8>,
}

And I have implemented TryFrom as:

impl TryFrom<Vec<Chunk>> for Message {
    type Error = String;

    fn try_from(mut chunks: Vec<Chunk>) -> Result<Self, Self::Error> {
        // Check a bunch of stuff
        // All chunks belong to the same device_id
        // All chunks belong to the same channel_id
        // etc.

        let device_id = chunks[0].device_id;
        let channel_id = chunks[0].channel_id;
        chunks.sort_unstable_by_key(|c| c.chunk_id);
        let total_payload: Vec<u8> = chunks.into_iter().flat_map(|c| c.payload).collect();

        Ok(Message {
            device_id,
            channel_id,
            total_payload,
        })
    }
}

This all works great. Now my question is: How should I handle receiving all the Chunks (from multiple device_id and channel_id)?

I was thinking about a MultipleMessagesBuilder with an add_chunk function, to which I can give it Chunks one by one. This will internally "sort" each chunk into an appropriate Vec<Chunk> depending on the device_id and channel_id. Once I have passed all the chunks, I can then call a initialize method, and it will try to make the messages from the vectors.

Does something like this make sense? How would the public API of this MultipleMessagesBuilder look like? I can't imagine a reasonable way to then obtain the messages, the errors of the ones that fail, etc.

Does youtube create folder for each channel?

I am implementing a channel system on my website. I have all the channel related information stored in a database and when someone clicks on a channel I do something like this: www.website.com/channel?id=4. Upon loading the channel.php, I use PHP to retrieve all the variables and necessary files.

I noticed many video hosting sites with channels have their url look like something like this: www.website.com/channel/channelname. Upon interacting on that page, the url then looks like www.website.com/channel/channelname/playlist when I click the playlist tab.

  1. Do these sites create folders per channel/user?
  2. Does that mean each channel/user has an autogenerated file called (in the example above) playlist.php?
  3. How can I set the url www.website.com/channel/channelname to load the index in that folder?
  4. In question 2, rather than having the playlist.php file in each and every single channel folder, somehow access playlist.php while not creating a folder. How can I make a template file rather than creating many instances of the file?
  5. Is there a way to make the URL appear as www.website.com/channel/channelname without creating the folder channelname?

Design Pattern: How to handle different version of class which has different properties?

My C# app reads json file which changes over time (weekly or monthly) and it has to support all the versions. For example,

Version 1
{firstname:"John", lastname:"Doe"}

Version 2
{firstname:"Tony", lastname:"Doe", address:{line1:"Xavier", line2:"California"}}

Version 3
{firstname:"Adam", lastname:"Wood", address:{line1:"13 House", line2:"Texas", pincode: 12345}}

My C# class which deserialise the json looks like below,

// Version 1
public class DetailsV1: IBase
{
    private string firstname;
    private string lastname;
}

// Version 2
public class DetailsV2: IBase
{
    private string firstname;
    private string lastname;
    private AddressV1 address;
}

// Version 3
public class DetailsV3: IBase
{
    private string firstname;
    private string lastname;
    private AddressV2 address;
}

From my brief search in Google, it says Strategy pattern is a good choice for this kind of problem. So, I created a context class like below,

public class Context
{
    private IBase details;
    private int version;

    public Context(int version, string path)
    {
        this.version = version;
        // TODO The version should be parsed from the file
        if (version == 1)
        {
            this.details = new DetailsV1(path);
        }
        else if (version == 2)
        {
            this.details = new DetailsV2(path);
        }
        else if (version == 3)
        {
            this.details = new DetailsV3(path);
        }
        else
        {
            throw new NotImplementedException();
        }
    }

    // To avoid unnecessary boilerplate, I believe the below functions should return only primitive types
    public int getPinCode()
    {
        if (version == 1)
        {
            throw new NotAvailableInThisVersionException();
        }
        if (version == 2)
        {
            throw new NotAvailableInThisVersionException();
        }
        if (version == 3)
        {
            var address = (this.details as DetailsV1).address;
            var pc = (address as AddressV2).pincode;
            return pc;
        }
        else
        {
            throw new NotImplementedException();
        }
    }
}

Below are my queries,

  • Is this correct design pattern or is there any other better design pattern for my usecase? My versions can grow upto 400+ and thus, my class also grows. I feel this if/else will look ugly (and error prone?).
  • If this is the correct design pattern, Is it correct to cast the address in getPinCode or this has to be handled inside the DetailsV3 class (i.e) DetailsV3 should have a method called getPinCode?
  • If this is the correct design pattern, then I presume these methods should provide only primitive types (or types I am sure going to be static forever). Am I right?

Pattern programing in python [closed]

I have been trying for a long time but failing to make a code for it. Please share a code for the above pattern because I'm struggling to make it out.

543210
432101
321012
210123
101234
012345

Is there a cleaner way to implement a "if in a if" statement?

Is there another way to make this:

  1. More readable; and
  2. use fewer lines of code?

This code structure just looks like it's still not complete. Is there any refactoring that can be applied to this to make it "cleaner"?

        if (someVariable){
            bool otherVariable = SomeMethod();

            if(otherVariable){
                // Do something here
            } else {
                // Do something here
            }
        } else {
            // Do something here
        }

jeudi 18 août 2022

Web API - Direct calls to different API's based on API version

Version one controllers call an existing Web API to get data.

Version two controllers need to call a new Web API to get data.

How can we change these call based on the version?

Do we need to create new service or handler to handle this? Or Is there any design pattern I can use to make changes?

Make a class iterable from a property using [Symbol.iterator] as generator function

I'm trying to make Month class iterable from a property in the constructor. So I used this[Symbol.iterable] as a generator function inside a constructor scope to be able to use the for...of loop and get access to the sequence of days. I'm following this tutorial, but it uses Vanilla JavaScript. The problem is happening in the iterator typing, I don't know what to do. If it works in pure JavaScript, I think it should work in TypeScript using the right typing.

//class Month

class Month {
  lang: string;
  name: string;
  number: number;
  year: number;
  numberOfDays: number;
  [Symbol.iterator]: () => Generator<Day, void, undefined>; // here is the problem

  constructor(date = null, lang = 'default') {
    const day = new Day(null, lang);
    const monthsSize = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    this.lang = lang;

    this.name = day.month;
    this.number = day.monthNumber;
    this.year = day.year;
    this.numberOfDays = monthsSize[this.number - 1];

    if (this.number === 2) {
      this.numberOfDays += isLeapYear(day.year) ? 1 : 0;
    }

    this[Symbol.iterator] = function* () {
      let number = 1;
      yield this.getDay(number);
      while (number < this.numberOfDays) {
        ++number;
        yield this.getDay(number);
      }
    };
  }

  getDay(day: number) {
    return new Day(new Date(this.year, this.number - 1, day), this.lang);
  }
}

const month = new Month();

for(day of month) {
  console.log(day.Date)
}

//other code needed

const getWeekNumber = (day: Date) => {
  const firstDayOfTheYear = new Date(day.getFullYear(), 0, 1);
  const pastDaysOfYear =
    (day.getTime() - firstDayOfTheYear.getTime()) / (24 * 60 * 60 * 1000);

  return Math.ceil((pastDaysOfYear + firstDayOfTheYear.getDay() + 1) / 7);
};

const isLeapYear = (year: number) =>
  year % 100 === 0 ? year % 400 === 0 : year % 4 === 0;

class Day {
  Date: Date;
  dayOfMonth: number;
  dayNumberOfWeek: number;
  dayNameOfWeek: string;
  dayNameOfWeekShort: string;
  year: number;
  yearShort: number;
  month: string;
  monthNumber: number;
  monthShort: string;
  timestamp: number;
  week: number;

  constructor(day: Date | null = null, lang = 'default') {
    day = day ?? new Date();

    this.Date = day;
    this.dayOfMonth = day.getDate();
    this.dayNumberOfWeek = day.getDay() + 1;
    this.dayNameOfWeek = day.toLocaleString(lang, {
      weekday: 'long',
    });
    this.dayNameOfWeekShort = day.toLocaleString(lang, {
      weekday: 'short',
    });
    this.year = day.getFullYear();
    this.yearShort = Number(day.toLocaleString(lang, { year: '2-digit' }));
    this.month = day.toLocaleString(lang, { month: 'long' });
    this.monthNumber = day.getMonth() + 1;
    this.monthShort = day.toLocaleString(lang, { month: 'short' });
    this.timestamp = day.getTime();
    this.week = getWeekNumber(day);
  }

  get isToday() {
    return this.isEqualTo(new Date());
  }

  isEqualTo(day: Day | Date) {
    day = day instanceof Day ? day.Date : day;

    return (
      day.getDate() === this.dayOfMonth &&
      day.getMonth() === this.monthNumber - 1 &&
      day.getFullYear() === this.year
    );
  }

  format(dateStr: string) {
    return dateStr
      .replace(/\bYYYY\b/, this.year.toString())
      .replace(/\b(YYY|YY)\b/, this.yearShort.toString())
      .replace(/\bWWW\b/, this.week.toString().padStart(2, '0'))
      .replace(/\bW\b/, this.week.toString())
      .replace(/\bMMMM*\b/, this.month)
      .replace(/\bMMMM\b/, this.month)
      .replace(/\bMMM\b/, this.monthShort)
      .replace(/\bMM\b/, this.monthNumber.toString())
      .replace(/\bM\b/, this.monthNumber.toString())
      .replace(/\bDDDD\b/, this.dayNameOfWeek)
      .replace(/\bDD\b/, this.dayOfMonth.toString().padStart(2, '0'))
      .replace(/\bD\b/, this.dayNumberOfWeek.toString());
  }
}

Runtime performance vs. independent components

I usually face a situation where I need to use N components, each of which needs to query something. For example, read a value from the DB.

Now there are two ways to do this:

  1. Each component will query the data independently
  2. Parent/container will do a batch query for all components and feed the part of the data as input to each component

With 1, you have a nice independent reusable component but N queries to the DB which is not efficient.

With 2, you have a good performance (Just need to make 1 DB query) but in terms of design, your components have more dependencies now. You need to provide them with that piece of data they need from DB.

Is there a 3rd way or a trade-off to having an independent, but performant system?

Which design pattern should we use for category of tenants / users?

Existed Code - We can perform CRUD on tenant and also we have business method for same in business layer. Who can perform actions against tenant - Restricted to two users (Role_A & Role_B). TenantController -> TenantService -> TenantDAO

New Scenario - Now we are introducing tenantCategory so older tenants will be known as Tenant_A and new tenants will be known as Tenant_B.

What we did - Used If else in same TenantService code and did what was required for new use case.

  • Skip few fields
  • Added few new fields
  • Added new validations
  • Did authorization in same method using if else as initially we were allowing two users (A & B).We used @PreAuthorization but for this new tenant only B can perform the actions.

What can be do better - Can use design pattern to separate the flow. I did some research and get to know suitable design pattern are -

  1. Strategy
  2. Decorator
  3. Visitor

But still not sure which one is suitable pattern.

Techstack - Java 11 & Spring Boot

mardi 16 août 2022

Why is there a "Get Status" step when implementing Async APIs w/ Polling?

Often times I see the following for polling:

  1. Send a request and get a unique ID back.
  2. Poll a "Status" endpoint, which tells the client when the request has been completed.
  3. Send a request to fetch the response.

Can't steps (2) and (3) be combined? If the response isn't ready, it'll return no response back, and some status indicating that. If it is ready, it'll return the response.

Why is (2) and (3) often separate steps?

Thanks!

How to do DI with DbContext that will change connection string in runtime? (C# Net 6)

in my team we have multiple databases, one for every client that works with us. In our API we only work with one database, so we do dependency injection of the DbContext using the connection string loaded inside appsettings (one instance of this API for every client). Now we have to access different databases with the same structure, and we don't know how to work properly with dependency injection in this case.

The way we have to obtain the connection string for every client is querying a parametry database that has them in a table.

enter image description here

We receive a request that contains that client_id and, based on that id, we obtain the connection string and use it to access the database.

So we must find a way to do DI after we have obtained that connection string that I need in that moment.

lundi 15 août 2022

How to design MVC in C++? [closed]

I'm trying to apply MVC architecture on my project. Refering to spring-webmvc, I found that View will be rendered by ModelMap(a class inherit LinkHashMap<String, Object>).

However, in C++, not everything is an Object. A view cannot simply get attributes it wants from map<string, object>. How to deal with this problem?

Allow class to modify singleton only if it has implemented interface

I have a singleton that's acting as a core setup and manager for a large application. I want to restrict write access to callers outside the singleton but still allow it only if they've implemented a specific interface I define (e.g., ICoreModifier)

The desired outcome is below:

public class Core
{
    // singleton code omitted

    int Property { get; set; }
}
public class A : ICoreModifier
{
    // implemented ICoreModifier so things are okay
    Core.GetInstance().Property = 1;
}
public class B
{
    // No ICoreModifier implementation so this results in compile or runtime error
    Core.GetInstance().Property = 1;
}

However, there's two issues I'm running into with this.

  1. I'm having trouble coming up with what would actually go on the interface. This tells me I must be following the wrong design structure. I'm open to alternative approaches. I've been thinking about some sort of Lock and Unlock kind of method implementation requirement, but delegating write access to the person asking to write sounds like a bad idea and probably wouldn't even work.

  2. Ideally, I'd like for this to be a compile time error rather than runtime. If that's not possible that's okay, but I'm still not quite sure how I go about doing a runtime check. My current thinking is to use reflection, but that seems messy and not very robust.

I've considered inheritance as well, but my understanding is that inheritance is with regard to is-a relationships. The classes getting write access are not cores themselves. This is why the can-do relationship interfaces provide seem most appropriate to me here.

How can I accomplish this?

Mouse controls for interacting with user interface

I'm making JS application which allow to create SVG Diagrams.
Some thing like that: https://app.dgrm.net/
And problem that I don't know how to build controls system. There are a lot of actions: drag, resize, select, change text, hover and etc. And all that stuff is related and there can be conflicts. It's not a problem to implement everything, but code will be bad and messy. And we have a lot of applications with the resolved problem and I don't want to reinvent the wheel.


The Question is: How to organize this stuff? Maybe there are some good articles or a pattern.


Also want to notice that I don't need technical advices, I need to figure out a design.
Also I explored source code on github of similar projects but I'm not sure if they used "right" option.

dimanche 14 août 2022

How to use Logger class as Singleton

I want to use my Logger class as a Singleton. But I can't understand what exactly I am doing wrong even after the reading several topics and wathcing a lot of videos I am still confused what I am doing wrong. Below is my class

import inspect
import logging as log
from env_setup import *


class Logger:
    @staticmethod
    def custom_logger(level):
        logger_name = inspect.stack()[1][3]
        logger = log.getLogger(logger_name)
        logger.setLevel(level)
        log_book = log.FileHandler(LOG_FILE) # LOG_FILE is getting from env_setup module where the path to file stored in
        formatter = log.Formatter("%(asctime)s - %(levelname)s - %(message)s", datefmt='%m/%d/%Y %I: %M: %S %p')
        log_book.setFormatter(formatter)
        logger.addHandler(log_book)
        return logger

And the usage is as below in another module:

class SomeClass:
    def __init__(self):
        self.log = Logger.custom_logger(level=log.INFO)

    def some_func(self):
        try:
            1 == 1
            self.log.info('passed as correct')
        except Exception:
            self.log.error('errored')
            raise Exception('Exception raised')

What exactly should I change in order to make this class as a Singleton. I need to store this object as a single object in my code. Thanks.

What design pattern might help us implement a simple stream filter (or interpreter)?

This is kind of a "white-board" question instead a "keyboard" question as it is not language-specific.

I often have a stream of characters which must be translated from one "language" to another...

EXAMPLE ONE: UPS & DOWNS

+---------------+---------+--------+---------+--------+---------+---------+---------+
| INPUT STREAM  | (-1, 0) | (0, 1) | (0, 1)  | (0, 1) | (0, -1) | (0, 1)  | (0, 1)  |
+---------------+---------+--------+---------+--------+---------+---------+---------+
| OUTPUT STREAM | "left"  | "up"   | "right" | "up"   | "down"  | "right" | "right" |
+---------------+---------+--------+---------+--------+---------+---------+---------+

EXAMPLE TWO: Toggling Between Cases

You can force stream output to be pure lower-case or pure upper-case and use a "$" character to toggle between different modes:


+---------+----------+-------------+-----------+----------------+----------------+---------------+---------------+--------------+--------------+
| INPUT:  | "ApPleS" |     "$"     | "BaNaNaS" |      "$"       | "BLACKberries" |      "$"      | "BlUeBeRrIeS" |     "$"      | "CaNtAlOuPe" |
+---------+----------+-------------+-----------+----------------+----------------+---------------+---------------+--------------+--------------+
| OUTPUT: | "APPLES" | toggle mode | "bananas" | "BLACKBERRIES" | toggle mode    | "blueberries" | toggle mode   | toggle mode  | "CANTALOUPE" |
+---------+----------+-------------+-----------+----------------+----------------+---------------+---------------+--------------+--------------+

Suppose that you had a class named CharEater which eats elements of a stream and sends new (translated) elements to another stream.

Exactly what characters the CharEater outputs should vary depending on what "mode" the stream filter is in.

Maybe are only a handful of modes (4 to 7 modes) that the class can be in.

I usually write very ugly code which amounts to a bunch of:

  • nested loops
  • if-else clauses
  • boolean flags.

For some reason, my boolean flags usually have names beginning with the word "is" or "has", such as:

  • "is_valid"
  • "is_digit"
  • "is_red".
  • "is_blue".
  • "has_hit_rock_bottom".

An example of some ugly code is shown below:

import io

def eat_the_string(chars:str):
    """
    The implementation here is ugly

    However...
        we accept a string as input

        we convert letters to upper case or lower case

        A dollar sign ($) is used to toggle between upper-case mode
        and lower-case mode.

    EXAMPLE
        INPUT:
            "ApPleS $ BaNaNaS $ BLACKberries $ BlUeBeRrIeS $ CaNtAlOuPe"
        OUTPUT:
            "APPLES  bananas  BLACKBERRIES  blueberries  CANTALOUPE"
    """
    strm = io.StringIO() # a string stream
    is_lowercase = False
    for ch in chars:
        if ch == "$":
            is_lowercase = not is_lowercase
        else:
            if is_lowercase:
                print(
                    ch.lower(),
                    file=strm, sep = "", end = ""
                )
            else: # in uppercase mode
                print(
                    ch.upper(),
                    file=strm, sep="", end=""
                )
    return strm.getvalue()

I am seeking a more elegant solution.

A bunch of nested loops with a handful of boolean flags is not great for many reasons.

Two drawbacks are:

  • the mess of boolean flags and test conditions is difficult for human beings to read and understand
  • a lot of the test-conditions are redundant. I sometimes an if statement for is_first_iteration == True even though it is guaranteed that is_first_iteration will be False after the first loop iteration.

What is an example of a better design pattern (or approach) for implementing a stream filter whose output changes based on what mode the stream filter is in? We probably do not need a full-blown general-purpose parser and interpreter, but that is one option.

Below is one attempt to re-factor the mess of nested-loops with boolean flags. Feel free to steer me in a different direction.

# import tools for abstract base classes
import io
from abc import ABC, abstractmethod

class PacAbstract(ABC):
    # This is an abstract base class

    @abstractmethod
    def process_a_char(this, ch: str):
        """
            Input paramater `old_ch` is a char, such as the letter "A"
        """
        pass  # `pass` is no_op().... no_operation()... do nothing.


class PacModeLowercase(PacAbstract):
    """
        `PacModeLowercase` converts
        string characters into lower-case letters
    """

    def process_a_char(this: PacAbstract, ch: str):
        """
            Input parameter `old_ch` is a char, such as the letter "A"
        """
        return ch.lower()


class PacModeUppercase(PacAbstract):
    """
         This class represents a **mode**
         for an `PacMan` to be in.

        `PacModeUppercase` converts
        string characters into upper-case letters
    """

    def process_a_char(this: PacAbstract, ch: str):
        # Input paramter `old_ch` is a string, such as "hello world"
        return ch.upper()


class PacMan(PacAbstract):
    PacModeUppercase = PacModeUppercase
    PacModeLowercase = PacModeLowercase
    # Like the videogame character named "pacman,"
    # a `PacMan` eats things.
    #
    # a PacMan has a pointer (or reference) to a PacMode
    # `PacMode` represents the **mode** which the PacMan is in
    #
    # The mode determines what PacMan outputs.

    def __init__(this: PacAbstract, *, mode: str = "lower"):
        # __init__ is sort of like a class constructor.
        #
        # However, the true constructor is type.__call__()
        #
        # In other languages,
        # `__call__()` is sometimes known as ``
        #
        # All of the following are equvilant:
        #    instance = PacMan(1, 2, 3)
        #    instance = type.__call__(PacMan, 1, 2, 3)

        # Error checking. make sure mode is string-like
        mode = "".join(str(ch) for ch in mode)

        # Get modified copy with trimmed leading and traiPacAbstract white space
        mode = mode.strip()

        # Get modified copy with uppercase letters
        # converted to lowercase letters
        mode = mode.lower()

        if mode == "lower":
            this._pac_mode = type(this).PacModeLowercase()
        else:
            this._pac_mode = type(this).PacModeUppercase()

    def process_a_char(this: PacAbstract, ch: str):
        """
            Input paramter `old_ch` is a string, such as "hello world"
        """
        return this._pac_mode.process_a_char(ch)


pacman = PacMan()

strm = io.StringIO()
inputs = "ApPleS $ BaNaNaS $ BLACKberries $ BlUeBeRrIeS $ CaNtAlOuPe"
for old_ch in inputs:
    new_ch = pacman.process_a_char(old_ch)
    print(new_ch, file=strm, sep="", end="")

print(strm.getvalue())
# output is "apples $ bananas $ blackberries $ blueberries $ cantaloupe"

Anyway.... what is the name of a design pattern such that the data coming out of a stream filter varies depending on what "mode" the stream filter is in?

Below is code written to convert camel-case to lower-case letters and under-scores.

The code is written in the anti-pattern of nested loops, boolean flags, and buffers:

def camel_to_underscore(chars:str):
    """
    The implementation here is an anti-pattern 

    The code is hideous mess of nested-loops, boolean
    flags, test-conditions, and string buffers. 

    EXAMPLE A:
        INPUT:  "getUserInput()"
        OUTPUT: "get_user_input()
        
    EXAMPLE B:
        INPUTS: 
                RedDeliciousApples
                GrannySmithApples
                ConcordGrapes
                GreenGrapes
        Outputs:
                red_delicious_apples
                granny_smith_apples
                concord_grapes
                green_grapes
    """
    chars = "".join(str(ch) for ch in chars)
    it = iter(chars)
    buffer = []
    buffer.append(next(it).lower())
    for ch in it:
        low_ch = ch.lower()
        if low_ch != ch:
            buffer.append("_")
        buffer.append(low_ch)
    return "".join(buffer)

If you do not have the name of a design pattern, do you have some pseudo-code different from the nest-loops with boolean flags? Maybe some sort of class object whose method outputs change depending on what "mode" the class is in?

EXAMPLE THREE: Removing Consecutive Duplicates

An example of a more complicated application might be to delete repeated sub-strings:

  • we read a string from left to right
  • if the same sub-string repeats itself ("Echo Echo Echo Echo") then we delete the redundant copies.
  • we allow a single character to repeat up to 2 times, but no other string may repeat.
INPUT OUTPUT
"Misssssssssissssssssippppppppppi" "Mississippi"
"apple apple apple apple" "apple"
"orange orange orange orange orange" "orange"
"\n\n\n\n\n\n\n\n" "\n"

samedi 13 août 2022

Use of Director and Builder Patterns for Complex Objects

I think I am getting confused between Directors and Builders. I need to build a series of different types of massages. Each message type is built from segments, however one segment type can be used in multiple message types. The input object for all messages and segments is the same.

Here is what I have been working on (simplified):

public class AdtA28Director implements AdtDirector {
    private static final String MESSAGE_TYPE = "A28";
    private Patient patient;

    public AdtA28Director(Builder builder) {
        this.patient = builder.patient;
    }
    
     public String toString(){
            return new StringBuilder("AdtBuilder:Type:Patient:").append("A28").append(":").
            append(patient).toString();
        }

    static class Builder {
        private Patient patient;
        private ADT_A05 adtMessage;
        
        public Builder(Patient patient) {
            this.patient = patient;
        }

        public Message build() throws HL7Exception, IOException {
            String currentDateTimeString = getCurrentTimeStamp();
            adtMessage = new ADT_A05();
            adtMessage.initQuickstart("ADT", MESSAGE_TYPE, "P");
            createMshSegment(currentDateTimeString);
            createEvnSegment(currentDateTimeString);
            return adtMessage;
        }
        
        private void createMshSegment(String currentDateTimeString) throws DataTypeException {
            MSH mshSegment = _adtMessage.getMSH();
            mshSegment.getFieldSeparator().setValue("|");
            mshSegment.getEncodingCharacters().setValue("^~\\&");
            mshSegment.getSendingApplication().getNamespaceID().setValue("Our System");
            mshSegment.getSendingFacility().getNamespaceID().setValue("Our Facility");
            mshSegment.getReceivingApplication().getNamespaceID().setValue("Their Remote System");
            mshSegment.getReceivingFacility().getNamespaceID().setValue("Their Remote Facility");
            mshSegment.getDateTimeOfMessage().getTimeOfAnEvent().setValue(currentDateTimeString);
            mshSegment.getMessageControlID().setValue(getSequenceNumber());
            mshSegment.getVersionID().getVersionID().setValue("2.4");
        }

        private void createEvnSegment(String currentDateTimeString) throws DataTypeException {
            EVN evn = _adtMessage.getEVN();
            evn.getEventTypeCode().setValue("A28");
            evn.getRecordedDateTime().getTimeOfAnEvent().setValue(currentDateTimeString);
        }
}

Using this I can

Message adtMessage = new AdtA28Director.Builder(patient).build();

Some message ojject types will require (or similar):

Message adtMessage = new AdtA01Director.Builder(patient).visit(visit).build();

I am not really sure that I am using the builder pattern correctly. Is this a reasonable approach - can it be improved? I am planning to move the creation of the MSH and ENV segments to a separate class(s). There are perhaps 20 different message types and maybe a similar number of segments that I have to manage so I am trying to build a very clear and understandable (scaleable) pattern.

Any guidance / corrections etc appreciated.

Choosing right design pattern

I have been contemplating for quite a while what would be the best design pattern to refactor given code to, but every time I think I have it, something just does not feel right.

public CalculatedCommission calculatedCommission(BigDecimal amount, int clientId, Date date) {
    // CALCULATE COMMISSIONS
    // Rule #1: Default pricing
    BigDecimal rule1Commission = amount.multiply(BigDecimal.valueOf(0.005));
    if (rule1Commission.compareTo(BigDecimal.valueOf(0.05)) == -1)
        rule1Commission = BigDecimal.valueOf(0.05);

    // Rule #2: Client with a discount
    BigDecimal rule2Commission = BigDecimal.ZERO;
    boolean isClientId42 = clientId == 42;
    if (isClientId42)
        rule2Commission = BigDecimal.valueOf(0.05);

    // Rule #3: High turnover discount
    BigDecimal rule3Commission = BigDecimal.ZERO;
    boolean monthlyTurnoverOf1000EUROHasBeenReached = isMonthlyTurnoverOf1000EUROHasBeenReached(amount, date);
    if (monthlyTurnoverOf1000EUROHasBeenReached)
        rule3Commission = BigDecimal.valueOf(0.03);

    // APPLY COMMISSIONS RULES
    CalculatedCommission calculatedCommission;
    if (isClientId42) {
        if (monthlyTurnoverOf1000EUROHasBeenReached) {
            if (rule1Commission.compareTo(rule3Commission) == -1) {
                calculatedCommission = new CalculatedCommission(rule1Commission, RULE1);
            } else {
                calculatedCommission = new CalculatedCommission(rule3Commission, RULE3);
            }
        } else {
            calculatedCommission = new CalculatedCommission(rule2Commission, RULE2);
        }
    } else if (monthlyTurnoverOf1000EUROHasBeenReached) {
        calculatedCommission = new CalculatedCommission(rule3Commission, RULE3);
    } else {
        calculatedCommission = new CalculatedCommission(rule1Commission, RULE1);
    }

    return calculatedCommission;
}

I thought at the beginning given pretty obvious business rules applied for given commissions it could be simply expressed as Strategy pattern where each Rule would be represented by specific Strategy. Although I am quite unsure how could I possibly decide which strategy to choose based on condition as there seems to be one branch where specific commission values are used condition of applying one strategy over another.

I would be grateful for small hint in what direction I could possibly look to get different perspective.

Should an entity or service be responsible for making API calls?

Let's assume that we are creating a program that interacts with some API. I see two approaches here, but I can't figure out which one is better.

1st approach: entities are making requests to API

type User struct {
    SomeUserId int
    SomeUserToken string
}

func (user *User) UpdateNickname(newNickname string) {
    call_api(...)
}

User{Id: 1, token: "abc"}.UpdateNickname("a")
User{Id: 2, token: "edf"}.UpdateNickname("b")

2nd approach: we have a service that makes these requests

type UserService struct {
    ...
}

func (service *UserService) UpdateNickname(user User, newNickname string) {
    call_api(...)
}

service.UpdateNickname(user1, "a")
service.UpdateNickname(user2, "b")

I guess that the second one is better, assuming that the "entity" is only for keeping some references to the entity that it actually holds, but I do not know how it actually should be. Hope to get an explanation for this.

Can some one explain me the this regex pattern in python? re.findall("[a-zA-Z*,*\-!*.]"

re.findall("[a-zA-Z*,*\-!*.]"

This regular expression checks for valid letters, ".", "-", "-", "!" in a word. I understood the first part

[a-zA-Z]

Can someone please explain this?

[*,*\-!*.]

Error in CreateInstance() while dynamically creating object of concrete type in Factory Pattern

I am actually new to design patterns and trying to implement factory pattern with .net core.

I tried to see couple of posts related to factory pattern and trying to implement it, I have added the concrete types in the config and reading it as dictionary in my code -

My Factory Interface -

public interface IEmpFactory
{
    public BaseEmployee CreateEmployeeType<EmpType>() where EmpType : BaseEmployee, new();
}

Implementation -

public class EmpFactoryImpl : IEmpFactory
{
    public BaseEmployee CreateEmployeeType<EmpType>() where EmpType: BaseEmployee, new()
    {
        return new EmpType();
    }
}

Below are my services which are using the Factory as dependency -

public interface IEmpService
{
    public string GetEmployeeBonus();
}

public class ContractEmpService : IEmpService
{
    IEmpFactory _empFactory;

    public ContractEmpService(IEmpFactory empFactory)
    {
        _empFactory = empFactory;
    }
    private BaseEmployee CreateMyEmployee()
    {
        return _empFactory.CreateEmployeeType<ContractEmp>();
    }

    public string GetEmployeeBonus()
    {
        return CreateMyEmployee().GetBonus();
    }
}

public class PermEmpService : IEmpService
{
    private readonly IEmpFactory _empFactory;

    public PermEmpService(IEmpFactory empFactory)
    {
        _empFactory = empFactory;
    }

    private BaseEmployee CreateMyEmployee()
    {
        return _empFactory.CreateEmployeeType<PermEmp>();
    }

    public string GetEmployeeBonus()
    {
        return CreateMyEmployee().GetBonus();
    }
}

Added these concrete types in the config -

enter image description here

Created the class to create a instance of the concrete type based on the type i.e, PermEmp or ContractEmp dynamically -

public class EmployeeTypeRouter : IEmployeeTypeRouter
{
    private readonly ConfigurationProps _props;

    public EmployeeTypeRouter(ConfigurationProps props)
    {
        _props = props;
    }

    public IEmpService GetInstance(string key)
    {
        string className = _props.EmpServices.Where(k => k.Key.Equals(key)).FirstOrDefault().Value;

        Type t = Type.GetType(className);

        return (IEmpService)Activator.CreateInstance(t);
    }
}

This is my calling method -

    [HttpGet(Name = "GetEmployeeBonus")]
    public string Get()
    {
        string type = "PermEmp";
        IEmpService empService = _empRouter.GetInstance(type);

        return empService.GetEmployeeBonus();
    }

based on the type passed here i want to fetch the concrete type and call the method.

I am getting the error like this on CreateInstance method -

enter image description here

Which is very clear, but i dont want to create a parameterless constructor.

Since i am registering the dependencies in .net core, do i need to pass it again here ? (which does not make sense for me)

Any help is really appreciated or if you feel i am doing something wrong please let me know.

vendredi 12 août 2022

What is logging? [closed]

Can someone pls tell me what is logging in python ? I know about the levels (info, debug ,warning, error, critical) in general but I'am not 100% sure that know what this is and I don't know what I can do with (except that I saw / told that I will use this everywhere in order to code big projects efficient), I still a beginner and I saw that in order to be a good programmer I need to know design patterns perfect and one of the subjects of it is logging

Use the Factory Pattern in Nest Js

I need to create a instance based on a query.

I have an interface like this:

import { GatewaySendMessageDto } from "./dto/gateway-send-message.dto";
import { IGateway } from "./interfaces/IGateway";

export interface GatewayInterface {

    sendMessage(channel: IGateway, data: GatewaySendMessageDto):void

}

and it's the basic method that my classes needs to implement

I create the Factory Class like this

export class GatewayFactory {

    public GatewayFactory(){}

    public getGateway (type) {
        
        let a = GatewayTypesEnum.Telegram;
        let gateway:GatewayInterface = null;
        switch (type){
            case 'Telegram':
                gateway = new TelegramService(??);
                break;
            case GatewayTypesEnum.Discord:
                //gateway = new foo();
                break;
        }
        return gateway;
    }

}

I need to create an instance of telegramService when the type is 'Telegram', but it has a dependecy like:

constructor(
        @InjectModel(Gateway.name) private readonly gatewayModel: Model<Gateway>,
        private bot: Telegraf,        
        private imagesService: ImagesService,

    ) 

obviously, telegramService implements GatewayInterface

so in my GatewayService I could do:

async sendMessageToGatway(){
        let gateway = new GatewayFactory()
        return gateway.getGateway('Telegram').sendMessage();
    }

How can I implement the Factory Pattern method when the service has the dependencies? Thanks

Design pattern for complex hierarchy

I'm trying to implement an application to solve a given task, made up of small sub-tasks. Individual workers are in charge of handling a portion of each sub-task. Then a coordinator regroups all the plans made by each worker and builds a global solution to the full task.

There may only be one worker assigned to each sub-task, but he does not have to complete it in its entirety; he can give a plan for only part of the sub-task, and then let the coordinator complete it as he is building the global solution (typically this gives the coordinator more flexibility as he can make plans from different workers fit better with each other but increases his workload). Furthermore, as they are created, plans are first sent to the coordinator, who can either directly reject it or ask the worker to store it for future use.

At any given time, a worker can send an alert to the coordinator if he thinks there is an issue with the plans he is producing. The coordinator will look at it in the future, and can then ask said worker to delete some of the plans he has already created and change the parameters he uses to crate future plans.

Finally, for a worker in charge of a certain portion of a certain sub-task, multiple methods are available to him. All methods generate the same plans, but one may be more efficient than another in a given context. The chosen method may not change during solving.

For the moment, the classes I have created look something like this:

class Subtask {
    // Concrete classes will contain various data relative to the sub-task
};

class Worker {
    const Subtask& subtask;
    // Concrete classes will have various objects relative to the portion this worker should solve
    Method method;

    vector<Plan> createdPlans;

    virtual Plan createPlan() {method.createPlan;}
    virtual void storePlan(Plan plan) {createdPlans.push_back(plan);}

    virtual Alert createAlert() = 0;
    virtual void applyAlert(Alert alert) {
        // remove plans from createdPlans according to the alert
        method.applyAlert(alert);
    }
}

class Method {
    const Subtask& subtask;

    virtual Plan createPlan() = 0;
    virtual void applyAlert(Alert alert) = 0;
};

class Plan {
    // Concrete classes contain various data relative to the plan
};

class Alert {
    const Worker& worker;

    virtual void trigger() {worker.applyAlert(this)}
};

Worker and Method hold references to their Subtask as they may regularly need data from it. Alert holds a reference to the Worker that created it to know who to apply to if the coordinator decides to trigger it.

For a given portion of a given sub-task, I need to implement specific Worker, Plan and Alert, and various Methods relative to that Worker.

I'm mainly facing two issues:

  1. In concrete implementations of Worker, createdPlans will only contain elements of the associated sub-class of Plan. For instance, in applyAlert, I need to cast them to access their specific data and verify if they should be removed by the alert or not. However, the coordinator also needs to iterate and do generic actions over them, so createdPlans needs to exist in Base class Worker.

  2. In implementations of Worker and Method, in applyAlert, I need to cast the alert to the sub-class corresponding to that type of Worker as I need specific information from it. Visitor pattern would not be adapted here, as only one type of Alert can actually be applied to a concrete Worker/Method.

C# State-Pattern private ChangeState

I´m trying to implement the State-Pattern using C# following this page. Here the UML of a State-Pattern.

enter image description here

The State it self sets the new sate in the context class. But here is my problem: I want to use Interfaces but the ChangeState-Method should not be present to the client but available for the state. But I don´t know how to implement a private interface within a class which I present for the client.

Here my first shot of the pattern Context-Class which should implement the IChangeState interface:

public interface IContext 
{
    string Input { get; set; }
    void DoTransition();
}

public class Context : IContext
{ 
    public string Input { get; set; }

    private AbstractState _state;

    public void DoTransition() 
    {
        _state.DoTransition();
    }
}

And the IChangeState interface which does the main trick but should not be visibile to the client. So I assumed to make it private but how to share this interface with the state or even implement it?

public interface IChangeState 
{
    void ChangeState(IState state);
}

And at least the States:

public interface IState 
{
    void DoTransition();
}

public abstract class AbstractState : IState 
{
    private IChangeState _stateChanger;

    public AbstractState(IChangeState stateChanger) => _stateChanger = stateChanger;

    public virtual void DoTransition() 
    {
        _stateChanger.ChangeState(new NextState(_stateChanger));
    }
}

public class NextState : AbstractState 
{
    public NextState(IChangeState stateChanger) 
        : base(stateChanger)
    { }

    public override void DoTransition()
    {
        base.DoTransition();
    }
}

How do I best capture possible side-effects of Func<..> in C#? Is there a best practice for this?

I have code from a maths library i am using, and cannot change. The function in question from the maths library I am using uses an approximation function iteratively, like this.

public double Calculate(double startInput, Func<double, double> approximationFunc)
{
    var result = 0d;
    var max = 10;
    for (int i = 0; i < max; i++)
    {
        result = approximationFunc(startInput);
        //do some checks ...
        startInput =DoSomething();
    }
    return result;
}

However, in the approximationFunc I am using 'in reality', I have to compute other things than the double result, and I need to re-use these results. The only thing I have come up with is:

 public void BusinessLogic(double startInput)
        {
            MyOtherResult myOtherResult = null;
            double myFunction(double input)
            {
                var result = ComputeMyResult(input);
                myOtherResult = ComputeMyOtherResult(result, someOtherStuff);
                return result;
            }

            var approximationResult = Calculate(startInput, myFunction);
            var myOtherApproximationResult = myOtherResult;
            // Do other stuff...
        }

However, I'm not sure if this the best way of getting the 'other result', and if there is a side-effects-free way of doing this. The solution I have come up with only works because I know that the library I use applies this function iteratively, and that's not ideal. How would you go about solving this in C#? I've been racking my brain for two days and it's not clicking.

jeudi 11 août 2022

mercredi 10 août 2022

Elegant solution to initalize a struct with many fields

In my program, I am trying to find an elegant solution to initalize a user struct. The problem I am facing is I have many, many fields which make initalizing the user bulky and messy. There is one thing to note which may be helpful:

  1. When a user is first registered to the app, some fields I want to have default values such as a bio, school, ocupation, etc. (because they have not yet had the chance to populate the data)

I have already tried to wrap other structs around the fields to make the class less messy, but still seems to be a terrible work around.

public struct User {
    
    //MARK: - Fields

    var email: String
    var userSettings: UserSettings
    var userProfile: UserProfile
    var uid: String
    
    
    init?(with userNode: [String: Any]) {
        
        guard let userProfile = UserProfile(userNode: userNode),
              let userSettings = UserSettings(userNode: userNode),
              let email = userNode[EMAIL] as? String,
              let uid = userNode[UID] as? String else { return nil }
        
        self.userProfile = userProfile
        self.userSettings = userSettings
        self.email = email
        self.uid = uid

    }
    
    /**
        Initalize a new user with credentials. Will initalize user with default settings and profile
     */
    init?(with credentials: AuthCredentials,
          profileDownloadUrl: [String],
          uid: String) {
        
        guard let birthday = credentials.birthday,
              let firstName = credentials.firstName,
              let lastName = credentials.lastName,
              let gender = credentials.gender,
              let preference = credentials.preference,
              let geoHash = credentials.location?.geoHash,
              let latitude = credentials.location?.latitude,
              let longitude = credentials.location?.longitude,
              let email = credentials.email else {
            return nil
        }
        
        //Create default profile
        self.userProfile = UserProfile(birthday: birthday,
                                         profilePictures: profileDownloadUrl,
                                         firstName: firstName,
                                         lastName: lastName)
        //Create default settings
        self.userSettings = UserSettings(minSeekingAge: MAX_AGE,
                                         maxSeekingAge: MIN_AGE,
                                         distanceRange: MAX_DISTANCE_RANGE,
                                         gender: gender,
                                         preference: preference,
                                         geoHash: geoHash,
                                         latitude: latitude,
                                         longitude: longitude)
        
        //Assign email
        self.email = email
        
        //Assign user id
        self.uid = uid

    }

}

What is the recomended design pattern to use? I've looked into the builder design pattern, but personally I am not a fan, as I will still have to manually set as many fields.

I have an interface (domain port) with several implementations (non-domain adapters). Where does the logic for choosing which adapter to use go?

Let's say I have a use case that needs to make calls to a client, defined as an interface, a port.

I want to use one implementation (adapter) or another, for that port; and the choice of which one to use depends on business logic - say, the country of the user, or a more complex calculation.

In terms of design patterns, that sort of smells like a factory to me; I could just have a function typed to return the interface and whose logic returns different implementations based on certain conditions.

However, I'm having trouble integrating this with my knowledge of architecture, and with what is and isn't domain:

  • If I create a domain function that chooses between one adapter or another, I need to have the adapters (non domain code) imported into my domain, so I can return the proper one. That's wrong, because I'm letting implementations be part of business logic.

  • On the other hand I could have an "adapter of adapters": I "leak" through the port the data needed to choose an adapter as part of the contract, and I have one single "wrapper adapter", that I always use for that port, which redirects the call to one of any possible third adapters. This is also wrong, since I have business logic (how to choose one adapter or another) outside the domain, and adapters calling other adapters (?).

How can I solve this problem? Is there a third option I'm not seeing?

Data object and editor object design pattern

Not sure how to ask this question but I'm looking for a clean way to solve a problem for a project. I'm trying create a class library that will allow someone to create a randomized character for a game and use the data for a web app. I have a CharacterModel class that has all the needed data publicly exposed, however I need a way to edit this information without making the setters publicly available. Also, if I have multiple characters in the future, how do I get the editor to effect specific objects? Is there a design pattern for this type of problem?

mardi 9 août 2022

Share the same object between two windows with out refresh all instance of the same object in the forms, MVVM pattern

I have a problem with the pattern MVVM in C# windows forms, I have a form called A that have an object binding, at this point all is ok, that form in another windows is opened like showdialog but when this happen the values ​​of form A are updated to the same values ​​of the form that was opened as showdialog, there is a way to show the info in the showdialog with out updated the values of the form A? I know that this is normal behavior of the MVVM design pattern, but is it possible to cancel the update of form A?

parse from a huge txt file and write each output in separate files

How can I extract a multiline string from a huge txt file and to write each found pattern in a separate file?

An example extract from source file (example.txt):

RIG 1C 0
RIC 1 F
RIB F F
RIB A F
RIB O O
RIC 2 C
RIB J J
RIB C J
RIB D C
RIB Z D
RIB R Z
RIB I I
RIB S S
RIC 3 Y
RIB Y Y
RIB M Y
RIB L M
RIB H L
RIB K H
RIB B K
RIB W B
RIB Q W
RIB V Q
RIB N V
RIB G B
RIB T B
RIB X X
RIG 1C 1
RIC 1 F
RIB F F
RIB A F
RIB O O
RIC 2 C
RIB J J
RIB C J
RIB D C
RIB Z D
RIB R Z
RIB I I
RIB S S
RIC 3 Y
RIB Y Y
RIB M Y
RIB L M
RIB H L
RIB K H
RIB B K
RIB W B
RIB Q W
RIB V Q
RIB N V
RIB G B
RIB T B
RIB X X
RIG DE 0
RIC 1 F
RIB F F
RIC 2 C
RIB C C

Pattern is from RIG to RIG

this means first file RIG1C0.txt contains:

RIG 1C 0
RIC 1 F
RIB F F
RIB A F
RIB O O
RIC 2 C
RIB J J
RIB C J
RIB D C
RIB Z D
RIB R Z
RIB I I
RIB S S
RIC 3 Y
RIB Y Y
RIB M Y
RIB L M
RIB H L
RIB K H
RIB B K
RIB W B
RIB Q W
RIB V Q
RIB N V
RIB G B
RIB T B
RIB X X

second file RIG1C1.txt :

RIG 1C 1
RIC 1 F
RIB F F
RIB A F
RIB O O
RIC 2 C
RIB J J
RIB C J
RIB D C
RIB Z D
RIB R Z
RIB I I
RIB S S
RIC 3 Y
RIB Y Y
RIB M Y
RIB L M
RIB H L
RIB K H
RIB B K
RIB W B
RIB Q W
RIB V Q
RIB N V
RIB G B
RIB T B
RIB X X

and so on.

I heard something about RegEx

Is someone able to help me?

How to properly design a solution, using patterns, that branches Trial and Pro version of an api?

I'm implementing some features that translate text and based on that my hobby app supports multiple types of translation (Bing, Google etc.). For that purpose, I created an abstract class

class Translate(ABC):
   @abstractmethod
   def translate(text, goal_lang):
      pass

Then I have

class GoogleTranslator(Translate):
    @staticmethod
    def translate(text, goal_lang):
        *translate logic*

class BingTranslator(Translate):
    @staticmethod
    def translate(text, goal_lang):
        *translate logic*

class YonigTranslator(Translate):
    @staticmethod
    def translate(text, goal_lang):
        *translate logic*

I made a Facade for these classes in the following way:

class Google(GoogleTranslator):
    def __init__(self):
        pass

    def translate(self, text, goal_lang):
        return super().translate(text, goal_language)

class Bing(BingTranslator):
    def __init__(self):
        pass

    def translate(self, text, goal_lang):
        return super().translate(text, goal_language)

class Yoing(YonigTranslator):
    def __init__(self):
        pass

    def translate(self, text, goal_lang):
        return super().translate(text, goal_language)

Why did I do it this way? Because I want to store another Google, Bing or Yonig features in one container and have Google features (for ex. meets, drive) stored in Google. However, the translator that I used is a free one and now I want to implement a pro (paid) version but still keep the old (free) one. When I decided to do it this way, I knew that it could get messy and that's why I came here to get some help and find the right approach. What I was thinking in doing is rename the GoogleTranslator to GoogleFreeTranslator and make another class that will be called GooglePaidTranslator(Translate). However, if I inherit both of these classes into Google and I call .translate(), I believe that the app will crash because both of the members that Google inherits from would have the same method! What I speak, translated to code would look like:

class GoogleFreeTranslator(Translate):
    @staticmethod
    def translate(text, goal_lang):
        *translate logic*

class GooglePaidTranslator(Translate):
    @staticmethod
    def translate(text, goal_lang):
        *translate logic*

class Google(GoogleFreeTranslator, GooglePaidTranslator):
    def __init__(self):
        pass

    def translate(self, text, goal_lang):
        return super().translate(text, goal_language)

This is where I'm stuck and I'm looking for help and further paths on how could I approach this. Should I maybe change the whole approach or is there a way to initialize Google and somehow tell the class to use the translate() method from one of the classes that it inherits from?

Business logic in Database [closed]

I see more and more projects proposing to put the business logic in the database (like postgrest, pgrest etc..). In theory, I understand the advantages of this approach but in practice I am not sure of the real gains.

Nowadays on of the most expensive resource (cloud provided by AWS, GCP etc..) is the database service. Adding the management of roles (RLS), functions (signup, signin etc...), views, is accept to move part of the load to a single point which is not the least expensive and critical.

Am I wrong to think that?

Should I use Builder Pattern Or a Regular Constructor For Service Classes?

When doing dependency injection without a framework (i.e. for a library), is it better practice to create a required args constructor for service classes or a builder for service classes? Is one more testable than the other?

@RequiredArgsConstructor
class MyServiceClass {
      private final Dependency1;
      private final Dependency2;
      private final Dependency3;
}

Vs.

@Builder
class MyServiceClass {

    @Nonnull
    private final Dependency1;

    @Nonnull
    private final Dependency2;

    @Nonnull
    private final Dependency3;

}

How to use command pattern in react calculator app

I have a calculator app and I'm trying to apply the command pattern

I have a fully working version

Please help me figure out how I should do

How do I use the command pattern in my code?

Calculator.jsx

export const Calculator = () => {
  const [history, setHistory] = useState([])
  const [formula, setFormula] = useState([])
  const [input, setInput] = useState('')
  const [result, setResult] = useState('')

  const handleDigit = number => {
    setInput(input + number)
    setFormula(formula => [...formula, input])
  }

  const handleClear = () => {
    setInput('')
    setFormula([])
    setResult('')
  }

  const handleDelete = () => {
    setInput(input.slice(0, -1))
  }

  const handleToggleSign = () => {
    setInput(input.charAt(0) === '-' ? input.slice(1) : '-' + input)
  }

  const handleOperator = operator => {
    setInput(input + operator)
  }

  const handleDecimalPoint = () => {
    if (!input.includes('.')) {
      setInput(input + '.')
    }
  }

  const handleEqual = () => {
    setResult(eval(input))
    setHistory(history => [...history, { input, result }])
    setInput('')
  }

  return (
    <Fragment>
      <MainContainer>
        <LeftSide>
  
          <Display
            result={result}
            input={input}
            formula={formula}/>
          <Keypad
            onDigit={handleDigit}
            onClear={handleClear}
            onDelete={handleDelete}
            onToggleSign={handleToggleSign}
            onOperator={handleOperator}
            onDecimalPoint={handleDecimalPoint}
            onEqual={handleEqual}
          />
        </LeftSide>
      </MainContainer>
    </Fragment>
  )
}

Keypad.jsx

export const Keypad = props => {
  const handleOnDigit = e => {
    props.onDigit(e.target.value)
  }

  const handleOnOperator = e => {
    props.onOperator(e.target.value)
  }

  return (
    <KeypadContainer>
      <KeypadRow>
        <FunctionsButton value="clearAll"onClick={props.onClear}>AC</FunctionsButton>
        <FunctionsButton value="clear"onClick={props.onDelete}>C</FunctionsButton>
        <FunctionsButton value="sign" onClick={props.onToggleSign}>+/-</FunctionsButton>
        <FunctionsButton value="/" onClick={handleOnOperator}>÷</FunctionsButton>
      </KeypadRow>
      <KeypadRow>
        <KeypadButton value={7} onClick={handleOnDigit}>7</KeypadButton>
        <KeypadButton value={8} onClick={handleOnDigit}>8</KeypadButton>
        <KeypadButton value={9} onClick={handleOnDigit}>9</KeypadButton>
        <FunctionsButton value="*" onClick={handleOnOperator}>x</FunctionsButton>
      </KeypadRow>
      <KeypadRow>
        <KeypadButton value={4} onClick={handleOnDigit}>4</KeypadButton>
        <KeypadButton value={5} onClick={handleOnDigit}>5</KeypadButton>
        <KeypadButton value={6} onClick={handleOnDigit}>6</KeypadButton>
        <FunctionsButton value="-" onClick={handleOnOperator}>-</FunctionsButton>
      </KeypadRow>
      <KeypadRow>
        <KeypadButton value={1} onClick={handleOnDigit}>1</KeypadButton>
        <KeypadButton value={2} onClick={handleOnDigit}>2</KeypadButton>
        <KeypadButton value={3} onClick={handleOnDigit}>3</KeypadButton>
        <FunctionsButton value="+" onClick={handleOnOperator}>+</FunctionsButton>
      </KeypadRow>
      <KeypadLastRow>
        <KeypadButton value={0} onClick={handleOnDigit}>0</KeypadButton>
        <KeypadButton value="." onClick={props.onDecimalPoint}>.</KeypadButton>
        <KeapadButtonEqual  value="="     onClick={props.onEqual}>=</KeapadButtonEqual>
      </KeypadLastRow>
    </KeypadContainer>
  )
}

I have read and studied the pattern, but how should I apply it to my application, I cannot yet understand and deal with it