vendredi 31 mars 2023

how can i preform sorted pagination when need to fetch data from multiple micro services?

lets for example look at this 2 micro service :


Micro service that handle cars orders:

Table:

  • orders [order_id, car_id, date,...]

Api: /GET /orders


Micro service that handle cars data:

  • cars [car_id, color ,price,...]

Api: /GET /cars


Now the problem is :

if i want at my UI app to show the merged data paginate and sorted ?

[order_id ,car_id ,color ,date ,price .....]

for example :

First scenario : first 500 rows , sorted by order_id

  • need to fetch data from orders api
  • then take the car_id and enrich the data from cars api

Second scenario : first 500 rows , sorted by car_id

  • need to fetch data from cars api
  • then take the order_id and enrich the data from orders api

i implement the code the fetching data this why:

const sortByOrder=(sortedBy)=>{
    return ORDER_FIELDS.includes(sortedBy) 
}
const sortByOrCars=(sortedBy)=>{
    return ORDER_FIELDS.includes(sortedBy) 
}
async function fetchOrderData(sortedBy,batchSize){
    
    if(sortByOrder(sortedBy)){
        const orderData = await fetchOrderData(sortedBy,batchSize);
        const orderIds = orderData.map(order=>order.id);
        const cars = await fetchCars(orderIds);
        return joinOrderAndCars(orderData,cars);
    }
    
    if(sortByOrCars(sortedBy)){
        const caersData = await fetchCarsData(sortedBy,batchSize);
        const carsIds = carsData.map(car=>car.id);
        const orders = await fetchOrders(carsIds);
        return joinOrderAndCars(orders,carsData);
    }
}

this is the naive approach it hard to maintain

  • for example to enrich data from third api

looking for a more genreal solution , or pattern and to learn from others that and encounter this issue

What would be the logic or tools to correctly handle data (parsing,creating,validating,cleaning...) in Javascript/Typescript?

I have a general question here, but after several days searching, I don't find the information I'm looking for.

I have some development skills (PHP, Javascript, React, HTML, etc) that I've picked up over time and self-taught. But I've reached a point where I lack the logic or skills to achieve what I need.

The backbone of the (music) app i'm working on is JSPF datas, which is a standard JSON format for music playlists. Here is an example of a JSPF dataset on the official website.

I'm looking for information to create some sort of toolkit for manipulating those datasets through my application - whether it's loading it, validating it, manipulating it, cleaning it up before it is saved in the DB, etc.

The idea is to use this toolkit as a module across the entire application (backend and frontend), so it needs to be perfectly designed because the whole app will rely on it - data will, among others, be processed by users; so validation is important.

I would like to create something (a class? a model? an interface ? Is there a name for this concept ?) that allows me to manage this data.

In the case of a playlist, I would need, for example

  • methods to manage the tracks (add/remove/empty/reindex...)
  • methods to import (fill) or export data in JSON
  • methods to validate (for a user form, for example) or clean (before saving in the DB) this data.

a draft of this could be something like

class Playlist = {
  //fill the object based on a JSON string
  public fromJson(json: string){}
  
  //converts the object to a JSON string
  public toJson(): string {}
  
  //compare datas to a schema, check if valid, trace errors...
  public validate(schema){}
  
  //clean data (strip what's not good) eg. before storing it in DB
  public sanitize(){}
  
  //some methods for tracks
  public addTracks(tracks:JSPFTrack[]){}
  public removeTracks(tracks:JSPFTrack[]){}
  public reindexTracks(tracks:JSPFTrack[],startNum:number){}
  public clearTracks(){}
  
  //....
}

I started looking at TypeScript, to, among other things, define strong types, but it's more complicated than I thought. I get a little confused between types, interfaces, classes, and most importantly, I realized that TypeScript is useful at compile time, not at run time.

I looked at the validation side, but there are a ton of recommended modules, like yup, zod - is there one that everybody agrees on ?

I also looked closely at a module that seems intuitive enough for me but is quite new and doesn't seem to be widely used - so I'm hesitant to rely on that even if it seems to fit my needs: Object Model.

What I'm looking for is probably... what many developers do design all the time. I just lack the resources to name those concepts and find good documentation on it.

Is there good ressources, or a clear example/tutorial that explains how to manage a simple dataset from start to finish like I would like to do, so I could improve my understanding on all this ?

Thank you very much!!!

Here is the current state of my TypeScript types designed according to this dataset.

Managing DTO and BO in a project calling an API

I'm working on a backend layer of a webapp in Java which is essentially an RESTful API (using Spring Boot). Within my backend I'm calling another API (essentially my database) to retrieve and combine data. Current my workflow for handling a GET request looks the following

  1. Receive request within my API
  2. Call the other API (database), and map it's JSON response to a DTO
  3. Convert DTO to BO to perform logic on it
  4. Return BO via spring boot (which turns its fields into a JSON body and returns this)

My question is
Following the DTO logic, would it be more correct to turn my BO into a second DTO, containing the data to be transferred (as I understand it is discouraged to transfer data with a BO)

Essentially this would add a step to my list above, between 3 and 4:
---> ...
---> 3.5. Convert BO to new DTO
---> 4. Return DTO via sprint boot

The reason I haven't done this is because it seems a bit intensive to convert objects twice, however I see the benefits to the DTO / BO pattern.

jeudi 30 mars 2023

Is good Idea Apply a generic common functions to all services using interfaces an abstracts?

I am starting a new project using Spring Boot 3. We are still at an early stage of the project and still defining things. so, being said that. Here is my question:

The problem I want to solve: the service layer which is meant to handle all the business logic shares common functions among the entities, eg: CRUD functions and others.

Proposal: Create a Generic interface with all common functions. then: creates an Abstract class that will implement this interface and override; why an Abstract because I want to prevent the paint of adding new functions to the parent interface and going through all the implemented cases.

Here is an example I implemented:

// Project stucture.
main-project
|-src
   |--main
       |-java
          |-com.project
               |-entities
               |-repositories
               |-service
               |    |-implementation    
               |-rest

now We all know what is inside entities, repositories and rest package, here is my service package implementation:

BaseCommonOperationInterface

public interface BaseCommonOperationInterface<E, V> {

  E createItemOf(V requestDto);
  E updateItemfrom(final Long identifier, V requestDto);
  void deleteItem(final Long identifier);
  Optional<E> findSingleRecordByIdentifier(Long skillDicCategoryId);
  List<E> listAllItems();
//more common function...
}

BusinessBaseAbstract

puiblic abstract class BusinessBaseAbstract<E, V> implements BaseCommonOperationInterface<E, V>{
//Here override all methods from interface...
 @Override
  public List<E> listAllItems() {
    return Collections.emptyList();
  }
//...
}

DictionaryService

public interface DictionaryService implement BaseCommonOperationInterface<DictionaryEntity, DictionaryrequestDto>{}

DictionaryServiveImpl


@RequieredArgConstructor
@Service
public class DictionaryServiveImpl extends BusinessBaseAbstract<DictionaryEntity, DictionaryrequestDto> implements DictionaryService{
private final DictionaryRepository dictionaryRepository;

//I can override eather single common function or all of them
@override
public List<DictionaryEntity> listAllItems(){
 return dictionaryRepository.findAll()
}
// all the methods I need overrided here...
}

DictionaryController

@RestController
public class DictionaryController{

private final DictionaryService service;

@GetMapping("/dictionary")
public List<DictionarEntity> getAllofThem(){
return service.listAllItems();
}
//Here rest of implementations...
}

Why no call the DictionaryRepository from the controller beacause we want to keep the Rest Controller clean as much as possible and delegate all business logic to Service package.

Does this pattern make sense? are there advantages and disavantages? are there others pattern that I can apply to abstract common function?

MVVM and tkinter

Is there a way to implement the Model-View-ViewModel pattern in Python 3, if my interface is made with tkinter? I am especially referring to the missing binding mechanism MVVM requires; is there a library to provide it or a workaround to mimic it? Or any example projects I could get inspired by? (The only tutorial I found on this topic used PyQt, and I do not wish to rewrite my whole interface).

How would I use the Factory method if I only have 1 class?

Let me explain: I have a concrete GUI class for my game:

public class GameGUI
{
    public void addElement(GameGuiElement element) { ... }
}

and classes that implement the GameGuiElement interface, such as Button and TextBox.

Until today, I always designed my GUIs like this:

public class SimpleGUI extends GameGUI
{
    public SimpleGUI()
    {
        super("Simple GUI Title");

        addElement(new Button("Click Here"));
    }
}


//somewhere in another class
new SimpleGUI().display(player);

But recently I read that it's bad practice to use inheritance only for configuration, so I did some research and found the Factory pattern; But how would I apply it if I only have the GameGUI class? I thought of creating this interface:

public interface GameGUIFactory
{
    GameGUI createFirstGUI();
    GameGUI createSecondGUI();
}

but my instinct immediately rejects that because configuring even 1 GUI takes a lot of code.. and also doesn't it blatantly violate SRP by being responsible for creating more than 1 GUI?

Best way to extend Unity3d Rigidbody?

I am designing a physics class library for Unity3d and would love to be able to hook and inject functionality into Unity3d's Rigidbody class, but it's my understanding that there is no way to do this directly while still being able to target all platforms.

I thought the next best thing might be to create a new class that inherits directly from Rigidbody. However, it looks like unity has prevented this from occurring in anything but the UnityEngine namespace by requiring the internal sealed ExtensionOfNativeClassAttribute on anything that inherits native classes. Furthermore, Unity does not searialize inherited classes well.

