lundi 31 janvier 2022

Is there a way I can refactor the code to remove repeated code

I have two classes, both of which implement an interface, but use a different client in their implementations like below:

public interface DDLExecutor {
  public void createDatabase(String databaseName);
}

public class HMSDDLExecutor implements DDLExecutor {
  private final IMetaStoreClient client;

  public HMSDDLExecutor(String tableName) {
    this.client = Hive.get().getMSC();
  }
 
  @Override
  public void createDatabase(String databaseName) {
    try {
      Database database = new Database(databaseName, "automatically created", null, null);
      client.createDatabase(database);
    } catch (Exception e) {
      LOG.error("Failed to create database " + databaseName, e);
      throw new HoodieHiveSyncException("Failed to create database " + databaseName, e);
    }
  }
}

public class ThriftDDLExecutor implements DDLExecutor {
  private final HMSClient client;

  public HMSDDLExecutor(String cfg) {
    this.client = new HMSClient(new URI(cfg.thriftUrl));
  }

  @Override
  public void createDatabase(String databaseName) {
    try {
      Database database = new Database(databaseName, "automatically created", null, null);
      client.createDatabase(database);
    } catch (Exception e) {
      LOG.error("Failed to create database " + databaseName, e);
      throw new HoodieHiveSyncException("Failed to create database " + databaseName, e);
    }
  }
}


How can I refactor it so that DRY principle is followed. Should I try creating a base class?

Passing shared_ptr in mediator design from one colleague object to other running in different threads

In a mediator design pattern with C++, I need to efficiently pass data from one object (running in one thread) to other object running in another thread using bind() call. Assuming I have a mechanism to enqueue function objects into a thread's execution queue (say Thread->Enqueue( functor ))

//Foo's call -- runs in Thread1's context
void Foo::DoSomeWork()
{
    shared_ptr<Object> o = std::make_shared<Object>()
    //fill the object

    //post to mediator
    M.PostData(o);
}

//Thread1 runs functions for class foo. this is called in Thread1's context
void Mediator::PostData(shared_ptr<Object> data)
{
    //Enqueue the functor into Thread2 execution queue 
    Thread2->Enqueue(std::bind(&Bar::ProcessData, Colleague2.get(), data));
}

//Thread2 context
void Bar::ProcessData(shared_ptr<Object> ReceivedData)
{
    //work on ReceivedData object. runs in Thread2's context
    //data passed on to Bar class
} 

instead of copying the shared ptr in the std::bind, is it possible to do std::move(data) to pass on the shared_ptr

e.g. 
Thread2->Enqueue(std::bind(&Bar::ProcessData, Colleague2.get(), std::move(data)));