So, in review, I'm not able to hook into Rigidbody directly (Please correct me if this is wrong!), and I'm not able to inhert from Rigidbody directly (Please correct me if this is wrong!). I think the next best option is to:

  1. Create a new Monobehavior, let's say it's called ModRigidbody, which makes a parellel implementation of all of Rigidbody's members. This class does not actually inherit from Rigidbody, but merely has members with all the same names / signatures as Rigidbody.
  2. On ModRigidbody add the attribute [RequireComponent(typeof(Rigidbody))]. Now I can add functionality to some ModRigidbody's members as I see fit, and have other members simply 'pass through' to transform.GetComponent<Rigidbody>().
  3. Have any end users (programmers) change all of their references to Rigidbody over to ModRigidbody.

To me this feels quite sloppy. Is there a way to mod the functionality of Rigidbody so that future users of this library will not have to change all of their Rigidbody over to ModRigidbody?

Design Pattern for I/O and Data Transformations in High-Level Block Diagrams

I am working on a application that is designed as a high-level block diagram, similar to Simulink or LabView. Unlike a typical Simulink / LabView program, it does a lot of I/O and data transformations. As this situation is not completely uncommon, I suspect that various solutions may already exist.

In order to find the most suitable approach, I am seeking suggestions for a design pattern in C++. Would anyone be willing to share their thoughts and experiences, perhaps with a code example?

The following is my own draft code. Both input and output is represented as an anyobject. A block may have an unlimited number of processor functions for different types. They are indexed in a map object, which connects the actual input type to the right processor function.

Looks like it does its job, but can it be made simpler, more elegant, and easier to read? I am particularly unhappy with all the casts that I had to make.


class Block {
protected:
    map<type_index, any (Block::*)(any)> processors;

public:
    virtual any process(any in) {
        auto it = processors.find(type_index(in.type()));
        return (this->*it->second)(in);
    }
};

class MultiplyBlock : public Block {
    any multiply(any in_) {
        auto in = std::any_cast<vector<float>>(in_);
        float product{1};
        for (auto f : in) {
            product *= f;
        }
        return product;
    }

public:
    MultiplyBlock() {
        processors.emplace(
                typeid(vector<float>),
                static_cast<any (Block::*)(any)>(&MultiplyBlock::multiply)
        );
    }
};

int main() {
    MultiplyBlock m;
    cout << any_cast<float>(m.process(vector<float>{1, 2, 3})) << endl;
}

Unit testing - scoping and best practice

I'm implementing a API project on .net core, the solution follows simple three layer architecture as described below.

  1. Orders.Api --> Function App that implements controllers, security, exception handler, etc.
  2. Orders.Service --> Class library that implements all business logic (validations, application flow, models, etc)
  3. Orders.Repository --> Class library that implements repos to INFRA like database, service bus, etc.

One of Api (POST Orders) is implemented as shown below.

    public class OrdersController
    {
        private readonly IHttpTriggerHelper _httpTriggerHelper;
        private readonly IOrderService _OrderService;        

        public OrdersController(IHttpTriggerHelper httpTriggerHelper, IOrderService OrderService)
        {
            _httpTriggerHelper = httpTriggerHelper;
            _OrderService = OrderService;
        }

        [Function("CreateOrder")]
        public async Task<HttpResponseData> CreateOrder([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "dealers/{dealerId:int}/Orders")] HttpRequestData req, int dealerId)
        {               
            var OrderRequest = await _httpTriggerHelper.GetRequestModel<OrderData>(req, cancellationToken);                                    
            var userId = _httpTriggerHelper.GetContextData(req, "User.Id") ?? string.Empty;
            var OrderResponse = await _OrderService.SendOrderRequest(dealerId, userId, OrderRequest, cancellationToken);

            return await _httpTriggerHelper.GetHttpResponse(OrderResponse, HttpStatusCode.Accepted, req, cancellationToken);
        }
    }

public class OrderService : IOrderService
    {
        private readonly IOrderRepository _orderRepository;
        private readonly IValidationManager _validator;

        public OrderService(IOrderRepository orderRepository, IValidationManager validator)
        {
            _orderRepository = orderRepository;
            _validator = validator;
        }

        public async Task<OrderResponse> SendOrderRequest(int dealerId, string userId, OrderData? orderData)
        {
            _validator.ValidateOrderRequest(orderData);

            orderData.EnrichWithRequestContextData(dealerId, userId);

            await _orderRepository.SendOrderRequest(orderData);

            return new OrderResponse { CorrelationId = orderData.CorrelationId, Status = orderData.Status };
        }
    }

I'm struggling to scope the contract and unit testing for OrderService.SendOrderRequest.

Here is my first approach on unit testing scope.

  1. OrderService must validate the orderData (Ensure validate method is called)
  2. orderData is enriched with request context data.
  3. orderData is stored with orderRepository.
  4. OrderResponse is built as expected.

Here is my second approach on unit testing scope.

  1. OrderService must validate the orderData (Ensure validate method is called)
  2. OrderService must throw exception when the orderData is not valid.
  3. orderData is enriched with request context data.
  4. orderData is stored with orderRepository.
  5. OrderService must throw exception when the failed to store the orderData.
  6. OrderResponse is built as expected.

The second approach seems to make the OrderService more robust. The question I've is on the points 2 and 5.

  1. Is it a general/good practice to unit test all possible exceptions thrown from dependencies?
  2. If so, this expectation is also applicable to upper layers (ex; Api controller)?

Please share if any other better approaches also.

mercredi 29 mars 2023

unable to fix a content div

I have created a register blade page using tailwind it's looking good but when I am trying to scroll it from the left side my main div is hitting the sidebar and changing the color of the side nav bar from dark to white because my main div is white I have created a form inside this div here is my code.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Dashboard</title>
    <meta name="author" content="name">
    <meta name="description" content="description here">
    <meta name="keywords" content="keywords,here">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
    <link rel="stylesheet" href="https://unpkg.com/tailwindcss@2.2.19/dist/tailwind.min.css"/> <!--Replace with your tailwind.css once created-->
    <link href="https://afeld.github.io/emoji-css/emoji.css" rel="stylesheet"> <!--Totally optional :) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.min.js" integrity="sha256-xKeoJ50pzbUGkpQxDYHD7o7hxe0LaOGeguUidbq6vis=" crossorigin="anonymous"></script>

</head>

<body class="bg-gray-800 font-sans leading-normal tracking-normal mt-12 ">

<header>
    <!--Nav-->
    <nav aria-label="menu nav" class="bg-gray-800 pt-2 md:pt-1 pb-1 px-1 mt-0 h-auto fixed w-full z-20 top-0">

<div class="flex flex-wrap items-center">
    <div class="flex flex-shrink md:w-1/3 justify-center md:justify-start text-white">
        <a href="#" aria-label="Home">
            <span class="text-xl pl-2"><i class="em em-grinning"></i></span>
        </a>
    </div>

    <div class="flex flex-1 md:w-1/3 justify-center md:justify-start text-white px-2">
        <span class="relative w-full">
            <input aria-label="search" type="search" id="search" placeholder="Search" class="w-full bg-gray-900 text-white transition border border-transparent focus:outline-none focus:border-gray-400 rounded-lg py-3 px-2 pl-10 appearance-none leading-normal">
            <div class="absolute search-icon" style="top: 1rem; left: .8rem;">
                <svg class="fill-current pointer-events-none text-white w-4 h-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                    <path d="M12.9 14.32a8 8 0 1 1 1.41-1.41l5.35 5.33-1.42 1.42-5.33-5.34zM8 14A6 6 0 1 0 8 2a6 6 0 0 0 0 12z"></path>
                </svg>
            </div>
        </span>
    </div>

    <div class="flex w-full pt-2 content-center justify-between md:w-1/3 md:justify-end">
        <ul class="list-reset flex justify-between flex-1 md:flex-none items-center">
            
            <li class="flex-1 md:flex-none md:mr-3">
                <a class="inline-block text-gray-400 no-underline hover:text-gray-200 hover:text-underline py-2 px-4" href="">Register a new candidate</a>
            </li>
            <li class="flex-1 md:flex-none md:mr-3">
                <div class="relative inline-block">
                    <button onclick="toggleDD('myDropdown')" class="drop-button text-white py-2 px-2"> <span class="pr-2"><i class="em em-robot_face"></i></span> Hi, User <svg class="h-3 fill-current inline" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                        <path d="M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z" /></svg></button>
                    <div id="myDropdown" class="dropdownlist absolute bg-gray-800 text-white right-0 mt-3 p-3 overflow-auto z-30 invisible">
                        <input type="text" class="drop-search p-2 text-gray-600" placeholder="Search.." id="myInput" onkeyup="filterDD('myDropdown','myInput')">
                        <a href="#" class="p-2 hover:bg-gray-800 text-white text-sm no-underline hover:no-underline block"><i class="fa fa-user fa-fw"></i> Profile</a>
                        <a href="#" class="p-2 hover:bg-gray-800 text-white text-sm no-underline hover:no-underline block"><i class="fa fa-cog fa-fw"></i> Settings</a>
                        <div class="border border-gray-800"></div>
                        <a href="" class="p-2 hover:bg-gray-800 text-white text-sm no-underline hover:no-underline block"><i class="fas fa-sign-out-alt fa-fw"></i> Log Out</a>
                    </div>
                </div>
            </li>
        </ul>
    </div>
</div>

</nav>

</header>
 