Not sure if using unique_ptr<> and try moving twice (one in function, other in std::bind will work or help

How to avoid prop drilling in Atomic design?

I recently got a new project. The project used Atomic design but the developer that worked on the project begore didn't follow the rule exactly. Molecules and organisms have a logic with API(axios). In the design, They have to do their features with props, right?

So I decided to seperate the logics that they're using. While working it, I got a curiosity. Components that made with the Atomic design are really clean. I know that but how about a prop drilling?

Pages pass props to organisms.
Organisms pass props to molecules and atoms.
Molecules pass propd to atoms.

Context API came out for solving this problem, but this isn't along with Atomic design.

Do I misunderdtand a concept of the design?

How do you guys avoid a prop drilling in Atomic design? Do I have to work with it?

React pattern stopping duplicate objects being added to state

This is the current value of the state (myState):

[{“id”: 123, “title”: “book 1”}]

When a user tries to add a new book, I want to check if the Id matches any of the ids which are already in the state variable. I tried doing this:

if (!myState.map(a => a.id).includes(newBook.id)) setMyState([newBook, ...myState]);

This works fine but I don’t think it is the correct approach because the state update is asynchronous so the user might be able to add the same book twice if the state is not updated fast enough. What is the best pattern for these situations?

dimanche 30 janvier 2022

The State Pattern for a Multiroom Game

I'm learning the state pattern. I have trouble to implement the following pattern with python and state_machine library.

enter image description here

My code so far:

from state_machine import (
    State,
    Event,
    acts_as_state_machine,
    after,
    before,
    InvalidStateTransition
)


@acts_as_state_machine
class Room:
    """The State pattern implemented for multiroom
    computer game in docs/state-diagrams.pdf
    """

    entry = State(initial=True)
    hall = State()
    dining_room = State()
    study = State()
    cellar = State()
    barn = State()
    ferry = State()

States seems easy to identify. Then come to transitions. I have trouble because each transition is from different state to another different state.

I tried to do the following:

east_to_hall = Event(from_states=entry,
                     to_state=hall)
south_to_hall = Event(from_states=dining_room,
                      to_state=hall)
west_to_hall = Event(from_states=study,
                     to_state=hall)
west_to_dining_room = Event(from_states=hall,
                            to_state=dining_room)
north_to_dining_room = Event(from_states=hall,
                             to_state=dining_room)
down_to_cellar = Event(from_states=(hall, study),
                       to_state=cellar)

But then it's messed up the transition. I'm asking for ideas on what's the transitions looks like in this state diagram.

Design patterns & Clean architecture in flutter

When I start programming a new application in flutter everything goes well at the beginning but when the project grows up it starts to become messy, and then I decide to delete the project to start over. I searched about the clean architecture and design patterns but I found a lot of choices such as DDD, BLoC, and so many patterns and architectures, I didn't what is the best thing to stick with every time I enter a research process that lasts forever. So I want to hear from you as professionals and expert coders what is the best thing to stick with and what should I do? please give some advice on how to deal with big projects in flutter? Thank you very much

samedi 29 janvier 2022

Is it ok to have the client and the invoker modifying the concrete ICommand, in the command pattern design?

I am trying out this flavor of the command pattern, for practice purposes, where the concrete implementation of the ICommand needs two pieces of data in order to properly execute. As of right now, the Client provides the initial data point via the command constructor, but it has no idea how to provide the second datapoint, which can only be set via a separate method SetPreparar(IStaff preparer). I have delegated that responsibility to the Invoker class.

I have seen various flavors of the command pattern, but I have not seen one in which both the client and the invoker are setting state.
I really like how clean it looks and feels, but the fact that 2 classes are changing state bothers me a little.

Hence the question in the title.

Below is a Console App written in .NET 6. Can I get a code review, I guess?

var cook = new Cook();
var bartender = new Bartender();
var bobWaiter = new Waiter(cook, bartender);
var customer = new Customer(bobWaiter);

customer.OrderFood("Pepperoni Pizza");
customer.OrderDrink("Iced tea");
customer.ThankYouThatsAll();

Console.ReadLine();


class Customer
{

    IWaiterInvoker _waiter;

    public Customer(IWaiterInvoker waiter)
    {
        _waiter = waiter;
    }

    public void OrderFood(string dishName)
    {
        var foodOrderCommand = new OrderFoodCommand(dishName);
        _waiter.TakeFoodOrder(foodOrderCommand);
    }

    public void OrderDrink(string bevName)
    {
        var beverageCommand = new OrderBeverageCommand(bevName);
        _waiter.TakeDrinkOrder(beverageCommand);
    }

    public void ThankYouThatsAll()
    {
        _waiter.ExecuteCommands();
    }

}

class Waiter : IWaiterInvoker
{
    IStaff _cook;
    IStaff _bartender;

    public List<IOrderCommand> allCommands { get; private set; }

    public Waiter(IStaff cook, IStaff preparer)
    {
        _cook = cook;
        _bartender = preparer;
        allCommands = new List<IOrderCommand>();
    }

    public void TakeFoodOrder(IOrderCommand command)
    {
        command.SetPreparer(_cook);
        allCommands.Add(command);

    }

    public void TakeDrinkOrder(IOrderCommand command)
    {
        command.SetPreparer(_bartender);
        allCommands.Add(command);
    }

    public void ExecuteCommands()
    {
        foreach (var cmd in allCommands)
        {
            cmd.Execute();
        }
    }
}


class Cook : IStaff
{
    public void Prepare(string item)
    {
        Console.WriteLine($"You dish {item} is ready");
    }
}


class Bartender : IStaff
{
    public void Prepare(string item)
    {
        Console.WriteLine($"Your drink {item} is ready");
    }

}

public interface IStaff
{
    void Prepare(string item);
}

public interface IOrderCommand
{
    void SetPreparer(IStaff preparer);
    void Execute();
}

public interface IWaiterInvoker
{
    List<IOrderCommand> allCommands { get; }
    void TakeFoodOrder(IOrderCommand command);
    void TakeDrinkOrder(IOrderCommand command);
    void ExecuteCommands();
}

public class OrderBeverageCommand : IOrderCommand
{
    string _beverage;
    IStaff _preparer;

    public OrderBeverageCommand(string beverage)
    {
        _beverage = beverage;
    }


    public void Execute()
    {
        _preparer.Prepare(_beverage);
    }

    public void SetPreparer(IStaff preparer)
    {
        _preparer = preparer;
    }
}


public class OrderFoodCommand : IOrderCommand
{
    string _dishName;
    IStaff _preparer;

    public OrderFoodCommand(string dishName)
    {
        _dishName = dishName;
    }

    public void Execute()
    {
        _preparer.Prepare(_dishName);
    }

    public void SetPreparer(IStaff preparer)
    {
        _preparer = preparer;
    }
}

How to customize Jena ARQ query engine to add additional triple pattern

Given the following triples describe Forklift1 location at the different times:

:forklift1 
   :location :station1, :dockdoor1;
   :9305fc5f-d43d :station1;
   :a4e9-2bcd5b97 :dockdoor1;
  .
:9305fc5f-d43d a :location;
   :createdDate "2022-01-02T10:00:00.000-05:00"^^xsd:dateTime; 
   :expiryDate "2022-01-03T14:00:00.000-05:00"^^xsd:dateTime; 
  .
:a4e9-2bcd5b97 a :location;
   :createdDate "2022-01-03T14:00:00.000-05:00"^^xsd:dateTime; 
  .

To retrieve Forklift1's current location, a SPARQL query is:

select ?o where { 
    :forklift1 :location ?o 
    optional{:forklift1 ?px ?o. ?px a :location. optional{?px :createdDate ?createdDate} optional {?px :expiryDate ?expiryDate}}
    filter (!bound(?expiryDate)) 
  }

result :dockdoor1

My goal is to make Query Engine return the same result but with a much simpler query:

select ?s where { 
    :forklift1 :location ?o.
}

result :dockdoor1

I am using Jena TBD + ARQ; I read some documents, it can be done by customizing ARQ Query Engine; for each Triple pattern :forklift1 :location ?o, to programmatically add the new property instance pattern optional{:forklift1 ?px ?o. ?px a :location. optional{?px :createdDate ?createdDate} optional {?px :expiryDate ?expiryDate}} filter (!bound(?expiryDate)).

Does anyone know how to do this? Your help will move my work forward!

Runtime factory design patterns

Let's assume I have the following classes:

class Listner
{
    ...
    int first_call = true;
    DataReader * reader;
    ***
    int dataIsAvailable(char * data, int len) {
        if (first_call) {
            if (data[0] == 'R') {
                reader = new RawReader();
            } else if (data[0] == 'E') {
                reader = new SecureReader();
            }
            first_call = false;
        }
        
        reader->read(data, len);
        printf("%s", data);
        
    }
}

class DataReader
{
    long read(...) = 0;
}

class RawReader : public DataReader
{
    long read(char * data, int len) {
        return ::recv(char * data, int len);
    }
}

class SecureReader : public DataReader
{
    long read(char * data, int len) {
        auto ret = ::recv(char * data, int len);
        decrypt(data, len)
        return ret;
    }
}

dataIsAvailable is called when there is new data available.

In this case, I know if the content is encrypted too late and it makes me check every time if this is the first time. Is there a way to avoid it?

vendredi 28 janvier 2022

Design pattern for declaring that class property expects a specific class or subclass

I want to declare a class property with a type that expects to be a specific class or subclass. So I need something like the following (hopefully the code is self-explanitory):

class LibraryClass
{
    private static string $utilityClass = LibraryUtilityClass::class;

    public static function setUtilityClass(string $utilityClass)
    {
        if ( is_a($utilityClass, LibraryUtilityClass::class) ) {
            self::$utilityClass = $utilityClass;
            return true;
        }
        return false;
    }
}

class MyUtilityClass extends LibraryUtilityClass{}
class FooBar{}

LibraryClass::setUtilityClass(MyUtilityClass::class); // returns true
LibraryClass::setUtilityClass(FooBar::class); //returns false (but IDE doesn't catch it)

I would really LOVE to do something more like this instead:

class LibraryClass
{
    public static [LibraryUtilityClassOrChildOf] $utilityClass = LibraryUtilityClass::class;
}
...
LibraryClass::$utilityClass = LibraryUtilityClass::class; // no issues
LibraryClass::$utilityClass = MyUtilityClass::class; // no issues
LibraryClass::$utilityClass = FooBar::class; // throws a type mismatch error (IDE will highlight)

I'd imagine this pattern is not an unusual one. I just want to extend a utility that is used by some vendor class and let LibraryClass know I'd like to use my extension instead of the default.

Does this pattern have a name, and how should it be done correctly? The first option above will work, but seems error-prone, and I'd love for my IDE to tell me it's wrong before runtime. (Maybe there's a PHPDoc way of doing this.)

I'm stuck on PHP 7.4, so no PHP 8.0 goodness for me, though a PHP8 way of doing this would certainly be nice to know.

jeudi 27 janvier 2022

Default empty usage of methods of uninstantiated class

In my system I have several classes that are not instantiated according to some configurations values. In some less frequent cases, they are not instantiated and calling it's method should just do nothing for each of it's methods. Currently, my solution is to ask whether the class instantiated, and only if so to call it's method (by && operator). So in my code whenever someone adds some new method to those classes or using an old one, if he forgets to check if it's instance was formed it leads to a bug. I think that my current solution is not elegant, makes the code less readable and bugs prone. Any suggestions? I wish to find a solution that will be applied to every new method that will be written (or at least fail in compilation if developer didn't take care of this case), and avoid checking every time applying a method whether it's class instance instantiated. Any suggestions?

How does the filter mechanisms in e commerce websites like Myntra, Amazon, Flipkart, etc., work?

Example 1: Take a website like Myntra (use this URL for reference -> https://www.myntra.com/men-tshirts?f=Categories%3ATshirts ). Here we have 21 filters for selecting a t-shirt. And everything is optional. What way of coding is required to achieve this ? Do we need any sort of design pattern or how are the permutations of all these handled in the backend.

Example 2: Consuming a Swagger API with multiple filters. Ideally you've to hit the URL (or construct the URL) based on the filter parameters you want. This again is similar to the above one of building a URL based on optional filter conditions.

Can someone provide insights on the approaches used or the best practices to achieve such tasks? I use Python and Flask, so anything in that line would be extremely helpful. If not, concept alone would be of great help.

What pattern should I use in a React form that needs an item ID when submitting?

I have a web app that requires some crud functionality. In this specific case, the user needs to update an existing item in a database. Right now I have a form component that I tried to keep as "dumb" as possible, however, now I am not so sure if it is as "dumb" as it could be while still sticking to good React patterns.

I am passing in 3 props to my form:

  1. Existing values which I then set in state as the inputs are controlled
  2. ID of the item that user is updating
  3. Function called "onSubmit" which is essentially an API call to my database. It requires updated values and an ID as arguments

On form submit, I call my "onSubmit" function that has been passed in via props, which takes in the ID I have also passed in via props as well as the new values the user has selected via the inputs on the form.

Is this the common pattern to use in this situation?

Make certain keywords in Laravel search go directly to certain pages

I've implemented a basic search on my Laravel site that searches a table of manufacturers in the database, and I'm now wanting to improve it (I could be wrong, but Scout seems like too much overkill right now to go through the headache of implementing).

I've come across sites that allow you to search by both manufacturer ("OnePlus") or manufacturer and model ("OnePlus 9T"), whereupon searching for any of those terms will take you directly to the OnePlus manufacturer page.

How should I approach implementing something like this with my own manufacturers table, and implementing something like this for manufacturer models (in the product sense, not MVC sense) when I don't have tables in the database to represent them? In the latter case, is creating a table of models for every manufacturer the only way to do this?

Where to place an actor within the state pattern?

I have problems finding the right place for an actor and a timer used in a state machine.

I found some inspiration from this site about the state pattern: State Design Pattern in Modern C++ and created a small example:

Simple door state machine

There might be more transitions possible but I kept it short and simple.

class Door 
{  
    void open() {}
    void close() {}
};

Events:

class EventOpenDoor
{
public:
    OpenDoor(Door* door) : m_pDoor(door) {}
    Door* m_pDoor;
};

class EventOpenDoorTemporary
{
public:
    EventOpenDoorTemporary(Door* door) : m_pDoor(door) {}
    Door* m_pDoor;
};

class EventOpenDoorTimeout
{
public:
    EventOpenDoorTimeout(Door* door) : m_pDoor(door) {}
    Door* m_pDoor;
};

class EventCloseDoor
{
public:
    EventCloseDoor(Door* door) : m_pDoor(door) {}
    Door* m_pDoor;
};

using Event = std::variant<EventOpenDoor,
                           EventOpenDoorTemporary,
                           EventOpenDoorTimeout,
                           EventCloseDoor>;

States:

class StateClosed {};

class StateOpen {};

class StateTemporaryOpen {};

using State = std::variant<StateClosed,
                           StateOpen,
                           StateTemporaryOpen>;

Transitions (not complete):

struct Transitions {

    std::optional<State> operator()(StateClosed &s, const EventOpenDoor &e) {
        if (e.m_pDoor)
        {
            e.m_pDoor->open();
        }
        auto newState = StateOpen{};
        return newState;
    }

    std::optional<State> operator()(StateClosed &s, const EventOpenDoorTemporary &e) {
        if (e.m_pDoor)
        {
            e.m_pDoor->open();
            **// start timer here?**
        }
        auto newState = StateOpen{};
        return newState;
    }

    std::optional<State> operator()(StateTemporaryOpen &s, const EventOpenDoorTimeout &e) {
        if (e.m_pDoor)
        {
            e.m_pDoor->close();
        }
        auto newState = StateOpen{};
        return newState;
    }

    std::optional<State> operator()(StateTemporaryOpen &s, const EventOpenDoor &e) {
        if (e.m_pDoor)
        {
            e.m_pDoor->open();
            **// stop active timer here?**
        }
        auto newState = StateOpen{};
        return newState;
    }

    /* --- default ---------------- */
    template <typename State_t, typename Event_t>
    std::optional<State> operator()(State_t &s, const Event_t &e) const {
        // "Unknown transition!";
        return std::nullopt;
    }
};

Door controller:

template <typename StateVariant, typename EventVariant, typename Transitions>
class DoorController {
    StateVariant m_curr_state;
    void dispatch(const EventVariant &Event)
    {
        std::optional<StateVariant> new_state = visit(Transitions{this}, m_curr_state, Event);
        if (new_state)
        {
            m_curr_state = *move(new_state);
        }
    }

    public:
    template <typename... Events>
    void handle(Events... e) 
{ (dispatch(e), ...); }

    void setState(StateVariant s)
    {
        m_curr_state = s;
    }
};

The events can be triggered by a client which holds an instance to the "DoorController"

door_controller->handle(EventOpenDoor{door*});

In the events I pass a pointer to the door itself so it's available in the transitions. The door is operated within the transitons only.

I have problems now with modelling the 20s timeout/timer. Where to have such a timer, which triggers the transition to close the door? Having a timer within the door instance means, I have a circular dependency, because in case of a timeout it needs to call "handle()" of the "door_controller".

I can break the circular dependency with a forward declarations. But is there a better solution?

Maybe I have modelled it not well. I'm open to improving suggetions. Thanks a lot!

JS - When to apply the module pattern

I have a module "badges.js", where I just have two methods: "increaseBadge" and "resetBadge".

//
// badges.js
//
function increaseBadge(badgeType, userId, value) {}

function resetBadge(badgeType, userId) {}

module.exports = { increaseBadge, resetBadge };

Does it have sense to apply the module pattern in order to offer a clean interface? Should I use an IIFE or just export an object?

I mean, this

const badges = Object.freeze(
  VALID_BADGES_TYPES.reduce(
    (acc, badgeType) => (
      (acc[badgeType] = {
        increase: (userId, value) =>
          increaseBadge(userId, badgeType, value),

        reset: (userId) =>
          resetBadge(userId, badgeType),
      }),
      acc
    ),
    {}
  )
);

function increaseBadge(badgeType, userId, value) {}

function resetBadge(badgeType, userId) {}

module.exports = badges;

VS encapsulating all the logic with an IIFE (does it have sens? Since I am already declaring all this related stuff in a module)

const badges = (() => {
  function increaseBadge(userId, badgeType, value) {}

  function resetBadge(userId, badgeType) {}

  return Object.freeze(
    VALID_BADGES_TYPES.reduce(
      (acc, badgeType) => (
        (acc[badgeType] = {
          increase: (userId, value) =>
            increaseUserBadge(userId, badgeType, value),

          reset: (userId) => resetUserBadge(userId, badgeType),
        }),
        acc
      ),
      {}
    )
  );
})();

module.exports = badges;

KIBANA - WAZUH pattern index

I hope you all doing well. I get an project to install wazuh as FIM on linux, AIX and windows. I managed to install Manager and all agents on all systems and I can see all three connected on the Kibana web as agents.

I created test file on the linux agent and I can find it also on web interface, so servers are connected. Here is test file found in wazuh inventory tab

But, I am not recieving any logs if I modify this test file.

This is my settings in ossec.conf under syscheck on agent server>

<directories>/var/ossec/etc/test</directories>
<directories report_changes="yes" check_all="yes" realtime="yes">/var/ossec/etc/test</directories>

And now I ma also strugling to understand meanings of index patterns, index templates and fields. I dont understand what they are and why we need to set it.

My settings on manager server - /usr/share/kibana/data/wazuh/config/wazuh.yml

alerts.sample.prefix: 'wazuh-alerts-*'
pattern: 'wazuh-alerts-*'

On the kibana web I also have this error when I am trying to check ,,events,, -the are no logs in the events.

Error: The field "timestamp" associated with this object no longer exists in the index pattern. Please use another field.
    at FieldParamType.config.write.write (http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:627309)
    at http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:455052
    at Array.forEach (<anonymous>)
    at writeParams (http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:455018)
    at AggConfig.write (http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:355081)
    at AggConfig.toDsl (http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:355960)
    at http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:190748
    at Array.forEach (<anonymous>)
    at agg_configs_AggConfigs.toDsl (http://MYIP:5601/42959/bundles/plugin/data/kibana/data.plugin.js:1:189329)
    at http://MYIP:5601/42959/bundles/plugin/wazuh/4.2.5-4206-1/wazuh.chunk.6.js:55:1397640

I will be greatfull for your help couse my boss is pushing on me and I never worked with wazuh application before :) Thank you very much

JS Refactoring - Dynamic object (key, value) where value is a high order function that invokes the same function

I have a function

function addActivityToUser(
  activityData,
  userId,
  batchOrTransaction = undefined
) {
  const newActivityRef = firestore
    .collection("activity")
    .doc(userId)
    .collection("userActivity")
    .doc();

  if (batchOrTransaction) {
    return batchOrTransaction.create(newActivityRef, activityData);
  }

  return newActivityRef.create(activityData);
}

The activity data object will always looks like:

{
    type: SOME VALID ACTIVITY TYPE,
    ...custom data
}

I have all the valid activity types in a constant:

const VALID_ACTIVITY_TYPES = ["Foo", "Bar"];

I am trying to create some kind of "single source of truth" (a centralized container or something like that).

For this, I have thought about doing the following:

//
// utils/activity/constants.js
//
const VALID_ACTIVITY_TYPES = ["Foo", "Bar"];

//
// api/activity.js
//
const activity = Object.freeze({
  add:
    VALID_ACTIVITY_TYPES.reduce(
      // eslint-disable-next-line no-return-assign
      (acc, activityType) => (
        acc[activityType.toLowerCase()] = (
          activityData,
          userId,
          batchOrTransaction = undefined
        ) =>
          addActivityToUser(
            { ...activityData, type: activityType },
            userId,
            batchOrTransaction
          // eslint-disable-next-line no-sequences
          ),
        acc
      ),
      {}
    ),
  delete: deleteUserActivityById,
}); // main exportable api

function addActivityToUser( // exportable
  activityData,
  userId,
  batchOrTransaction = undefined
) {
  console.log(`Storing ${JSON.stringify(activityData, null, 2)} to ${userId}`);
}

function deleteUserActivityById() {} // exportable

//
// main.js
//
const activityData = { text: "Hello world!" };

const userId = "nSDsAip1029dnsj";

activity.add.foo(activityData, userId);

As you can see, in my solution I am dinamically creating an object which values is a high order lambda function... Is this a pattern/anti-pattern?

I don't like using the high order function which only purpose is to attach a "type" field to the activity data and return the main method... how can I refactor that? Is it possible?


My main purpose is to avoid doing

addActivityToUser({type: VALID_ACTIVITY_TYPES[0], ...}, ...);

in every single module. Instead, at least for me, this namespaced way is better:

activity.add.foo(...)

mercredi 26 janvier 2022

Microfrontend + Clean Architecture on Frontend?

Is mixing a microfrontend + clean architecture a good combination or is it architectural overkill and overengineer?

Wordpress Html5 form validation with pattern on input fields

I have done a php code that register user in two databases with checking e-mail in database via php server-side script - working well. I have done now a html form to catch all data from client and use this php script. Anyway I got a problem with form validation by html5 built-in form validation using RegEX pattern.

Below is a code but firstable I describe what i have done yet:

  1. I have done a page on wordpress website with elementor editor.
  2. Added a codesnippet with a code snippet plugin - making a php function that place a form when shortcode is called.
  3. Placed shortcode on that page and it shows a form very well.
  4. Tested it and validation is not working. It looks like wordpress is ignoring pattern in input.

Debuging a problem:

  1. I have verified a regex code on testing website and when placed "@" it shows validation error. If I place "@" in wordpress form - it passes a validation.
  2. Tried to add found in web script to delete "novalidate" in form but not worked.
  3. Tried to delete type="text" in inputs.
  4. Tried to delete required in inputs.

Nothing is helping and im stuck without ideas how make it work... Someone knows what is going on?

CODE:

<form class="bcformularz" action="test.php" method="post">
<p>Poniższe dane zostaną zapisane w Twoim koncie do przyszłych faktur, zostaną również użyte do utworzenia konta w aplikacji.</p>
<label>Nazwa firmy</label>
<input type="text" name="billing_company" pattern="/([^\s][a-zA-Z0-9_-\s\.]+)/g" required />
<label>Imię</label>
<input type="text" name="billing_first_name" pattern="[a-zA-Z]+" required/>
<label>Nazwisko</label>
<input type="text" name="billing_last_name" pattern="[a-zA-Z]+" required/>
<label>NIP</label>
<input type="text" pattern="[0-9]{10}" name="billing_nip" required/>
<label>Ulica i numer domu.</label>
<input type="text" name="billing_adress_1" required/>
<label>Kod pocztowy</label>
<input type="text" pattern="^[0-9]{2}-[0-9]{3}$" name="billing_postalcode" required/>
<label>Miasto</label>
<input type="text" pattern="([A-zÀ-ž]+)" name="billing_city" required/>
<label>Kraj</label>
<input type="text" pattern="([A-zÀ-ž]+)" name="billing_country" required/>
<label>Telefon (opcjonalnie)</label>
<input type="text" pattern="^[0-9]{3}-[0-9]{3}-[0-9]{3}$" name="billing_phone" required/>

<label for="userpakiet">Wybierz pakiet:</label>
<select name="userpakiet" id="userpakiet">
<option value="solo">Solo</option>
<option value="basic">Basic</option>
<option value="medium">Medium</option>
<option value="pro">Pro</option>
</select>
<input type="submit" value="ZAREJESTRUJ"/>
</form>

Python Flask for background long running jobs

API sync requests for immediate response, but we have long running (5 to 100 minutes) jobs where we cannot depend on sync request, we should implement worker nodes handles long running jobs and api just submit jobs and get status.

while I am browsing, recommended way to use cache system , queue system, worker nodes similarly like below diagram approach 1

Since Redis is cache system and writing status states relying on redis cache is good approach ?

Another approach is using persistent no sql db, queue system and worker nodes like below diagram

approach2

Above approach slows down the submissions and getting status because no cache system is using.

approach 3 I am consider to go with cache no sql and persistent no sql DB similarly like below

aproach3

I am designing first time production ready application and implementing my. I want to make sure correct design principals are used.

Load estimated per second 1000 requests average

Also how difficult implementing approach 3 ?

Below is what I am expecting.

  1. Performance
  2. tasks status api states for at least last 30 days jobs.

Programming: Python Framework: Flask

How does the client knows the concrete service API in Dependency injection design pattern

I'm trying to understand the technical approach for implementing DI.

this code sample is DI taken from https://en.wikipedia.org/wiki/Dependency_injection- the injector is the c'tor:

// Constructor
Client(Service service, Service otherService) {
    if (service == null) {
        throw new InvalidParameterException("service must not be null");
    }
    if (otherService == null) {
        throw new InvalidParameterException("otherService must not be null");
    }

    // Save the service references inside this client
    this.service = service;
    this.otherService = otherService;
}

Now, 2 DI principles:

  1. Thanks to the Service interface the client doesn't care who's the concrete service.
  2. The client need to know the concrete service API.

My question: What is the technical way in which the client get to know the API of the injected service?

mardi 25 janvier 2022

Design Pattern Help --each object can alter the state of the other?

I am new to design patterns so seeking guidance. I believe I should use an observer pattern but is this true if each observer can alter the state of the other?

Specifically, my situation is as follows: I have a numpy array of elements e.g. 10x10 array. I have a separate object that I plan to make a class - Object A. Each instance of object A connects to a subset of the 10x10array but importantly there can be overlap so at position 4, 3 in the array I might have concrete objects A, B, and E attached.
Now, during the course of the program there are rules which govern how many objects can be attached to 1 array element as well as requirements on the objects to attach to a certain number of array elements. As a result, concrete object A can alter the state of the array elements i.e. attach to different positions in the array, but depending on the array elements' other attached concrete objects this can affect how A connects. In other words, my attach objects need to "observe" the array and the array elements need to "observe" the attach objects. Should I use an observer design pattern or is there some other pattern I should be exploring?

Not sure if it matters but this will be a python implementation.

Design pattern for checking two modes (online/offline) in multiple places

I'm working on a Xamarin application. Currently the app works in Offline mode. In Offline mode, user download a SQLite database from a server. The app then queries data from this SQLite database to display and performs CRUD actions. Changes will be synced to server when user clicks sync button.

Now, I want to implement an Online mode. In Online mode, whenever the user go to a screen, it will make a WebApi request to the server. Same goes for CRUD actions.

UI will be the same in two modes (Online/Offline). User can choose which mode they want to work on. I want to prevent the use of mode checking conditional statement in all places.

For example, when user goes to screen A conditional statement will looks like

if (mode == "Online") {
  getDataOnline();
} else if (mode == "Offline") {
  getDataOffline();
}

This check will be required in most places.

What would be a design pattern or best way to achieve this?

Azure Subscription design [closed]

There are many ways in which Azure Subscriptions can be grouped along with Management groups. I am having a dilemma if one should have a dedicated subscription of horizontal IT services such as data integration, wherein all data integration services for all the different projects/products live in a single subscription. Alternatively, one can also club all services related to a specific product including integration services, storage, etc. in same subscription(different resource groups). I am trying to identify the limitations(technical/process overhead/DevOps, etc.) one approach may have over the other.

Laravel modualr [closed]

I created an Affiliate Module, but the error message still appears

[Symfony\Component\Debug\Exception\FatalThrowableError]
Class 'Modules\Affiliate\Providers\AffiliateServiceProvider' not found I have no idea what this error means. Could you please help me. Thanks

lundi 24 janvier 2022

Design ideas for managing multiple third party apis with separate authentication methods

Trying to figure out the best approach to design for the following:

We have a REST API that is going to fetch plant data. We have a few third party plant data providers.

  1. Each provider has its own REST API
  2. Each provider has its own authentication/authorization method (OAuth1.0, 2.0, etc)
  3. We aren't guaranteed that the authentication methods are the same

A request to our main REST API will switch based on provider, so different logic will be handled for each provider. In turn we will need to pull down the appropriate authentication for the third party api.

Here are a few design features I have locked down to start off:

  • definitely going to need an external cache to store the various providers access tokens
  • going to implement a few functions like get_token and refresh_token
  • The AuthToken will look something like:
@dataclass
class AuthToken:
   access_token: str
   expiration_date: int
   generation_date: int
   refresh_token: str


   def get_access_token(self):
       pass

   def refresh_token(self):
       pass

I have these ideas floating around, but the class design for this authentication stuff is evading me. so any help there would be awesome. I also included a few ideas below.

Ideas:

  • Creating an implicit interface with Protocols and then having each provider have its own ProviderAuthToken class. So when we switch based on provider we just pass in its respective AuthToken class.
  • Maybe I'll need an Authentication class to store the provider's necessary variables to like generate a JWT or whatever we may need.

Probably missing a whole bunch of stuff, but thanks a ton for any help. I'm new to the field as well so any general tips are welcome!

Other considerations:

  • using lambda
  • using python

Also took inspiration from this question! :)

Design Pattern recommendation

I'm developing an application that is to be run in two separate offices. The UI needs to be consistent, however some of the buttons on the UI will change depending on which office is running the application along with the functional logic behind those buttons. Which design pattern is recommended to code the following in Python? The aim is to be able to re-use components for the application being developed for both offices without having to maintain duplicate code.

To help illustrate with a very simple example:

Sample UI

In the attached screenshot - if the application is being run in Office A only show "Contact Us" with it's own code logic, however if the application is running in Office B, show both "Contact Us" and "Lets work together" with their own separate code logic different from Office A.

Thanks

Why DDD for CQRS and Event Sourcing application?

I am just starting with the CQRS, Event Sourcing. While examining many frameworks, I have realized that one of the thing most of the frameworks assumed that our application is modelled based on the DDD principles. I am not sure but can anyone explain to me that how DDD, CQRS, and Event Sourcing are related to each other and why DDD is generally required for implementing the CQRS and Event Sourcing pattern?

power query design patterns?

At work, I'm stuck with 32 bit Excel,which I understand is known for poor power query performance. This is also my personal experience. Typically when I start a new Power Query project, all goes well for a couple of days, until things get increasingly complex, and everything slows down to the point where I spend 10 times as much time waiting for refreshes than actually developing, which is highly frustrating. By the time the refresh finishes, I've often forgotten what I wanted to do next. I'm not getting any younger :( What I've started doing is splitting my project into two or more workbooks, each of which does some power query heavy lifting, such that my 'dashboard' workbook does very little recalculation, it just connects to the latest refreshed data in the underlying workbooks. This approach works well for me, but I haven't seen it covered anywhere, so I was wondering if any of you adopted the same approach, or had other better techniques to address this problem. I feel that PQ is still quite immature in many ways, especially the IDE. This said, I think it's already very powerful, and I look forward to what the next few years will bring.

dimanche 23 janvier 2022

How to create this christmas tree pattern?

e

so I'm trying to create this Christmas tree pattern using the loop, if the number increase, the number of layers as well as lines will increase, so how to do this ples

Chaining of rest API calls [closed]

Problem : orchestration design pattern or implementation

use case : I have n rest api calls each has it's own request and response and they should be called in sequence like response of 1 can be used in making request of another call and in end i need to return final response which can have values mix of all responses from diff api's.

Prototype or Pseudocode as below : 

Class - > returnType methodName(RequestObject request)

Service A - > ResponseObjectA callA(RequestObjectA request)
Service B - > ResponseObjectB callB(RequestObjectB request)
Service C - > ResponseObjectC callC(RequestObjectC request)
Service D - > ResponseObjectD callD(RequestObjectD request)


public class OrchestrationService {


@Autowired
ServiceA a;

@Autowired
ServiceB b;

@Autowired
ServiceC c;

@Autowired
ServiceD d;

 public finalResponse orchestrationFlow(OrchestrationRequest request) {

--transformer to convert request to RequestObjectA
ResponseObjectA roa = a.callA(RequestObjectA)
--transformer to convert request and roa to RequestObjectB
b.callB()
-- tranformer
c.callC()
--transformer
d.callD()

--Made finalResponse

}

This is how i am doing right now, but it seems to be tightly coupled. Can anyone suggest me how i can achieve this in a loosely coupled way ? I looked for chain of responsibility design pattern but not able to think from design point of view.

samedi 22 janvier 2022

Decorator pattern on a panel

I am trying to make a winform Panel that will be scrollable with a decorator design pattern. But I dont understand how I can use it with an interface because than I am losing all of the panel properties like size,location etc.

when I initialize the component I declare him like this:

IPanel scrollablePanel= new VScrollablePanell(new CorePanel())

I am probably doing something wrong but I cant figure it out, hope you can help me out

public interface IPanel
    {
        void Operation();
    }

    public class CorePanel : Panel,IPanel
    {
        public void Operation() { }

    }
    public class PanelDecorator :IPanel
    {
        protected IPanel m_Decorated;
        public PanelDecorator(IPanel i_Decorated)
        { m_Decorated = i_Decorated; }
        public virtual void Operation()
        { m_Decorated.Operation(); }

    }
    public class VScrollPanel : PanelDecorator
    {
        public VScrollPanel(IPanel i_Decorated) :
        base(i_Decorated)
        { }
        public override void Operation()
        {
            Scroll();
        }
        private void Scroll()
        {
}

How to Model pattern matching using ML - various input predict output

The Blackbox shown provides outputs based on input. Outputs are sometime string concatenation of parts or whole input sometime they are multiplication of two input. I want to create ML model which can predict output1 , ouput2 ... output5 based on provided input1, input2.. input5

Basically I am trying to reverse engineer Black box. Diagrams below show sample data and High level view.. The Blackbox could vary.

What kind of Models can I use for the string pattern ( LSTM, RNN .. ?) High level view

Sample data sample data

exporting function vs const then export

I'm a NOOB to NodeJs and trying to understand the difference and pros and cons to a couple of patterns ....

In a controller I often see people use :

exports.myFunction = async function (req, res) { ......}

In other examples I see

const myFunction = async function (req, res) { ......}
module.exports = {myfunction}
  1. what is the advantage of declaring the function as constant then exporting it vs exporting it as part of the definition? Is it just style, or will it make the code more testable or something else?

  2. I have seen that people code services as classes and export the whole class. Is this best practice?

  3. Why not define controllers as classes, and why not export the class?

I see these patterns mixed up in various articles talking about patterns and practices and haven't got my head around the nuances.

Thanks.

vendredi 21 janvier 2022

Are shortness of time and no clients a reason to go for a monolithic backend app? [closed]

I've a client who plans to create an application that'll let companies to offer its co-work spaces and users to be able to choose which of them they want to go. There will be multiple type of users that will be able to access different kind of applications/dashboards to administrate its data.

I started to think into building a microservices layer but then I start having doubts weather it'd be good to go for a monolithic approach.

My question is: is it ok to go for a monolithic pattern when having these concerns?:

  • Rush to have an MVP in production.
  • No clients, so no incomes yet.
  • Good ideas, but not very defined. Only a small to medium workflow is clear and is the one I'm working on.
  • Related to #2, they are spending a lot of money in developers and they need to start seeing some profit soon to be able to validate if the product works. Having a microservies layer will be more expensive than a monolithic due to more databases, instances, etc.

Dynamically use Type for a method in Generic

I have many Schemas as below:

public class Schema1 
{
   public string prop1 {get; set;}
   public int prop2 {get; set;} 
}

public class Schema2 
{
   public DateTime prop3 {get; set;}
   public bool prop4 {get; set;} 
}

Now I want to dynamically get their type and call below method where T is Schema1 or Schema2 and so on. Below method returns objects of T i.e. List, List, List... so on. Below I am passing Type as well in parameter but confused how to use it.

public static List<T> Method1(string param1, out SchemaError[] errors, Type type)
{
List<T> list = new List<T>();   
// other Operations
list = JsonConvert.DeserializeObject<List<T>>(string);
return list;
}

How can I approach this problem? Is there any way through Interface or any design pattern to separate out schemas? I know there is a way through reflection

MethodInfo method = typeof(ClassName).GetMethod(nameof(MethodName));
MethodInfo generic = method.MakeGenericMethod(schemaType);
return generic.Invoke(Activator.CreateInstance(typeof(ClassName)), new object[] { param1 });

but there are some limitations with reflection approach.

Angular component Design pattern or principle

How should we get rid of if else/switch statement - business logic for specific components?

For example, I want to display data in my table and I have created 2 components. 1st is Smart component - table wrapper and 2nd is dumb component - table component.

<table-wrapper> smart component which is responsible to load the data and pass the data to my embedded component
   <table></table> dumb component which takes just input data and then output for emit the events
</table-wrapper>

As per Single responsibility principles, one component should do a single task, not multiple tasks. I have 100 tables and use this single component to render and display the data. In some tables, I have a couple of conditions for different scenarios which I don't want to write in my component which becomes very large files in the future and we end up writing an if-else/switch statement. How should we manage this type of additional separate logic for any component which is not responsible for a specific component. I am not quite sure if I need to follow any design pattern or principle.

NullPointerException with java and Selenium, TestNG and POM design pattern [duplicate]

Can you please tell my How I can fix this Null Pointer Exception?

import org.openqa.selenium.WebDriver;
            import org.openqa.selenium.chrome.ChromeDriver;
            import org.openqa.selenium.support.PageFactory;
            import org.testng.Assert;
            
            
            import java.util.concurrent.TimeUnit;
            
            
            public class BasePage {
            
            
                public WebDriver driver;
            
            
                public HomePage openBrowser() {
                    System.setProperty("webdriver.chrome.driver", "C://Users//Cata//Desktop//ChromeDriver1//chromedriver.exe");
                    driver = new ChromeDriver();
                    driver.manage().window().maximize();
                    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
                    driver.get("https://www.emag.ro/homepage?ref=emag_CMP-60801_stock-busters-martie-2020");
                    return PageFactory.initElements(driver, HomePage.class);
                }
        
        
        
        import org.openqa.selenium.Keys;
        import org.openqa.selenium.WebElement;
        import org.openqa.selenium.support.FindBy;
        import org.openqa.selenium.support.PageFactory;
        
        
        public class HomePage extends BasePage {
        
        
            @FindBy(id = "searchboxTrigger")
            public WebElement searchBox;
        
        
            public SearchPage clickSearchPage() {
        
                searchBox.sendKeys("Rasnita de cafea");
                searchBox.sendKeys(Keys.ENTER);
                return PageFactory.initElements(driver, SearchPage.class);
            }
        
        }
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.FindBy;
    import org.openqa.selenium.support.PageFactory;
    
    public class SearchPage extends BasePage {
    
    
    
          @FindBy(css = "input.form-control.js-custom-price-min")
          public  WebElement minimPrice;
    
          @FindBy(css = "input.form-control.js-custom-price-max")
          public WebElement maxPrice;
    
          @FindBy(css = "button.btn.btn-alt.js-custom-price-trigger")
          public WebElement filterButton;
    
          @FindBy(xpath = "//*[@id=\\\"main-container\\\"]/section[1]/div/div[2]/div[2]/div/div/div[2]/form/div[3]/button[1]")
          public WebElement caffeMachine;
    
        public SearchPage(WebDriver driver) {
            this.driver = driver;
    
        }
    
    
    
        public SearchPage filterPrice(){
               minimPrice.clear();
               minimPrice.sendKeys("200");
               maxPrice.clear();
               maxPrice.sendKeys("800");
               filterButton.click();
               return PageFactory.initElements(driver, SearchPage.class);
    
        }
    
        public ProductPage getCaffeMachine() {
            caffeMachine.click();
            System.out.println("Product is in cart");
    
    
              return PageFactory.initElements(driver, ProductPage.class );
        }
    }

    import org.openqa.selenium.WebDriver;
    
    public class ProductPage extends BasePage {
    
    
    
        public ProductPage(WebDriver driver) {
            this.driver = driver;
        }
    
        public void addToCart(){
    
        }
    
    }
    
    
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;

public class EmagTest {


    HomePage homePage;
    SearchPage searchPage;
    ProductPage productPage;


    @Test
    public void writeEmagTest() {

        BasePage basePage = new BasePage();

        homePage = basePage.openBrowser();

        searchPage = homePage.clickSearchPage();
        searchPage.filterPrice();
        productPage = searchPage.getCaffeMachine();

        productPage.addToCart();
    }
}
    
    

The error message is: java.lang.NullPointerException at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69) at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38) at com.sun.proxy.$Proxy6.clear(Unknown Source) at SearchPage.filterPrice(SearchPage.java:30) at EmagTest.writeEmagTest(EmagTest.java:21) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:134) at org.testng.internal.TestInvoker.invokeMethod(TestInvoker.java:597) at org.testng.internal.TestInvoker.invokeTestMethod(TestInvoker.java:173) at org.testng.internal.MethodRunner.runInSequence(MethodRunner.java:46) at org.testng.internal.TestInvoker$MethodInvocationAgent.invoke(TestInvoker.java:816) at org.testng.internal.TestInvoker.invokeTestMethods(TestInvoker.java:146) at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:146) at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:128) at java.util.ArrayList.forEach(ArrayList.java:1255) at org.testng.TestRunner.privateRun(TestRunner.java:766) at org.testng.TestRunner.run(TestRunner.java:587) at org.testng.SuiteRunner.runTest(SuiteRunner.java:384) at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:378) at org.testng.SuiteRunner.privateRun(SuiteRunner.java:337) at org.testng.SuiteRunner.run(SuiteRunner.java:286) at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:53) at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:96) at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187) at org.testng.TestNG.runSuitesLocally(TestNG.java:1109) at org.testng.TestNG.runSuites(TestNG.java:1039) at org.testng.TestNG.run(TestNG.java:1007) at org.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:72) at org.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:123)

Whats a good way to implement an extended data structure in a pipeline pattern?

I want to implement a pipeline pattern. That means i want to implement multiple stages working on a common job in a sequential manner. The stages themselves get a reference to the jobs data, and can modify this data:

class PipelineJob{
  final JobData data;
  final stages = [FirstStage(), SecodnStage()];
  run(){
    for(stage in stages){
      stage.run(data);
    }
  }
}

class PipelineStage{
  run(JobData data){
    // do something with data
  }  
}

class Pipeline{
  InputData input;
  OutputData result;
  start(InputData input){
    final job = PipelineJob.fromInput(input);
    job.run(); 
  }
}

So far, so good. But now i might have some data in the job, that is conditional on some type. And stages want to process this data differently depending on this type. Specifically, lets say, job data is structured in the following way:

class JobData {
  List<Info> infos;
}

class Info {
  DateTime time;
}

class ExtendedInfo extends Info {
  int count;
}

Depending on the type of info a stage mgith want to modify an Info object or might expect an ExtendedInfo, but might not want to change the type of the object. So i can check if an object is an ExtendedInfo with is ExtendedInfo and i can run the stage conditionally.

But for a general stage, that would process Info in general: How can i guarantee, that my stage will create ExtendedInfo objects, when my stage is trying to replace an existing ExtendedInfo object in the jobs job.data.infos?

  1. Inheritance: One way would be to let the stage always check with is ExtendedInfo and create the appropiate type and then store it.