<main>

    <div class="flex flex-col md:flex-row">
        <nav aria-label="alternative nav">
            <div class="bg-gray-800 shadow-xl h-20 fixed bottom-0 mt-12 md:relative md:h-screen z-10 w-full md:w-48 content-center">

                <div class="md:mt-12 md:w-48 md:fixed md:left-0 md:top-0 content-center md:content-start text-left justify-between">
                    <ul class="list-reset flex flex-row md:flex-col pt-3 md:py-3 px-1 md:px-2 text-center md:text-left">
                        <li class="mr-3 flex-1">
                            <a href="" class="block py-1 md:py-3 pl-1 align-middle text-white no-underline hover:text-white border-b-2 border-gray-800 hover:border-pink-500">
                                <i class="fas fa-tasks pr-0 md:pr-3"></i><span class="pb-1 md:pb-0 text-xs md:text-base text-gray-400 md:text-gray-200 block md:inline-block">Dashboard</span>
                            </a>
                        </li>
                        <li class="mr-3 flex-1">
                            <a href="#" class="block py-1 md:py-3 pl-1 align-middle text-white no-underline hover:text-white border-b-2 border-gray-800 hover:border-purple-500">
                                <i class="fa fa-envelope pr-0 md:pr-3"></i><span class="pb-1 md:pb-0 text-xs md:text-base text-gray-400 md:text-gray-200 block md:inline-block">Messages</span>
                            </a>
                        </li>
                        <li class="mr-3 flex-1">
                            <a href="#" class="block py-1 md:py-3 pl-1 align-middle text-white no-underline hover:text-white border-b-2 border-gray-800 hover:border-pink-500">
                                <i class="fas fa-chart-area pr-0 md:pr-3"></i><span class="pb-1 md:pb-0 text-xs md:text-base text-gray-400 md:text-white block md:inline-block">Analytics</span>
                            </a>
                        </li>
                        <li class="mr-3 flex-1">
                            <a href="" class="block py-1 md:py-3 pl-0 md:pl-1 align-middle text-white no-underline hover:text-white border-b-2 border-gray-800 hover:border-red-500">
                                <i class="fa fa-wallet pr-0 md:pr-3"></i><span class="pb-1 md:pb-0 text-xs md:text-base text-gray-400 md:text-gray-200 block md:inline-block">Students Data</span>
                            </a>
                        </li>
                    </ul>
                </div>


            </div>
        </nav>
        <section>
            <div class=" flex-1 bg-gray-100 mt-12  pb-24 pt-6 md:pb-5  w-screen rounded-lg overflow-x-auto ">
             <!-- form -->
<div class="w-full md:w-1/2 md:max-w-full mx-auto bg-white rounded-lg ">
  <div class="p-6 border border-gray-300 sm:rounded-md">
  <form action="" method="post" enctype="multipart/form-data">
  @if(Session::has('success'))
          <div></div>
          @endif
          @if(Session::has('fail'))
          <div></div>
          @endif
      @csrf
      <!-- <pre>
        @php
        print_r($errors->all());
        @endphp
     </pre> -->
      <label class="block mb-6">
        <span class="text-gray-700">Name</span>
        <input
          required
          name="name"
          type="text"
          class="
            block
            w-full
            mt-1
            border-gray-300
            rounded-md
            shadow-sm
            focus:border-indigo-300
            focus:ring
            focus:ring-indigo-200
            focus:ring-opacity-50
          "
          placeholder="Joe Bloggs"
        />
      </label>
      <label class="block mb-6">
        <span class="text-gray-700">Email address</span>
        <input
          required
          name="email"
          type="email"
          class="
            block
            w-full
            mt-1
            border-gray-300
            rounded-md
            shadow-sm
            focus:border-indigo-300
            focus:ring
            focus:ring-indigo-200
            focus:ring-opacity-50
          "
          placeholder="joe.bloggs@example.com"
        />
      </label>
      <label class="block mb-6">
        <span class="text-gray-700">Phone no.</span>
        <input
          required
          name="phone_number"
          type="text"
          class="
            block
            w-full
            mt-1
            border-gray-300
            rounded-md
            shadow-sm
            focus:border-indigo-300
            focus:ring
            focus:ring-indigo-200
            focus:ring-opacity-50
          "
          placeholder="+91..."
        />
      </label>
      <label class="block mb-6">
        <span class="text-gray-700">Address</span>
        <input
          required
          name="address"
          type="text"
          class="
            block
            w-full
            mt-1
            border-gray-300
            rounded-md
            shadow-sm
            focus:border-indigo-300
            focus:ring
            focus:ring-indigo-200
            focus:ring-opacity-50
          "
          placeholder=""
        />
      </label>
      <label class="block mb-6">
        <span class="text-gray-700">Select course</span>
        <select
          required
          name="select_course"
          class="
            block
            w-full
            mt-1
            border-gray-300
            rounded-md
            shadow-sm
            focus:border-indigo-300
            focus:ring
            focus:ring-indigo-200
            focus:ring-opacity-50
          "
        >
          <option></option>
          <option value="" selected="selected" disabled="disabled">-- select one --</option>
     <option value="Front-end">Front-end</option>
     <option value="Back-end">Back-end</option>
     <option value="Full stack">Full stack</option>
     <option value="UI design">UI design</option>
     <option value="UX design">UX design</option>
        </select>
      </label>
        

      <label class="block mb-6">
        <span class="text-gray-700">Highest Qualification</span>
        <select
          required
          name="highest_qualification"
          class="
            block
            w-full
            mt-1
            border-gray-300
            rounded-md
            shadow-sm
            focus:border-indigo-300
            focus:ring
            focus:ring-indigo-200
            focus:ring-opacity-50
          "
        >
          <option></option>
          <option value="" selected="selected" disabled="disabled">-- select one --</option>
     <option value="Primary education">Primary education</option>
     <option value="Secondary education">Secondary education or high school</option>
     <option value="Bachelor's degree">Bachelor's degree</option>
     <option value="Master's degree">Master's degree</option>
     <option value="Doctorate or higher">Doctorate or higher</option>
        </select>
      </label>
      <label class="block mb-6">
        <span class="text-gray-700">Your CV</span>
        <input
          required
          name="cv_file"
          type="file"
          class="
            block
            w-full
            mt-1
            focus:border-indigo-300
            focus:ring
            focus:ring-indigo-200
            focus:ring-opacity-50
          "
        />
      </label>
      <div class="mb-6">
        <button
          type="submit"
          class="
            h-10
            px-5
            text-indigo-100
            bg-indigo-700
            rounded-lg
            transition-colors
            duration-150
            focus:shadow-outline
            hover:bg-indigo-800
          "
        >
          Submit
        </button>
      </div>
     
          </div>
        </div>
      </div>
      
      <div>
        <div class="mt-2 text-gray-700 text-right text-xs">
          by
          <a href="https://herotofu.com" class="hover:underline" target="_blank"
            >HeroTofu</a
          >
        </div>
      </div>
    </form>
  </div>
</div>      
            </div>
        </section>
    </div>
</main>
<script>
    /*Toggle dropdown list*/
    function toggleDD(myDropMenu) {
        document.getElementById(myDropMenu).classList.toggle("invisible");
    }
    /*Filter dropdown options*/
    function filterDD(myDropMenu, myDropMenuSearch) {
        var input, filter, ul, li, a, i;
        input = document.getElementById(myDropMenuSearch);
        filter = input.value.toUpperCase();
        div = document.getElementById(myDropMenu);
        a = div.getElementsByTagName("a");
        for (i = 0; i < a.length; i++) {
            if (a[i].innerHTML.toUpperCase().indexOf(filter) > -1) {
                a[i].style.display = "";
            } else {
                a[i].style.display = "none";
            }
        }
    }
    // Close the dropdown menu if the user clicks outside of it
    window.onclick = function(event) {
        if (!event.target.matches('.drop-button') && !event.target.matches('.drop-search')) {
            var dropdowns = document.getElementsByClassName("dropdownlist");
            for (var i = 0; i < dropdowns.length; i++) {
                var openDropdown = dropdowns[i];
                if (!openDropdown.classList.contains('invisible')) {
                    openDropdown.classList.add('invisible');
                }
            }
        }
    }
</script>
</body>
</html>

How to assign a specific icon to a specific weapon?

Each weapon in the game does have an icon that will be shown on screen when the weapon is picked up.

The weapons are implement as different classes all based on the same base abstract class.

What I'm trying to sketch up is how to define such relationship in the editor, specifically, I want to be able to change a weapon's icon by drag'n'drop a texture on some object in the inspector.

What I'm not looking for:

  • the use of enumerations to declare such relationship
  • not declaring a direct reference to a texture asset, i.e. a path.

How would you achieve that?

What is the best practice to save chat messages?

I would like to ask what would be the best practice regarding saving chat messages, should I save them in the same database where I store user data, or use separate one?

To give a little bit more detail I am making two apps, web(user app) and desktop(admin app). They are communicating with database trough REST API. Web app will have chat functionality and I was thinking maybe use separate database that will directly communicate with the app.

All advice is appreciated.

mardi 28 mars 2023

why Add a CSS style inside a PHP code comment

why add a css code inside php comment like this :

/**
 * Contains various information about errors thrown by libxml. The error codes
 * are described within the official
 * xmlError API documentation.
 * @link https://php.net/manual/en/class.libxmlerror.php
 */