class Info{
  DateTime time;
  int? counter;
}

class ExtendedInfo extends Info {
  int count;
}

class JobData{
  List<Info> infos;
}

class FirstStage implements PipelineStage{
  run(JobData data){
    for(int i = 0; i<data.infos.length; i++){
      if(data.infos[i] is ExtendedInfo){
        data.infos[i] = processExtendedInfo(i);
      }
    }
  }

  ExtendedInfo processExtendedInfo(ExtendedInfo i){
    // process it, create and return result
  }  
}
  1. Optional parameters: Another way, would be to merge ExtendedInfo and Info into one Info class with more optional fields:
class Info{
  DateTime time;
  int? counter;
}

class JobData{
  List<Info> infos;
}

that would give better type safety, but in general this practice would make null checks necessary every time one tries to use an extended info.

  1. Extension class: I could move the "extension" of Info into an optional extension class
class Info{
  DateTime time;
}

class InfoExtension{
  int counter;
}

class JobData{
  List<Info> infos;
  List<InfoExtension?> infoExtensions;
}

this preserves type safety, requires handling the lists together doe, which is kinda awkward. One could easily forget to update infoExtensions alongside with infos.

Is there a best practice?

jeudi 20 janvier 2022

Is decoupling design system and ui-component library a good approach

I am in process of creating a design system and thinking of decupling ui-component library system from it. My reason is - design specification will come from different team and ui-component will be designed by a different team. I want both the teams to work independently. So, design team will create/update design spec and release to ui-component team. UI team will work on creating/modifying component. Meanwhile design team start working on new version of specification or optimization.