class LibXMLError
{
    /**
     * <p style="margin-top:0;">   //  <-----------  here
     * the severity of the error (one of the following constants:
     * <b><code>LIBXML_ERR_WARNING</code></b>,   //  <-----------  here
     * <b><code>LIBXML_ERR_ERROR</code></b> or   //  <-----------  here
     * <b><code>LIBXML_ERR_FATAL</code></b>)     //  <-----------  here
     * </p>
     * @var int
     */
    public int $level;

DynamoDB Single-Table Design for Advanced Set of Access Patterns

I've been working on new projects and experimenting with DynamoDB single-table design and recently I've encountered some problems with implementing more complex use cases and would like to get some input.

I was wondering how you implement resources that have multiple relations in DynamoDB. I understand you need to think about access patterns when designing your hash and sort keys, but I am struggling with scenarios where there are multiple ways in which the data will be accessed. Here is an example scenario with job postings and its access patterns:

  • Get jobs by status (ex. statuses: "taking applications", "reviewing applications", "complete")
  • Get jobs by company
  • Get jobs by date published
  • Get jobs by certification required (ex: Forklift certified)
  • Get a single job
  • Get all jobs

Here is what I came up with

PK (Hash Key) SK (Sort Key) Title Publish Date ...
COMPANY#12345 COMPANY#META Microsoft ...
COMPANY#12345 JOB#7890 Developer 2023-03-28 ...

With something like this, I can see how you could get all jobs for a company:

  • PK = 'COMPANY#12345') and begins\_with(SK, 'JOB#')

Get all jobs:

  • begins\_with(SK, 'JOB#')

Get a single job (assuming you have the id) with a GSI that swaps PK and SK

  • SK = 'JOB#7890'

Past these three access patterns, I'm not sure I see what the best way to go would be. I would appreciate if anyone has some tips on how things could be re-designed to permit all the access patterns above.

Design pattern for system retrieving data about an entity and updating it

I've come across the following situation multiple times when writing code (especially webapps) and would like to know the best practice (possibly design patterns) to solve it correctly:

My data is stored in some database or repository where I retrieve the data itself through an API. (therefor needing some sort of GET request)

My retriven data is processed and turned into a object representing the data. Fx a Dog with name, race, age.

In one way or the other I represent this Dog's data on my frontend using classic js, html.

I now want my users to be able to change the data on my frontend, send a request to my backend, and through my backend send a request to the API, updating my database / repository.

This is where my question arises.

What is the best way to structure this processflow? The first naive solution that pops into my head is having a Dog class like the following:

public class Dog() {

 // relevant fields

 public Dog(String json) {
  // map json result to Dog's fields
 }

 public static Dog getDogFromDb() {
  // call api
  // map api's json result to dog object
  // return Dog object
 }
 public void updateDogInDb(credentials, etc) {
  // take current dog, with its id, name, etc. and submit a request to the api, to update it according to Dog's fields and provided credentials.
 }
 // other dog methods, that might be relevant to the context...
 ...
}

In reality the Dog class would be much more complex, containing fields that represent other objects or lists of objects. Fx a Dog could have the following field List<Owner> ownersDogHasHad, this shouldn't change the question I simply want to clarify the complexity.

This approach works in practise, but seems to involve alot of different responsibilities in a single class, since Dog both represents a Dog and its methods, but also the practise of making a dog from a json response.body, making a dog from a database entity, and updating a dog in the databse.

How would this be written in a cleaner and clearer way? Is there any appropriate design patterns relavant?

How to register Infrastructure layer dependencies in Clean Architecture using .NET 6?

I am implementing a project using Clean Architecture in .NET 6. As per the Clean Architecture principle we should not reference Infrastructure layer in Web Api(Presentation layer), we should only access Application layer in Web Api.

So how can I register Infrastructure layer's dependencies without violating the Clean Architecture principle? I have created below extension method in Infrastructure layer to register dependencies:

namespace JwtWithIdentityDemo.Infrastructure.IoC
{
    public static class RegisterInfrastructure
    {
        public static void AddInfrastructure(this IServiceCollection services,
            IConfiguration configuration)
        {
            services.Configure<JwtSetings>(configuration.GetSection(JwtSetings.SectionName));
            services.AddSingleton<IJwtTokenGenerator, JwtTokenGenerator>();
            services.AddTransient<IUserManagerWrapper, UserManagerWrapper>();

            // For Identity
            services.AddIdentity<IdentityUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            services.AddScoped<UserManager<IdentityUser>>();

            // For Entity Framework
            services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(configuration.GetConnectionString("JwtWithIdentityDemoDb"),
          sqlServerOptions => sqlServerOptions.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)
              .EnableRetryOnFailure(
                  maxRetryCount: 5,
                  maxRetryDelay: TimeSpan.FromSeconds(30),
                  errorNumbersToAdd: null)
            ),
                ServiceLifetime.Transient
            );

        }

    }
}

If I call AddInfrastructure method in Program.cs then I have to add reference of Infrastructure library, which is violating the Clean Architecture's principles.

var builder = WebApplication.CreateBuilder(args);
{
    builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssemblyContaining<Program>());

    builder.Services.AddApplication(builder.Configuration);
    builder.Services.AddControllers();

    builder.Services.AddEndpointsApiExplorer();
    builder.Services.AddSwaggerGen();

    builder.Services.AddInfrastructure(builder.Configuration)

}

lundi 27 mars 2023

How to perform extensive business logic and retry from where it failed

I am trying to solve a problem where a lot of transactions happening in the business logic.

For example:

The request comes to the server (Service A)

  1. Step 1 - Transaction in DB
  2. Step 2 - Call Service B
  3. Step 3 - Another transaction to DB
  4. Step 4 - Call Service C
  5. Step 5 - 3rd Party service call
  6. Step 6 - Another transaction to DB

and so on... all the steps are dependent on the previous step.

Now, the problem is, if a step failed, I don't want to roll back the whole transaction but want to start from where it failed.

Is there a design pattern/solution that exists or what is the best way to solve this problem?

One of the solutions in my mind is

Break down the whole business logic into smaller logic (Per step) once a Step is complete, it will push the message in Queue (another Topic - Step2) and so on. If any of the steps failed, that will be picked from the queue again. This will solve the problem of retrying from the step it failed but I am worried about resources. Per call, I have to push around 7-8 messages (Steps) in the queue and process them separately.

Dynamic Inheritance, some piece of code... could you look and help mi in improving my code?

So i built this piece of code, but it looks like something is wrong in it. Is it not bad practice to creates function which creates class like belowe?

Should i build some subclasses?

base file

class BaseCsvLogger(ABC):
    """The file name is the same for whole working app time.
    """
    # some code ...
    def log_to_file(self, *args):
        ...

class DynamicFileName:
    @property
    def filename(self):
        return self.__filename()

class StaticFileName:
    @property
    def filename(self):
        return self.__filename

DynamiclyOpenFile class has modified log_to_file function to open file just befor super().log_to_file and close it just after.
StatyclyOpened open file in init method.

final class creator

from base_logger import DynamicFileName, StaticFilename, BaseCsvLogger


def Logger(filename: Union[str, Callable[[], str]],
           headers: Iterable[str],
           datetime_fmt: str,
           sep: str = ';',
           dec: str = ',',
           open_on_logging: bool = False) -> BaseCsvLogger:

    if open_on_logging:
        baseclass = DynamiclyOpenFile
    else:
        baseclass = StaticlyOpened

    if callable(filename):
        fname_type = DynamicFileName
    else:
        fname_type = StaticFilename

    class LoggerTmp(baseclass, fname_type):
        def __init__(self,
                     filename,
                     headers,
                     datetime_fmt,
                     sep,
                     dec) -> None:
            super().__init__(filename,
                             headers,
                             datetime_fmt,
                             sep, dec)
    logger = LoggerTmp(filename, headers, datetime_fmt, sep, dec)
    return logger

dimanche 26 mars 2023

I want you to create a single page application which contains any 5 or 6 games [closed]

I want you to create a single page application which contains any 5 or 6 games, and on selection we have to calculate total amount as per selection, Once the user selects the games and the total shown on the screen , The user can select multiple items . Java , android studio

example

I tried to do the same, but I couldn't and faced a lot of problems

What are some good places to find AWS architecture diagrams?

I know that the AWS docs are a good reference for sample architectural diagrams. I was wondering if there are any other websites/github repositories where one can find good references.

For example, there are github repositories for cloudformation templates to create standard resource stacks like VPC, DNS, CloudFront, EBS, EFS, etc. which makes the process of deploying resources very easy and espouses 'do not repeat yourself'.

I'm wondering if there is something similar for solutions architecture; so for example if I want to deploy a DevOps pipeline with certain other constraints, is there an architecture that I can use and just make small changes to suit my use case?

Thanks.

Apply Observer pattern to a Asteroid game

I want to apply the designer pattern to my Asteroid game. The use is for it to observe when I colide with an asteroid press or any input like the arrow keys and spacebar.

The Current code that takes care of that is:

 Map<KeyCode, Boolean> pressedKeys = new HashMap<>();

    scene.setOnKeyPressed(event -> {
        pressedKeys.put(event.getCode(), Boolean.TRUE);
    });

    scene.setOnKeyReleased(event -> {
        pressedKeys.put(event.getCode(), Boolean.FALSE);
    });