What you suggest on this.

Interface in an array

Hye everyone, Do you know if it is good practice to make a table with an interface like this? :

 public interface ITemp
 {
    void Findpath();
 }

 public class TempUn : ITemp
 {
    public void Findpath()
    {
          throw new System.NotImplementedException();
    }
 }

 public class TempDeux : ITemp
 {
     public int deux;
     public void Findpath()
     {
          throw new System.NotImplementedException();
     }
 }

 public ITemp[] TabTest;

 public void init()
 {
     var un = new TempUn();
     var deux = new TempDeux();

     TabEssai = new ITemp[2];
        TabEssai[0] = un;
        TabEssai[1] = deux;
 }

I'm asking this because if I understand correctly the creation of the array allocates a fixed memory. I'm not sure if it's a good idea to create an array of elements that respect the interface but are of variable size, , is that a problem?

Good Day,

Each service in a IEnumerable

I have a service that will be available in my app via dependency injection, but this service itself will have a subservice injected into it, which can be from varying services that inherit from ISubService.

Start -> Will have multiple Services of type IService -> Each IService will have a different service that inherits from ISubService.

It doesn't have to inherit, I just thought this would be the first step to solve my problem.

Interfaces

interface IService
interface ISubService
interface ISubService1 : ISubService
interface SubService2 : ISubService