new AnimationTimer() {

    @Override
    public void handle(long now) {
        if (pressedKeys.getOrDefault(KeyCode.LEFT, false)) {
            ship.turnLeft();
        }

        if (pressedKeys.getOrDefault(KeyCode.RIGHT, false)) {
            ship.turnRight();
        }

        if (pressedKeys.getOrDefault(KeyCode.UP, false)) {
            ship.accelerate();
        }
        if (pressedKeys.getOrDefault(KeyCode.SPACE, false) && projectiles.size() < 3) {
            // we shoot
            Projectile projectile = charFactory.createProjectileFactory(new Polygon(2, -2, 2, 2, -2, 2, -2, -2), (int)ship.getCharacter().getTranslateX(), (int)ship.getCharacter().getTranslateY()).createProjectile();
            projectile.getCharacter().setRotate(ship.getCharacter().getRotate());
            projectiles.add(projectile);
        
            projectile.accelerate();
            projectile.setMovement(projectile.getMovement().normalize().multiply(3));
        
            pane.getChildren().add(projectile.getCharacter());
        }

        ship.move();
        asteroids.forEach(asteroid -> asteroid.move());
        projectiles.forEach(projectile -> projectile.move());

        asteroids.forEach(asteroid -> {
            if (ship.collide(asteroid)) {
                stop();
            }
        });

I've tried to apply the pattern but i end up with it either not working or it being super laggy, delayed or can't take in more than one command. What I did was create an interface with the method update, then a class that takes in the handling and the demo code uses the handling class. But even then the code looked messier, so I could've done it wrong.

I don't want a complete code block as an answer but would like if someone could help with the logical thinking or push me in the right direction.

Here is the full demo code:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.project.ConcreteClasses.Asteroid;
import com.project.ConcreteClasses.Projectile;
import com.project.ConcreteClasses.Ship;
import com.project.Factory.AbstractCharacterFactory;

import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Polygon;
import javafx.stage.Stage;

public class Demo extends Application {
public static int WIDTH = 500;
public static int HEIGHT = 400;

List<Projectile> projectiles = new ArrayList<>();

AbstractCharacterFactory charFactory = new AbstractCharacterFactory();

@Override
public void start(Stage stage) throws Exception {
    
    Pane pane = new Pane();
    pane.setPrefSize(WIDTH, HEIGHT);

    Ship ship = charFactory.createShipFactory(new Polygon(-5, -5, 10, 0, -5, 5), WIDTH / 2, HEIGHT / 2).createShip();
    List<Asteroid> asteroids = new ArrayList<>();
    for (int i = 0; i < 5; i++) {
         Asteroid asteroid = charFactory.createAsteroidFactory().createAsteroid();
         asteroids.add(asteroid);
     }
    
    pane.getChildren().add(ship.getCharacter());
    asteroids.forEach(asteroid -> pane.getChildren().add(asteroid.getCharacter()));

    Scene scene = new Scene(pane);
    stage.setScene(scene);
    stage.show();
    
    Map<KeyCode, Boolean> pressedKeys = new HashMap<>();

    scene.setOnKeyPressed(event -> {
        pressedKeys.put(event.getCode(), Boolean.TRUE);
    });

    scene.setOnKeyReleased(event -> {
        pressedKeys.put(event.getCode(), Boolean.FALSE);
    });

new AnimationTimer() {

    @Override
    public void handle(long now) {
        if (pressedKeys.getOrDefault(KeyCode.LEFT, false)) {
            ship.turnLeft();
        }

        if (pressedKeys.getOrDefault(KeyCode.RIGHT, false)) {
            ship.turnRight();
        }

        if (pressedKeys.getOrDefault(KeyCode.UP, false)) {
            ship.accelerate();
        }
        if (pressedKeys.getOrDefault(KeyCode.SPACE, false) && projectiles.size() < 3) {
            // we shoot
            Projectile projectile = charFactory.createProjectileFactory(new Polygon(2, -2, 2, 2, -2, 2, -2, -2), (int)ship.getCharacter().getTranslateX(), (int)ship.getCharacter().getTranslateY()).createProjectile();
            projectile.getCharacter().setRotate(ship.getCharacter().getRotate());
            projectiles.add(projectile);
        
            projectile.accelerate();
            projectile.setMovement(projectile.getMovement().normalize().multiply(3));
        
            pane.getChildren().add(projectile.getCharacter());
        }

        ship.move();
        asteroids.forEach(asteroid -> asteroid.move());
        projectiles.forEach(projectile -> projectile.move());

        asteroids.forEach(asteroid -> {
            if (ship.collide(asteroid)) {
                stop();
            }
        });

        List<Projectile> projectilesToRemove = projectiles.stream().filter(projectile -> {
            List<Asteroid> collisions = asteroids.stream()
                                                        .filter(asteroid -> asteroid.collide(projectile))
                                                        .collect(Collectors.toList());
        
            if(collisions.isEmpty()) {
                return false;
            }
        
            collisions.stream().forEach(collided -> {
                asteroids.remove(collided);
                pane.getChildren().remove(collided.getCharacter());
            });
        
            return true;
        }).collect(Collectors.toList());
        
        
        projectilesToRemove.forEach(projectile -> {
            pane.getChildren().remove(projectile.getCharacter());
            projectiles.remove(projectile);
        });

        if(Math.random() < 0.005) {
            Asteroid asteroid = charFactory.createAsteroidFactory().createAsteroid();
            if(!asteroid.collide(ship)) {
                asteroids.add(asteroid);
                pane.getChildren().add(asteroid.getCharacter());
            }
        }

    }
}.start();
}

public static void main(String[] args) {
    launch();
}
}

samedi 25 mars 2023

Typescript: Use inferred type of object for use in Generic

The Context

I'm trying to use Alpine.js together with TypeScript. For that, I'm using the community-maintained typings package @types/alpinejs (GitHub) together with the re-useable components design pattern described here. Here is a simple example using the type AlpineComponent<T>:

// This is the type for alpine components from definitely typed
import { AlpineComponent } from "alpinejs";

/**
 * I have to declare the T-part of the AlpineComponent<T> beforehand,
 * to be able to use it later. Otherwise, all my custom properties
 * will have the type "any"
 */
type Component = AlpineComponent<{
  foo: string;
  greet: (to: string) => string;
  // The list goes on and on and on in real-world code
}>

export default (): Component => {
  return {
    foo: "foo", // type "string", as defined in the type `Component`
    bar: "bar", // inconveniently has the type "any", since I didn't declare it inside my type `Component`...will have to do it manually... 😩
    greet(to) {
      return `Hello ${to}!`;
    },
    /**
     * init() is being invoked automatically by Alpine.js when the component is mounted
     */
    async init() {
      console.log(this.greet("World")); // greet correctly has the return type "string"
      await this.$nextTick(); // this is a "magic" method from Alpine.js. It's defined in the type `AlpineComponent`.
    },
  }
}

As you can see in the above example, right now I first define my type Component = AlpineComponent{...} with all the properties I will be using. And then I have to type them again when actually building my component.

Downsides of my current approach

  1. Typing everything twice as I'm doing now is quite cumbersome and feels very conflated.
  2. On alt-click on any property, my IDE (VS Code) now always jumps to the definition in my custom type Component rather then to the implementation inside my actual code. But I'm actually always more interested in the implementation instead of the definition.

The actual Question

Is there a better way to organize this, with less repeated typing of properties? Maybe something like inferring the type of the object returned from my component for the dynamic part of AlpineComponent<T>?

What are some actual example usages for the Chain of Responsibility design pattern [closed]

I am interested in a few actual examples for where you could use a chain of responsibility.

People always seem to explain very abstract reasons as to when you could use one but don't tell you concrete examples.

I am trying to find a logic to identify orders from a same entity with different names

I am trying to find a logic to identify orders from a same entity with different names. For example, I have a order list like this :

Order No From
123 ABC PVT LTD
124 ABC - India
125 ABC - USA
126 AB Companies
127 Del
128 All ABC Softwares

So in this example, as u can see, ABC - Pvt LTD / ABC - India / ABC - USA are same entity with different locations. Thus I want to consider them as one entity and their order count = 3 but it should not include the All ABC Softwares which is a different entity of its own.

The result should look like this :

Orders From
3 ABC
1 AB Companies
1 Del
1 All ABC Softwares

Similarly I have a list of 2000 entities that i need to match and group with similar ones.

I tried exploring Fuzzy match but it breaks for cases like, ABC - USA vs AB Companies, which should ideally be different but gives me as close as ABC PVT LTD

vendredi 24 mars 2023

Observer design pattern using boost asio concurrent channel

My program blocks when trying to send data from producer to consumer using boost asio channel.

The async_send method is not asynchronous. And the documentation says :this method send asynchronously data.

I tried to implement the observer design pattern using boost asio channels to send data between threads.

But Im a little bit surprised for the behaviour of async_send.

struct Subject
{
    using Channel = asio::experimental::concurrent_channel<void(
        std::error_code, std::shared_ptr<Response>)>;
    std::list<Channel> channels;
};
asio::awaitable<void> for_each_channel(Subject& subject, auto action)
{
    for(auto it = subject.channels.begin();
        it != subject.channels.end();)
    {
        if(it->is_open())
        {
            co_await action(*it);
            ++it;
        } else
        {
            it = subject.channels.erase(it);
        }
    }
}
asio::awaitable<void> notify_all(
    Subject& subject, std::shared_ptr<Response> response)
{
    co_await for_each_channel(
        subject,
        [&](Subject::Channel& channel)
        {
            return channel.async_send(
                std::error_code{},
                response,
                asio::use_awaitable); // blocks here
        });
}
asio::awaitable<void> close(Subject& subject)
{
    co_await for_each_channel(
        subject,
        [&](Subject::Channel& channel)
        {
            return channel.async_send(
                std::error_code{asio::error::operation_aborted},
                nullptr,
                asio::use_awaitable);
        });
}
auto& add_observer(Subject& subject, auto executor)
{
    return subject.channels.emplace_back(executor);
}
void remove_observer(Subject::Channel& observer)
{
    observer.close();
}
asio::awaitable<void> producer(Subject& subject)
{
    for(;;)
    {
        auto data = std::make_shared<Response>();
        co_await notify_all(subject, std::move(data));
    }
    co_await close(subject);
}
asio::awaitable<void> consumer(Subject& subject)
{
    bool ok{true};
    auto& observer =
        add_observer(subject, co_await asio::this_coro::executor);
    while(ok)
    {
        auto const [ec, response] = co_await observer.async_receive(
            asio::as_tuple(asio::use_awaitable));
        if(ec)
        {
            break;
        }
        co_await treatment(); // treat the response
    }

My question is why async_send is not asynchronous.

How to avoid blocking the producer threads ?

Is there a more useful/helpful documentation for boost asio channels other than boost documentation.

Extract n characters after pattern in string in R

I have a long string with mupltiple instances of pattern. I want the n characters following the pattern. Say that my string is "quick fox jumps over the lazy dog" and I want the two characters after every "u". i.e. I would want a vector c("ic", "mp") as my output. How can I do this?

Thanks!

Compile Time Interface

I am just wondering, is it a bad practice to use the below pattern for writing interfaces in C++? I recently came across a code base that uses this. Any advantages or disadvantages of using this? Is there a name for this pattern?

template<class Impl>
class Interface {
private:
  Impl impl_;
public:
  
  template<class... Args>
  Interface(Args&&... args) : impl_(std::forward<Args>(args)...){ }

  void foo(){
    impl_.foo();
  }

  void foo_bar(){
    impl_.foo_bar();
  }
}

class Impl1 {
private:
  int x_;
  std::string y_;
public:

  Impl1(int x, std::string y) : x_(x), y_(y){}

  void foo(){
    ...
  }

  void foo_bar(){
    ...
  }
}

class Impl2 {
private:
  int x_;
public:

  Impl2(int x) : x_(x){}

  void foo(){
    ...
  }

  void foo_bar(){
    ...
  }
}

int main {

  auto impl_1 = Interface<Impl1>(1, "whatever");
  auto impl_2 = Interface<Impl2>(2);
  return 0;
}

jeudi 23 mars 2023

How to use Shared Element Transition and State Pattern Together in Flutter?

I'm working on a Flutter widget that uses the state pattern whereby the layout changes in reaction to the state of an underlying model, so effectively there is a portion of the widget tree being swapped out when the state changes... but it does not use navigation.

But the basic (abstract) idea is:

The UI is presented to the user in a specific state.
The user completes some action available in that state by interacting with the UI.
The action triggers a function in the underlying model.
The model decides whether that was successful or not and if so, transitions to the next appropriate state.
The UI (stateful widget) is notified of this state change and replaces the section of the widget tree corresponding to the current state's layout.

The hierarchy of objects is like this:

Stateless widget (the main widget that the developer uses).

  • "has a" Stateful Widget (containing the various states that are "swapped out" as the model state changes)
    • "has a" model

The reason for using the state pattern is that in my specific case the widget is for recording, playing, and editing audio and is rather complicated as I only want the minimum necessary widgets present in any given state.

When the state changes, the various widgets' position, shape in some cases, visibility, interactivity, and click behavior all change.

Also there are states than can be transitioned to from more than one other state.

So you can see how this would be hell to implement in a single stateful widget and why I chose the state pattern to help with a separation of concerns.

Incidentally, I have previously implemented it the hellish way (no code provided here), just not with any animation:

enter image description here

Since then I have refactored it using the underlying model and state pattern in the hopes that adding animation would be the next step.

So far, I've gotten everything working (it doesn't crash and this is not a debugging question) except there is no animation between the states as is.

This is some example code that shows my current approach:

import 'package:flutter/material.dart';
import 'model.dart';

class AudioRecorderUI extends StatefulWidget {
  final AudioRecorderModel model;

  const AudioRecorderUI({super.key, required this.model});

  @override
  State<AudioRecorderUI> createState() => _AudioRecorderUIState();
}

class _AudioRecorderUIState extends State<AudioRecorderUI> {
  // the audio interface widget that corresponds to the current state of the model
  late AudioUIState _currentUIState;

  @override
  void initState() {
    super.initState();
    // add listener to the model
    widget.model.addListener(_reactToModelState);

    // set initial state
    // TODO: this is potentially problematic (calling setState inside initState)
    _reactToModelState();
  }

  @override
  void dispose() {
    // Remove the listener when the widget is disposed
    widget.model.removeListener(_reactToModelState);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return _currentUIState.build(context);
  }

  // ---------------------------------------------------------------------------------- REACTING TO MODEL'S STATE

  // Update the UI state based on the model's new state.
  // This is run manually the first time in order to set the initial state (which dpeneds on whether a recording exists or not)
  // From then onwards, it is set automatically using ChangeNotifier
  void _reactToModelState() {
    setState(() {
      _currentUIState = _getUIStateFromModelState(widget.model.state);
    });
  }

  AudioUIState _getUIStateFromModelState(AudioWidgetState modelState) {
    switch (modelState) {
      case AudioWidgetState.standby:
        return StandbyUIState(model: widget.model);
      case AudioWidgetState.recording:
        return RecordingUIState(model: widget.model);
      case AudioWidgetState.post:
        return PostUIState(model: widget.model);
    }
  }
}

// ------------------------------------------------------------------------------------------ UI STATES

// Define the different UI states as separate classes by extending an abstract class

abstract class AudioUIState {
  final AudioRecorderModel model;
  AudioUIState({required this.model});

  // this is a multiplier we use to establish a reference unit
  // ... by multiplying it with the view height.
  // We use the result for:
  // - the height and width of buttons
  // - add more
  static const double multiplierForGridSize = 0.125; 

  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return generateStackViewInConcreteInstance(
            height: constraints.maxHeight, width: constraints.maxWidth, gridSize: constraints.maxHeight * multiplierForGridSize);
      },
    );
  }

  // this is an abstract method
  Stack generateStackViewInConcreteInstance(
      {required double height, required double width, required double gridSize});
}