Service that has to have multiple instances, with a different subservice each time

public class Service: IService
{
   public Service(SubService ISubService, ... ) { ... }
}

My registration of services.

services.AddTransient<IIService, Service>(); // This service should have SubService 1
services.AddTransient<ISubService1, SubService1>();
services.AddTransient<IIService, Service>(); // This service should have SubService 2
services.AddTransient<ISubService2, SubService2>();

Class that will have multiple services, with different subservices

public class Start
        public Start(IEnumerable<IService> services, ... ) { ... }

I have tried adding a parameter to the construction when adding the transient, but this does not work as I have other parameters via dependency injection which are expected.

Thank you for your help in advance.

can you help me to write this pattern [closed]

We want to put all the strings of length n consisting of the letters 0 and 1 in a row in such a way that if we write the two adjacent strings in a column, they will differ from each other in only one letter.

1<=n<=15

ex)please enter number:2

00

01

11

10

ex) please enter number:3

000

001

011

010

110

111

101

100

mercredi 19 janvier 2022

Message sequencing in Distributed Env

I need some guidance on the solutioning of a problem which I am facing at the moment. I have a microservice which is deployed in 8 pods and it has a JMS listener which is enabled in all the pods to increase parallelism.

Now the event is getting processed in different order and not able to maintain the order of event processing. The business required the events to be processed in a specific order (Event contains a sequence no, which guarantees the order). But we need the parallelism in place to run the listeners in multiple pods.

If anyone have any suggestions of how to design it, please can you share? using DB or redis or any other component?

Thanks Sandeep

SQLalchemy internals and design pattern

What is the design pattern in SQLalchemy and how does it work?

  1. I wonder how defining each column as class variable in a child class of db.Model provides necessary information to create table. How does db.create_all get these data?

  2. We usually don't explicitly define init for the table, however we can use the initializer. How this is done?

  3. Why this design has been used? Is it because class variables are initiated when the interpreter reaches the definition, while there can be many instances?

shared data between two python projects

I have 2 systems written in python. One of them pass data to the Other (the other get data from different sources as well) using tcp Socket and checking if the connection is a alive "manually". I thought about changing the passing data from tcp socket to something that design for this stuff, from what I read something like rabbitMQ, Kafka. my only requirements are 'real-time' and reliable so I could know if there some problem in passing the Data. I would be happy to hear your thoughts about the subject (and maybe get some links about this issue). I also need to mention that the systems run apart from each other on different servers for a reason. (the data is json messages)

Microservices Architecture - API Gateway with Aggregator

I am trying to build a system which involves a client which will talk to a few microservices. I got to the point where I realize I don't want the client to communicate directly with all the microservices so an API Gateway sounds like the right choice.

The issue is with the API Composition, I came across 2 options that I am trying to understand.

  1. The API Gateway aggregator is quite understandable as it will query the microservices on its own and combine the result to return to the client. From what I understand it means that it has to have some of the logic of all microservices, is that correct? If so, is it a good approach?

  2. The API Gateway with the Aggregator pattern (separately). If I implement these 2 I will get something like this: API And Aggregator

From what I see it appears that the API Gateway will no longer do any routing since it has a bottleneck to that aggregator (which will do the requests to other services on its own). So I will get only Auth, Cache and load balancing from the API Gateway but the aggregator will do the routing as if he is the gateway?

How to write Builder Pattern for class that extends abstract class in Java?

I have the "Client" class that extends abstract class "User":

public abstract class User {
    private Long id;
    private String firstName;
    private String lastName;
    private String email;

   //getters and setters
}

public class Client extends User{
    private List<Account> accountList;

    //getters and setters
}

I have written the builder for the "Client" class, but I can't have access to the User's fields (id, firstName, lastName, email) for use it all in building. How to do it?

public class Client extends User {
    private List<Account> accountList;

    public static Builder builder() {
        return new Client().new Builder();
    }


    public class Builder {
        private Builder() {
        }

        public Builder setAccountList(List<Account> accountList) {
            Client.this.accountList = accountList;
            return this;
        }

        public Client build() {
            return Client.this;
        }
    }
}

mardi 18 janvier 2022

Better solutions to long pattern matching chains (for Dart)

I've often found myself having to use annoying patterns like:

ClassA extends BaseClass {
  static bool is(val) { ... }
}
ClassB extends BaseClass {
  static bool is(val) { ... }
}
...
ClassZ extends BaseClass {
  static bool is(val) { ... }
}

BaseClass parser(val) {
  if(ClassA.is(val)) {
    return ClassA(val);
  } else if(ClassB.is(val)) {
    return ClassB(val);
  ...
  } else if(ClassZ.is(val)) {
    return ClassB(val);
  }
}

This is very error prone and requires a lot of monotonous code. I was wondering if there was a way to expedite this process in a non-language specific (or in a language specific for Dart) way that doesn't involve listing all the pattern matchers after they've been defined. I would like to avoid this as I had too many bugs to count caused by forgetting to list one of the already defined class's pattern matcher.

How to crate a list of objects and execute them one by one?

I need to create a list of objects and execute them one by one in 2-3 threads. When the first object finishes executing, another one starts to execute in it's place. All objects are members of the same class with different input parameters. There can be a lot of objects of this class and therefor I cannot hardcode them as written below. I like to find the best way to solving this issue.

// The simple class. He do nothing 
public class SomeClsass implements Runnable{

    run(){
        sum();
    }
    
    // The simple function
    private void sum(){
        
        // Some code. It doesn't meaning 
        int j =0;
        for(int i=0; i<=10000; i++){
            j=i; 
            
        }
    }
}

public static void main(String args[]){
    
    // I don't wont to create objects as here
    SomeClass someClass = new SomeClass();
    SomeClass someClass1 = new SomeClass();
    SomeClass someClass2 = new SomeClass();
    SomeClass someClass3 = new SomeClass();
    // ...... more then 1000 objects
    
    
    // When this two objects finishes one by one next object will starts executing 
    someClass.run();
    someClass1.run();
    

}

Why some methods of ndarray are present as an equivalent function in top-level of numpy?

I see there is ndarray.reshape and also numpy.reshape and the documentation mentions them to be equivalent. Similarly for ravel. If that is the case, why did they make unnecessary duplicate of these methods in numpy namespace while also breaking one of the Zen principle

There should be one-- and preferably only one --obvious way to do it.

Why numpy has two ways to resize viz "numpy.resize" and "ndarray.resize"?

Why it didn't went with a single way with some extra parameters to incorporate the minor difference between both the ways?

lundi 17 janvier 2022

Which design pattern best suits for my scenario

I'm still junior into programming, and would like to use best practices for my current project.

  • I have checkout with checkout data.
  • Shipping will be calculated based on products (quantity, weight) and shipping address.
  • I have multiple shipping providers.
  • At first I want to use ShippingProvider 1 to calculate shipping price.
  • If shipping can't be calculated I want to use ShippingProvider 2
  • Again, if shipping can't be calculated I want to use ShippingProvider 3
  • At the end if none of the providers respond with shipping I want to use fixed shipping set in database.

I was thinking about Strategy pattern but in my case it can be run all of the strategies during checkout. Do you have any ideas how can be done in the correct way?

typescript : Mixin vs Generic class

In below example, How can i serve same purpose using Mixin while GenericClass is working expected.

import "reflect-metadata";
import Knex, { Knex as KnexSpace } from "knex";
export const knex = Knex({
  client: "pg",
})
type Constructor<T = {}> = new (...args: any[]) => T;
const tableMetaName = Symbol("table");

export function Mixin<TBase extends Constructor>(Base: TBase) {
  return class extends Base {
    query = knex.table<KnexSpace.CompositeTableType<TBase>>(
      Reflect.getMetadata(tableMetaName, Base).tableName
      );
  };
}

export class GenericClass<TBase extends {}> {
  query = knex.table<KnexSpace.CompositeTableType<TBase>>(
    Reflect.getMetadata(tableMetaName, this.constructor).tableName
  );
}




class User {
  id: number;
  firstname?: string;
}

const userModal = Mixin(User);
new userModal().query.insert({ id: 1 }); // Error Argument of type '{ id: number; }' is not assignable to parameter of type 'typeof User | readonly (typeof User)[]'.

new GenericClass<User>().query.insert({ id: 1 });

sharing you same on typescript-playgroud

I need help to print this pattern in python, i have given my approach but couldnt figure out pls support

Required Pattern

My Approach Code:

n=int(input(":"))
for i in range(n+1):
    for j in range(1,i+1):
        print(","+str(j), end="")
    print()
    
for i in range(n, 1, -1):
    for j in range(1, i):
        print(","+str(j), end="")
    print()

But Couldnt get required pattern pls help

dimanche 16 janvier 2022

Allowing a class to perform an internal operation on another

Say you have two interfaces: IPatient and IOperator. Each class derived from IOperator needs to be able to perform a unique operation on an instance of a class derived from of IPatient. I'll call subclasses of these "Patients" and "Operators" for brevity's sake. Each operation requires access to the Patient's internal members (whether direct or indirect), and the actual operation may differ depending on which Patient is being operated on.

Consider PatientA and PatientB. We have the concept of an operation that makes the patient's internal member become "true", but it must be done differently depending on the patient, as you can see:

class IPatient {};

class PatientA : public IPatient { bool setMeToTrue = false; };
class PatientB : public IPatient { const char* setMeToTrue = "false"; };

Every solution I can think of requires one of the following:

A) Declaring every Operator a friend of Patient
B) Giving Patient a separate public method for each Operator (teach Patient to operate on itself, Operator just says "do it")
C) Some solution involving an enum of every Operator and a big select statement or similar

The problem with these approaches is that they all require modifying Patient (or some monolithic enum) whenever a new Operator is added to the codebase. Also, since each operation is unique to an Operator, having the operation be defined externally to the Operator who performs it feels like a fault in the design. Why even bother having Operators if someone else does all the work?

Is there any way to do this without resorting to the methods listed above?

I have trouble understanding the flow of pipeline design pattern, especially how the chain of steps are executed one after the other?

I am trying to implement pipeline design pattern using reference from : https://java-design-patterns.com/patterns/pipeline/ and https://medium.com/@deepakbapat/the-pipeline-design-pattern-in-java-831d9ce2fe21

I have created example classes as below to debug and understand the flow .When the call jobPipeline.execute(12); in PipelineRunner.class is fired, only first step's method should be executed correct? but how come other steps(second and third steps) are also getting executed one after the other?

Step.class

public interface Step<I, O> {
  O executeStep(I stepData);
}

Pipeline.class

public class Pipeline<I, O> {

  private final Step<I, O> current;

  public Pipeline(Step<I, O> current) {
    this.current = current;
  }

  public <K> Pipeline<I, K> next(Step<O, K> step) {
    return new Pipeline<>(input -> step.executeStep(current.executeStep(input)));
  }

  public O execute(I input) {
    return current.executeStep(input);
  }
}

PipelineRunner.class

public class PipelineRunner {

  public static void main(String[] args) {

    Step<Integer, Integer> firstStep = x->{ System.out.println("First step");
      return 2; };

    Step<Integer, Integer> secondStep = x->{ System.out.println("Second step");
      return 2; };

    Step<Integer, Integer> thirdStep = x->{ System.out.println("Third step");
      return 2; };


    var jobPipeline = new Pipeline<>(firstStep)
        .next(secondStep)
        .next(thirdStep);


     jobPipeline.execute(12); //How rest of steps( second and third step) are executed with this single call on the jobPipeline object?

  }

}

Ouput:

First step
Second step
Third step

Is folder name shadowing 3rd-party package name or Python module name is an anti-pattern?

Consider the following (very simplified) project structure:

project/
    src/
        collections/
        validators/
        foo/
        bar/

The "collections" sub-directory name shadows the Python's "collections" module.

The "validators" sub-directory name shadows "validators" 3rd-party package name.

Question:

Is it an anti-pattern to have sub-directories with the same names as Python modules or 3rd-party packages?

Note, the real project structure has about 100 sub-directories, so it is a bit hard to do not shadow names.

Vuex: single load of several datasets

In my Vue project, there are some references data, changing very rarely (payment methods, predefined service types etc.). I can load them conditionally

    async loadPaymentTypes({state, commit}) {
        if (state.payment_types.length === 0 ) {
            const data = await axios.get('/api/v1/payment-types');
            commit(setPaymentTypes, data.data);
        }
    },