class StandbyUIState extends AudioUIState {
  StandbyUIState({required super.model});

  @override
  Stack generateStackViewInConcreteInstance(
      {required double height, required double width, required double gridSize}) {
    return Stack(
      children: [
        Positioned(
          top: (height/2)-(gridSize/2),
          left: (width/2)-(gridSize/2),
          child: Container(color: Colors.lightBlue, height: gridSize, width: gridSize,
            child: TextButton(
              onPressed: () {
                model.startRecording();
              },
              child: const Text("REC"),
            ),
          ),
        ),
      ],
    );
  }
}

class RecordingUIState extends AudioUIState {
  RecordingUIState({required super.model});

  @override
  Stack generateStackViewInConcreteInstance(
      {required double height, required double width, required double gridSize}) {
    return Stack(
      children: [
        Positioned(
          top: 20,
          left: 20,
          child: Hero(tag: "poo",
            child: Container(color: Colors.red, height: gridSize, width: gridSize,
              child: TextButton(
                onPressed: () {
                  model.stopRecording();
                },
                child: const Text("STOP"),
              ),
            ),
          ),
        ),
        Positioned(top: height/6, left: 0, child: Container(height: 2*height/3, width: width, color: Colors.yellow),)
      ],
    );
  }
}

class PostUIState extends AudioUIState {
  PostUIState({required super.model});

  @override
  Stack generateStackViewInConcreteInstance(
      {required double height, required double width, required double gridSize}) {
    return Stack(
      children: [
        Positioned(
          top: 20,
          left: 20,
          child: Container(color: Colors.red, height: gridSize, width: gridSize,
            child: TextButton(
              onPressed: () {
                model.startRecording();
              },
              child: const Text("RE-REC"),
            ),
          ),
        ),
        Positioned(
          top: 20,
          left: width/2 - gridSize/2,
          child: Container(color: Colors.green, height: gridSize, width: gridSize,
            child: TextButton(
              onPressed: () {
                model.startPlaying(from: 0, to: 1);
              },
              child: const Text("PLAY"),
            ),
          ),
        ),
        Positioned(
          top: 20,
          right: 20,
          child: Container(color: Colors.green, height: gridSize, width: gridSize,
            child: TextButton(
              onPressed: () {
                model.stopPlaying();
              },
              child: const Text("STOP"),
            ),
          ),
        ),
        Positioned(top: height/6, left: 0, child: Container(height: 2*height/3, width: width, color: Colors.yellow),)
      ],
    );
  }
}

As you can see in the example code, the states are separate classes that extend a base class.

As stated, I would like to have the various views and buttons "shared" by these states (they are not actually shared, unfortunately) animate their properties between states.

But with the current design, I can't just use an Animated widget like AnimatedPositioned because that widget is designed to be used within a single stateful widget's state class and animate as its properties are updated and setState is called.

However, in my case, the entire class containing said AnimatedPositioned widget would be replaced. And so an AnimatedPositioned widget would only work if I abandoned the state pattern and combined all the states into a single stateful widget.

So it seems what I'm seeking is a "shared element transition."

However, the only existing options for this seem to be a Hero widget or a PageRouteTransition, neither of which work in this scenario because I'm not using navigation.

You may not think that the state pattern is necessary because the functionality seems simple, but this is a minimal example and it's going to get much more complicated.

I am at the very limit of my abilities here!

How can the animations be achieved? That is, is there any "common practice" that isn't messy or "work-aroundy" that accomplishes what I'm trying do within the confines of the current design... or would I need to change the whole approach?

Ideally, the code should be structured in a such a way that each state's logic is separated, and that a developer could easily add an entire new state or change the layout of an existing state, and yet the states would still animate between one another without that having to be defined explicitly.