but I hate to copypaste that code (and you see, it's a prototype, I have to add error handling to all actions).

How can I make some good factory like

async loadPaymentTypes({state,commit}) {
    check_load(state.payment_types, '/api/v1/payment-types', 'setPaymentTypes')
}

?

samedi 15 janvier 2022

Apply a method to all fileds of a case class of a specific type

I'll give an example/motivation for what I'm trying to do.

Imagine I have a Money case class, and a way to convert it's value from one currency to another:

case class Money(currency: String, amount: BigDecimal) {
  def convert(date: LocalDate)(using cc: CurrencyConverter): Money = {...}
}

The CurrencyConverter is a Map with daily exchange rates between currency, so that I can use the convert method to go for example from something like Money("EUR", BigDecimal(100)) to Money("USD", BigDecimal(114.13)).

Then, I have a lot of different case classes with one or more Money fields. For example:

case class House(date: LocalDate, price: Money, city: String)

case class MarketData(
    exchange: String,
    ticker: String,
    date: LocalDate,
    closingPrice: Money,
    openPrice: Money
)

Since I could data where the data is in a lot of different currencies, for example

val house1 = House(LocalDate.parse("2010-01-01"), Money("USD", BigDecimal(400000)), "San Francisco")
val house2 = House(LocalDate.parse("2018-01-01"), Money("EUR", BigDecimal(200000)), "Rome")

it would be useful to give each case class a method convertCurrency to allow them to convert their Money fields to a common currency.

I could define a trait with an abstract method and manually override it inside each case class definition, like so:


trait MoneyConverter[A] {
  def convertCurrency(using cc: CurrencyConverter): A
}

case class House(date: LocalDate, price: Money, city: String)
  extends MoneyConverter[House] {
  override def convertCurrency(using cc: CurrencyConverter): House =
    House(date, price.convert(date), city)
}

case class MarketData(
                       exchange: String,
                       ticker: String,
                       date: LocalDate,
                       closingPrice: Money,
                       openPrice: Money
                     ) extends MoneyConverter[MarketData] {
  override def convertCurrency(using cc: CurrencyConverter): MarketData =
    MarketData(
      exchange,
      ticker,
      date,
      closingPrice.convert(date),
      openPrice.convert(date)
    )
}

but it seams like I'm repeating myself. Each method is doing basically the same: it is applying the convert method to each Money field, and leaving the other fields as they were.

So my question is: Is there a way for me to describe this behavior for a generic class A, so that I can then just extend the MoneyConverter trait, without having to manually override the convertCurrency method for each case class?

Achieving DRY and decoupling with incongruous APIs

In my time as a game engine developer, I have frequently encountered the following scenario, and I've never seen a particularly great solution to this problem. I hope to break this down so that it's generic enough to be discipline-agnostic and people from other fields can chime in.

Scenario

Say we're designing an API. Part of this API is described by InterfaceA and InterfaceB. This allows us to provide many diverse implementations of their respective responsibilities, then dynamically select or modularly swap them at runtime without needing to alter the client code. This is especially useful when the implementations use components that are available on some platforms but not others. This design allows us to provide at least one permutation of modules that completes the API on every desired target platform.

Problem

APIs in the wild come in all shapes and sizes, and the ways they interact can get quite ugly.

Consider a windowing API and a rendering API. The former provides a desktop window, and the latter provides a context in which we can draw graphics into the window. In a perfect(ly standard) world, every window would provide a simple CreateRenderer() method that would let us choose our desired implementation, and the window would take ownership of it. Unfortunately, this is not that world. Here are a few examples of asymmetries we might encounter in the ecosystem of APIs:

Potential Windowing API Constraints
• Needs to know which rendering API will be used in advance before a window can be constructed.
• Windowing API may not be compatible with all rendering APIs available on the platform.
• Changing certain renderer settings requires destroying the window and creating a new one that "supports" the desired value for the setting.
• When the window is resized, it will have to report the new size to the renderer so it can react to the change. (for pathological fun, let's say one renderer doesn't even support resizing and will crash if you try)

Potential Rendering API Constraints
• Requires some sort of ID for an existing window, which manifests in many different types/formats depending on which windowing API we used.
• The implementation might need to follow different code paths depending on which windowing API is used. • The renderer needs to know the "capabilities" of the window so it doesn't try to do anything unsupported.

I said I would keep this general, so let's boil this back down to a pure software engineering problem. It's clear that a lot of communication may take place between APIs, and a lot of the time we don't know for sure what communication will be necessary until runtime. In the API examples above, there's a strong sense that the window should "own" the renderer, but let's assume there is no clear ownership between our two concepts.

Fragments of Solutions

To this day, I have never found a completely elegant way to encapsulate all these messy unknowns, but I know of a few mechanisms that can help contain the mess a bit.

Events
First of all, we can rein in a lot of the complexity by taking an event-driven approach to the problem. When ImplA does something ImplB needs to react/respond to, it can send out an event, which ImplB can handle internally. One problem with this, however, is that we may also need to include event info, and we may need to pass data which is represented differently from API to API.

Opaque Pointers
We can fight API micromanagement with opaque pointers. Instead of having to pollute the implementations with tons of methods like GetDataFormattedForSpecificImplB(), we can create a struct

struct DataForImplB
{
    int data, neededBy, implB;
};

or

typedef void* DataForImplB;

and then have a single virtual function

virtual DataForImplB* GetDataForImplB() = 0;

that each A impl provides its own override of. The problem now is that each B impl has to know what the underlying type is so it can cast it back and make use of it. I find myself having to create enums of all the implementations to pass around and then use select statements to branch depending on which implementation the pointer was received from. This all feels very messy, very boilerplate, and not DRY. Furthermore, the amount of work needed grows exponentially with each added implementation.

Question

There are enough ugly APIs and inconsistencies out there that I just know there has to be some design pattern to coax these jagged teeth into interlocking. If you see a pattern hiding in this problem, what is it? If not, will I have to throw modularity out the window and consign myself to a life writing endless boilerplate and big, monolithic, tightly-coupled classes?

Hopefully I've explained the problem clearly enough. If anyone has found themselves in a similar situation, how did you solve it?

Typescript does not recognize that the generic parameters match

In the following code typescript complains that the argument does not match the called function.

In general that is ok, but in this case the type of emailType and args are bound to the same generic type T so it should not error. As you can see in the following lines, if you fix the type T to some concrete value, e.g. "Foo" typescript correctly recognizes that the types match.

  • Is there either a way to tell typescript that the types match (without a as any assertion)?
  • Do you know of a better pattern to this problem? I really like it, because it makes calling sendMail convenient as you have intellisense for the emailType, which makes it easy to see which emails are available, and then intellisense for the required data to send the email.
const mails = {
  Foo: (args: { foo: string }) => "",
  Bar: (args: { bar: string }) => "",
}

function sendMail<T extends keyof typeof mails>(emailType: T, args: Parameters<typeof mails[T]>[0]){
  mails[emailType](args) // ERROR: Argument of type '{ foo: string; } | { bar: string; }' is not assignable to parameter of type '{ foo: string; } & { bar: string; }'
  mails[emailType as "Foo"](args as Parameters<typeof mails["Foo"]>[0]) // works
  mails[emailType as "Bar"](args as Parameters<typeof mails["Bar"]>[0]) // works
}

vendredi 14 janvier 2022

How to read a block of pattern file?

I have some pattern files that I like to read just a few parts of them.

Exemple: text.txt

Recipe: 
'name' 
Ingredients:
Item 1
Item 2
Item N... 
How to prepare:
Item 1
Item 2
Item N... 

I'd like to get only the ingredients.

How to represent/store/handle data when when there are multiple input and one output in backend and frontend?

I am building an E-commerce type application where I need to show the price of an item based on multiple option selection like:

packet size concentration Color Price
250ml 100 white 100
250ml 100 Gray 90
250ml 50 white 80
250ml 50 Gray 70
100ml 100 white 50
100ml 100 Gray 40
100ml 50 white 30
100ml 50 Gray 20

So Options would look something like this:
PackSize: | 250ml | 100ml |
Concentration: | 100 | 50 |
Color: | white | Gray |

Based on user selection of options from all three category, I intend to get the final price.

How should I store this data in RDBMS, as currently all possible combination is stored with a unique id and its price, but how should I share this data to the frontend for the selection of option through the checkbox.

I could think of a nested Map with pack size as a key like:
Map<packSize,Map<concentration,Map<color,Price>>> and refresh all options as an option get selected and so on.

But it doesn't feel right, as if the user selects the options in any other order like going from child to parent (color->concentration->packsize) rather than the parent to child (packSize->concentration->color) i am not sure how to track each selection and show the corresponding price.

Is there any better approach, can Hashing(taking all three inputs along with unique id and creating a one-to-one mapping with hash and price) work here? What is the best convention?

A nudge to the right path would be very helpful, else i could end up doing a lot of unnecessary, complex, and inefficient coding.

When I should split class into struct and struct builder class?

For example, we have next class.

class Request{
public:
  RequestHeader header;
  String body;

  Request(const RequestHeader& header, const String& body); 
  Request(const String& json); 
};

Some articles recommend split Request entity and Request build logic. For example, next.

struct Request{ //RequestDTO?
  RequestHeader header;
  String body;
};

class RequestBuilder{
public:
  static Request build(const RequestHeader& header, const String& body);
  static Request build(const String& json);
};

When we should use this recommendation? At first sight, it is useless complex. Constructor are normal part of a class. Why we should avoid this?

Why is interface used as a type in the Laravel Repository Pattern?

I did a investigation on the Laravel Repository Pattern in order to isolate somehow custom queries and I've also tried it on my internal project.

I'm very satisfied how it works. It's definitely good practice of writing custom queries.

One thing are confusing me about the implementation. This is the way of dependency injection in the controllers.

Here is how the suggested best practice of it looks like:

class UsersController extends Controller
{
    private $userRepository;

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

    public function index() {
        $users = $this->userRepository->all();

        return view('users.index', [
            'users' => $users
        ]);
    }
}

What I don't like here is that parameter type in the constructor. I guess it shouldn't be interface.

In the service provider this interface is connected with only one class (here it is UserRepository) which is implementing that interface and it works with this solution.

I think that it's better solution to use UserRepository here as a type of parameter insted of interface. What do you think about this?

jeudi 13 janvier 2022

How to design an object-database relation in Rust?

I'm creating a Rust web application and I will need popular data types like User, Role, Privilege, etc. All of them needs to be stored in the database so for each model I need to implement an SQL query generation logic. Now I'm thinking where to put that logic in the code.

I have some ideas but all of them seem to have drawbacks.

  1. Use e.g. Create Trait. Which then I would implement for each data type.

    trait Create {
        fn create(&self, client: &DbClient) -> Result<(), Error>;  
    }
    

    This is ok but I would like to put all the SQL logic inside a dedicated module, not tie it to data model. Also, I would have to pass &DbClient every time.

  2. Create dedicated module e.g. Storage which would have &DbClient inside and expose an API for each concrete data type.

    struct Storage {
        client: &DbClient,
    }
    
    impl Storage {
         async fn create_user(&self, &User) -> Result<(), Error> { }
         async fn create_role(&self, &Role) -> Result<(), Error> { }
    }
    

    This one will result in a single struct with so many methods which I doubt is an elegant solution.

  3. Create StorageUser, StorageRole, etc. but this time I would have some many generic objects to pass and it also doesn't look good for me.

    struct StorageUser {
        client: &DbClient,
    }
    
    impl StorageUser {
         async fn create(&self, &User) -> Result<(), Error> { }
    }
    
    struct StorageRole {
        client: &DbClient,
    }
    
    impl StorageRole {
         async fn create(&self, &Role) -> Result<(), Error> { }
    }
    

How would you approach it? I'm aware this is highly opinion-based question.

How to handle different logic in an if block with out duplicating code?

What is the best way to handle an if block that does something but the conditionals are different?

Lets say I have this function in JavaScript.

const updateText1 = function (id) {
    const selector = $(id);
    selector.on('change', function () {
        const text = selector.val();
        if(seen[text]) {
            // update some fields here
        } else {
            //more stuff here
        }
    })
}

But then I need to do the same thing inside the if statement but with a different or similar conditional

const updateText2 = function (id) {
    const selector = $(id);
    selector.on('change', function () {
        const text = selector.val();
        if(seen[text] || text.trim() === '') {
            // update some fields here
        } else {
            //more stuff here
        }
    })
}

then else functions are used like this

obj1 = {
  test: function() { updateText1(this.id) }
}

obj2 = {
  test: function() { updateText2(this.id) }
}

I know I could just combine the logic together but, since both objects that this function is attached to are handling slightly different things I'm trying to keep my code DRY and not repeat the if body multiple times. I've tried injecting the logic like this

obj2 = {
  // logic code here
  test: function() { updateText2(this.id, logic) }
}

But this results in the code not updating since the value is gotten via the Jquerry on change. Am I over thinking this, Should I just combine the logic, or is there a better way to organize and handle this?

JSON deserialization for multiple messages design pattern C#?

I have a use case in which a .net app is running in the background and listening for Kafka messages. I will receive various payloads/messages from Kafka. Each payload has different structure and contains different items in it. For each payload, we must deserialize it into its own entity(not always be one to one mapping, there can be some mapping logic for payload to the entity in some cases), each of which has its own table in the database. So, after deserialization, these entities must be saved in a database and also sent to another Kafka topic.

Broadly I have divided this whole flow into 3 parts maintaining SRP. One will be deserialization, second will be database save and third will be Kafka.

I am currently implementing deserialization as shown below:

First payload examples:

{
   "type":"fuel",
   "data":{
      "fueltype":"petrol",
      "mileage":23.76,
      "tankcapacity":37
   }
}

{
   "type":"engine",
   "data":{
      "enginetype":"K series",
      "maxpower":88.50,
      "displacement":1197
   }
}

So these messages are differentiated using the type

For code I thought of using individual parsers for each type

public interface IJsonParser
    {
        Payload Parse(dynamic data);
    }

 public class FuelParser : IJsonParser
    {
        public Payload Parse(dynamic payload)
        {
            Fuel f = new Fuel();
            f.Mileage = (float)payload.data.mileage;
            return f;
        }
    }

    public class EngineParser : IJsonParser
    {
        public Payload Parse(dynamic data)
        {
            Engine e = new Engine();
            return e;
        }
    }



public class Payload
    {
        public int Id { get; set; }
    }

 public class Fuel : Payload
    {
        public string FuelType { get; set; }
        public float Mileage { get; set; }
        public int TankCapacity { get; set; }
    }

 public class Engine : Payload
    {
        public string EngineType { get; set; }
        public float MaxPower { get; set; }
        public int Displacement { get; set; }
    }
 


 public static class JsonParserFactory
    {
        public static IJsonParser GetJsonParser(string type)
        {
            switch (type)
            {
                case "fuel":
                    return new FuelParser();
                case "engine":
                    return new EngineParser();
                default:
                    return null;
            }
        }
    }

string message = "{\r\n\t\"type\": \"fuel\",\r\n\t\"data\":\r\n\t\t{\r\n\t\t\t\"fueltype\": \"petrol\",\r\n\t\t\t\"mileage\": 23.76,\r\n\t\t\t\"tankcapacity\": 37\r\n\t\t}\r\n}";
            dynamic data = JsonConvert.DeserializeObject<object>(message);

            IJsonParser parser = JsonParserFactory.GetJsonParser(data.type.ToString());
            var model = parser.Parse(data);// This model will then be saved in DB as well as sent to another Kafka topic which is the 2nd and 3rd part of the flow.

So based on the type I have create a Factory which is creating the individual parsers.

I just wanted the suggestion if this is a good design. My only concern is in the future there will be multiple types of payloads coming which will then increase the number of parsers as we go along.

Any suggestions?