Things I have considered:

  • put everything in one huge class and just do all the animations explicity (Noooo!)
  • Use an animated builder to wrap each state and go from there somehow.
  • Use a Flow widget as suggested in comments (It feels to difficult to figure out how to apply that to this use case)
  • Add a new layer like an "Animation Coordinator" between the model and the main layout container that is aware of all the target layout configurations of each state, and what state is being transitioned from and to.

Java Creational design pattern

I am trying to create a class which returns me XX(XX could be either String or List based upon 2 different implementations) based on the input I provide.

I was thinking of building this using Factory/Abstract design pattern wherein the parent class will have 2 subclasses implementing their own logic and then returning String or List.

Can someone please tell if this can be achieved with above mentioned patterns or not?

public class DisplayFactory {

    public Display getDisplay( String device) {
        if ("D".equals(device))
            return new StringDisplay();
        return new StringListDisplay();
    }
}

public abstract class Display<T> {
    T displayFormat;
}

public class StringListDisplay extends Display {
    public StringListDisplay() {
        List<String> stringListDisplay = new ArrayList()<>;
        // some logic
        return stringListDisplay
    }
}

public class StringDisplay extends Display {
    public StringDisplay() {
        String stringDisplay;
        // some logic
        return stringListDisplay
    }
}

Problem with above approach is that the variable displayFormat needs to public to be used in other packages... Can someone share what could be a better approach here? The ideal solution would look like(please do share if its not possible to achieve below requirements):

  1. We should be able to return the specific datatype(String or List) and not some generic datatype(like Object).
  2. Should be able to fetch the value somehow.

Thanks

Which design pattern to choose in Golang

I understand this question seems obscure. Though I really am scratching my head around this.

I have a tremendously big XML to Marshal. The XML might go upto 1900-2000 lines at its peak level with around 21 levels of nested tags (~ 600-700 different types of XML elements to fill).

Currently I am preparing data model in Go from which I would be able to do xml.Marshal(). However, I also need to do lots of validation checks over this 600-700 fields before marshalling. They also have inter-dependency over each-other.

So, What should be the best design pattern I should choose to develop the solution?

mercredi 22 mars 2023

Akka, DDD and hierarchy of actors as aggregates

I know Akka and the actor model works well in a DDD approach. However, I do have one question about the hierarchy.

Imagine that I have a system where we can send messages to users. I may have one UserActor and a MessageActor.

+-----------+      +--------------+
| UserActor |      | MessageActor | 
|-----------|      |--------------|
| + id      |      | + id         |
+-----------+      | + userId     |
                   +--------------+

At some time, we may want to disable an user, and we do not want this user to accept any new messages.

It seems to be useful to have the UserActor receiving the CreateMessage and Disable commands. So that a disabled user can reject new messages without having to maintain that state somewhere else.

+------------+      +--------------+
| UserActor  |      | MessageActor | 
|------------|      |--------------|
| + id       |   /->| + id         |
| + messages |--/   +--------------+
+------------+                       

Is that a common usage or is it better to limit the number of child actors and use other mechanism to maintain the constraints ?

Thanks

Why is variable declared with "declaration pattern" only available in if statement

For reference in this example I have this Person type, although it could be any type:

public class Person
{
   public Person? Partner { get; set; }
   public Person? Child { get; set; }
}

Somewhere else I am checking if the person has a partner and children, but its not required to declare either.

Currently it looks like:

Person partner = null!;
if (person.Partner is not null)
{
   partner = person.Partner;
   //do stuff
}

if (person.Child is Person child)
{
   if (partner is not null)
   {
      //do one way
   }
   else
   {
      //do other way
   }
   //do stuff
}

Live example

I wanted it to look something along the lines:

if (person.Partner is Person partner)
{
   //do stuff
}

if (person.Child is Person child)
{
   if (partner is not null)
   {
      //use partner
   }
   //other stuff
}

Live Example

partner on the last example is declared outside of the if statement scope, but is not assigned. How could I, using this pattern, let the compiler know that its either declared with the person.Partner reference or null!?

Much like the out keyword on the following example doesn't throw a "not declared" error:

SomeMethod(out Person partner);
if(partner is not null) { }

Live Example

I am learning about the C# patterns and have looked into the documentation and feature proposal and there is no mention of what I was looking for, not even why it is declared outside of the scope preventing me from using the variable name? Even if I tricked my way around the pattern using it on the needed scope as shown here its not declared.

Is the above first example the standard approach and only way to do it?

Template Method vs Decorator Pattern

I write the code in Java and I have a case where I need to get the status of an order depending on the product type. Each product type has the same base logic as written below.

protected String getStatus(ProductType productType, Result result) {
  if (result.isSuccess()) {
    return "SUCCESS";
  } else if (result.getPaymentMethod().equals("TRANSFER")) {
    return "WAITING_CONFIRMATION";
  } else {
    return "WAITING_PAYMENT";
  }
}

However, each product type can have custom logic. For example:

  • if product type is "A", no need to modify the logic above
  • if the status returned from the method above is "SUCCESS" and the product type is "B", I need to call another service to check the status of the product issuance
  • if the status returned from the method above is "SUCCESS" and the product type is "C", I need to call partner service.

My question is what is the best design pattern to implement?

The first idea is using something like template method pattern

public class BaseProductStatusService {

  public String getStatus(Result result, Product product) {
    String status;
    if (result.isSuccess()) {
      status = "SUCCESS";
    } else if (result.getPaymentMethod().equals("TRANSFER")) {
      status = "WAITING_CONFIRMATION";
    } else {
      status = "WAITING_PAYMENT";
    }

    return doGetStatus(status);
  }

  protected String doGetStatus(String status, Product product) {
    return status;
  }
}

// For product A, no need to have its own class since it can use the base class

public class ProductBStatusService extends BaseProductStatusService {

  @Override
  protected String doGetStatus(String status, Product product) {
    if (status.equals("SUCCESS")) {
      return this.checkProductIssuance(product);
    }

    return status;
  }
}

public class ProductCStatusService() extends BaseProductStatusService {

  @Override
  protected String doGetStatus(String status, Product product) {
    if (status.equals("SUCCESS")) {
      return this.checkStatusToPartner(product);
    }

    return status;
  }
}

Another alternative is using decorator pattern

public interface ProductStatusService() {
   String getStatus(Result result, Product product);
}

public class DefaultProductStatusService implements ProductStatusService {

  public String getStatus(Result result, Product product) {
    String status;
    if (result.isSuccess()) {
      status = "SUCCESS";
    } else if (result.getPaymentMethod().equals("TRANSFER")) {
      status = "WAITING_CONFIRMATION";
    } else {
      status = "WAITING_PAYMENT";
    }

    return doGetStatus(status);
  }
}

public abstract class ProductStatusServiceDecorator implements ProductStatusService {

  private ProductStatusService productStatusService;

  public ProductStatusServiceDecorator(ProductStatusService productStatusService) {
    this.productStatusService = productStatusService;
  }

  public String getStatus(Result result, Product product) {
    return this.productStatusService.getStatus();
  }
}

// For product A, no need to have its own class since it can use the DefaultProductStatusService class

public class ProductBStatusServiceDecorator extends ProductStatusServiceDecorator {

  public ProductStatusServiceDecorator(ProductStatusService productStatusService) {
    super(productStatusService);
  }

  public String getStatus(Result result, Product product) {
    String status = super.getStatus();

    if (status.equals("SUCCESS")) {
      return this.checkProductIssuance(product);
    }

    return status;
  }
}

public class ProductCStatusServiceDecorator extends ProductStatusServiceDecorator {

  public ProductStatusServiceDecorator(ProductStatusService productStatusService) {
    super(productStatusService);
  }

  public String getStatus(Result result, Product product) {
    String status = super.getStatus();

    if (status.equals("SUCCESS")) {
      return this.checkStatusToPartner(product);
    }

    return status;
  }
}

which one is better for the above case and what is the reason? or do you have other suggestion?

mardi 21 mars 2023

How to manage python dependencies based upon user input? A question about structuring the python code

I am trying to implement the methodology described here. The details except for the ones I will post here are irrelevant to the scope of the question

  1. The intent is to implement hyperparameter tuning for lightgbm
  2. I do it the typical way - import lightgbm via import lightgbm, write a class that does it for me
  3. There is a special way to do hyperparameter optimization for lightgbm and that requires me to import lightgbm like from optuna.integration import lightgbm and the rest of the code can remain identical
  4. I want to provide the end users the capability to choose between the vanilla methodology (in point 2) or the special methodology (point 3). To implement that I have the following in the __init__ of the main class and the __init__ takes and argument use_lightgbm_heuristics=True
global lightgbm
    if use_lightgbm_heuristics:
        print("will be using heuristics")
        from optuna.integration import lightgbm
    else:
        print("will be using vanilla lgbm")
        import lightgbm

There is an import statement in the main class of my code. Can I do better?

Visitor design pattern: can my visitor returns a Promise or should I create a new interface

I am now using a Visitor pattern where I have 2 visitors using the same interface returning T. It basically looks like the schema below, but my visitor returns something.

I would like to change the return type of one of my visitor to return a Promise.

Should I create a new interface for this issue?

enter image description here

lundi 20 mars 2023

Selecting an architecture for objects of the same family with different function variants and variable inputs

I have many types of objects (screws, dowels, and many more) of the same family (fastener) who all have a function called 'geometry_requirements'. This function always takes a few common arguments and a few different arguments based on the object type.

One of the requirements is that the geometry requirements need to be stored in a database, making it very lenghty and 'empty' due to the differences between fasteners. Thus, the main challenges are making the construction of the tables for the database efficient and the overall approach able to accomodate for various conditions and various inputs.

Question: Are design patterns, or structures, or any solutions to this that I can explore and compare (to the solution below) please?

Initial approach:

My initial approach was to construct a database with only essential information to limit the length and then implement a Strategy Pattern to accommodate for special considerations.

class GeometryRequirements()

  • mapping of strategies, select the right one and perform operations

class GeometryStrategy

  • abstract class

class ObjStrategy(GeometryStrategy)

  • one strategy class per fastener type
  • handles input validation, conditions and query to database

Understanding the Open/Closed principle - do we have a counter-example

I'm trying to reach a better understanding of the Open/Closed principle. I'm familiar with reference material such as

Robert Martin's explanation

and Jon Skeet's exploration of the ideas, and the related concept of Protected Variation.

I have a nagging feeling that I still haven't got to essence of the Open/Closed Principle. One approach I have to increasing understanding of a concept is to explore the negation or inversion of the idea. I'm having trouble coming up with a concrete example of a violation of the Open/Closed principle - my hope is that if we have such an example we can point to it and say "Look at the unfortunate results of designing that way, how much better things would be if we were Open/Closed."

So, the question. Can you give a non-trivial example of, say, a Java class that is Closed for Extension or Open for Modification and why that would be a bad thing.

Obviously there are trivial cases such as making a class final so inheritance is barred but I don't think that's the core of the Open/Closed principle.

Can static list shared anywhere in spring boot application

Can I use static list initialized by @PostConstruct and get updated in every 4 secs, in other controllers, here I am trying to avoid multiple db calls. Is it correct approach? Please suggest. If not, What will be the consequences later as currently is working fine. Latest version of list not required its ok if any of the controller using old version of list and data insertion order is also not required that is why using parallelstream.

public class SpringBootApplication{

public static List<RefData> refDataList = null;

public static void main(String[] args) {
    
     SpringApplication.run(SpringBootApplication.class, args);
}



@PostConstruct
@Scheduled(fixedRate = 4000)
public void refDataUpdate() {

    refDataList =refDataService.findAllRefData();
    log.info(Ref Data Updated");

}

Controller 1

public class DataController1 {
     
@Scheduled(fixedRate = 10000)
public void updateRefDataByApi1() {
    List<RefData> list = SpringBootApplication.refDataList.parallelStream()
        .collect(Collectors.toList());
     
          <----Some Logics on Ref data list------->

        refDataService.saveAllRefData(list);
 }

Controller 2

public class DataController2 {
 
 @Scheduled(fixedRate = 10000)    
 public void updateRefDataByApi2() {
    List<RefData> list = SpringBootApplication.refDataList.parallelStream()
        .collect(Collectors.toList());
     
          <----Some Logics around Ref data list------->

        refDataService.saveAllRefData(list);
 }

Controller 3

public class DataController3 {

@Scheduled(fixedRate = 10000)
public void updateRefDataByApi3() {
    List<RefData> list = SpringBootApplication.refDataList.parallelStream()
        .collect(Collectors.toList());
    
    List<ResultList> resultList= new ArrayList<>();
         
     <----Some Logics around Ref data list------->

  
        otherService.saveAll(resultList);
 }
   

TypeError: %X format: an integer is required, not numpy.ndarray How to solve?

enter image description here
from __future__ import print_function
import numpy as np
def tohex(val, nbits):
 return hex((val + (1 <<nbits)) % (1 <<nbits))
array=np.load('C:/Tool/Python_pattern/agilev3_new/inout_pattern_layer52/in_52.npy')
#print(array.shape)
print(array.dtype)

# array[#][Row][Column][Channel] #1 52 52 384
fp = open("in_52.dat", "w")

for ch in range(384):
 data=array[ch]
 #print(data.dtype)
 #print(data)
 print(str("%08X" %(data)))
 
 if data<0:
  data=2**32+data
  #fp.write(str("%08X" %(data)))
  fp.write(str("%08X" %(data)))
 else:
  #fp.write(str("%08X" %(data)))
  fp.write(str("%08X" %(data)))
 fp.write("\n")
fp.close()

Here is the code I am using. I am trying to get a data file in powershell. But it always show error.

When I do in powershell.

PS C:\Tool\Python_pattern\agilev3_new\inout_pattern_layer52> python for_bias_patterm_rowachannel_base.py

I got this

Traceback (most recent call last):
  File "for_bias_patterm_rowachannel_base.py", line 16, in <module>
    print(str("%08X" %(data)))
TypeError: %X format: an integer is required, not numpy.ndarray

dimanche 19 mars 2023

Backrefs in Firebase Firestore

I am an experienced developer but a beginner in database management. I am wondering what is the best pattern to organize my database stored in Firestore (NoSQL).

I have two patterns in mind:

  • a user has pictures. I want to be able to get all the pictures for one user, and to get the picture owner easily
  • a chat room will have users, and users will have several chat rooms. It want to query a user's list of chat rooms and a chat room list of users. I want to be able to delete my chat room and its content if the last user leaves it.

What is the most efficient pattern to manage this in a Firestore context? Should I use backrefs or cross reference the documents, or should I use a query for all the images / chat rooms where the userId matches my user? How do I manage efficiently the "garbage collection" use case?

I have started with cross references but I am concerned by the extra cost of writing and editing more data (a user enters a chat room, it edits the user and the chat room), or the latency increase for the "get all pictures" use case if I store a lot of pictures and I rely only on indexes.

How to implement undo/redo feature which is consistent across application cycles in android?

I am implementing an undo/redo feature. I am following the commank pattern. I want the undo/redo to work even after I restart the application.

Currently, I am passing the fragment to update the view in the command itself. I am storing the command manager class which has list of undo/redo stacks using Xtream Serializer and restore the command manager when the app starts. But after restart I call undo(), it doesn't work.

I am supposed to ask for the view to update when undo() is called and not store it but I dont understand a way to it. Similarly storing just the information needed to undo and redo the command should be stored and the views to update should be asked at runtime. I don't know how to achieve this. Can someone please help?

Backend for Frontend in Microservices. HTTP or RPC with RabbitMQ for communication?

I'm implementing a microservice architecture and I need the use of Backend for Frontends, but I have doubts about how to implement its communication with microservices.

What do you do think about use RabbitMQ RPC to communicate a backend to frontend with all microservices?

I see these advantages:

  • It maybe offers better performance than REST.
  • Good scalability and native load balance.
  • It's easy to implement without the overhead of define types like with GRPC.

But these drawbacks:

  • It's a single point of failure. If RabbitMQ crashes, all microservices will be inaccessible, losing all microservice's independence.
  • It's based on asynchronous communication and in that case we are using it synchronously.

Would you use RabbitMQ RPC in that scenario or only for internal asynchronous communications between microservices? Based on your experience, what type of communication do you recommend for a backend for frontend?

Thanks!

HTTP:

enter image description here

RPC:

enter image description here

samedi 18 mars 2023

Chain of responsibility special scenario

In normal chain of responsibility design pattern implementation, handlers of the request will be added to the chain in a sequential order and will be executed accordingly. However in a special scenario if it's required to skip intermediate handlers and process request in the final handler, will it violate COR design pattern? Please refer the code snippets below. Hope it will clarify this further. Thanks in advance.

public class SomeHandler extends RequestProcessor {

public SomeHandler() {
    super();
}

@Override
public void process(Request request) {
    if (request != null) {
        //Logic to decide request type
        if ("TYPE_ONE".equalsIgnoreCase(request.getType())) {
            //passing to next object in the chain. Multiple chains...
            this.nextRequestProcessor.process(request);
        } else if ("TYPE_TWO".equalsIgnoreCase(request.getType())) {
            //passing to the last object in the chain,skip all the other intermediate objects
            new FinalHandler().process(request);
        }
    }
}

}

Dependency injection how to avoid hiding dependencies to stateful objects like a validator

I would like to have your opinion about such a situation, the code is quite simple to should be easy to follow:

@Component
class MyService {
    
    AusiliaryService ausService;

    public MyService(AusiliaryService ausService) {
        ...
    }

    public boolean isAccountValid(Account account) {

     AccountValidator accountValidator = new AccountValidator(account);
     boolean isValid = accountValidator.isValid(account);
     if(isValid) {
        ausService.openAccount(account);
     }
    }
}

Note that AusiliaryService is also spring managed and we are using constructor injection.

In this class AccountValidator is a dependency of MyService but it does not appear in the constructor so we could say the visibility of this dependency is somehow hidden.

Since we are hardcoding the instantiation of
AccountValidator accountValidator = new AccountValidator(account);

We may also have some potential issues with writing unit tests MyService, unless you may think such any unit tests should also impact AccountValidator, which for me would be a valid line of thought.

A possible work around for both "issues" would be to use a factory, to remove from MyService the responsability to instantiate AccountValidator object.

@Component
class MyService {
    
    AusiliaryService ausService;
    AccountValidatorFactory accountValidatorFactory;

    public MyService(AusiliaryService ausService, AccountValidatorFactory accountValidatorFactory;) {
        ...
    }

    public boolean isAccountValid(Account account) {

     AccountValidator accountValidator = accountValidatorFactory.getValidator(account);
     boolean isValid = accountValidator.isValid(account);
     if(isValid) {
        ausService.openAccount(account);
     }
    }
}

Note that also AccountValidatorFactory is spring managed and we are using constructor injection.

A cons of this solution could be though the proliferation of such factories classes, if you use this kind of pattern often in your code.

What would is your approach in such situations ? Which kind of solution would you prefer ? Would be possible to make AccountValidator also spring managed to help with this, how would that be done ?