vendredi 31 mai 2019

What is a good design pattern for tracking issues in a class?

I have a class that has a custom equals() method. When I compare two objects using this equals method, not only am I interested in whether or not they are equal, but if they are not equal, what was different about them. Finally, I want to be able to retrieve the differences arising from an unequal situation.

I currently use logging to display where my objects are unequal. This works, but I have a new requirement of being able to extract the actual results of the equals check for display later. I suspect there is an object-oriented design pattern for handling this type of situation.

public class MyClass {
  int x;
  public boolean equals(Object obj) {
    // make sure obj is instance of MyClass
    MyClass that = (MyClass)obj;

    if(this.x != that.x) {
      // issue that I would like to store and reference later, after I call equals
      System.out.println("this.x = " + this.x);
      System.out.println("that.x = " + that.x);
      return false;
    } else {
      // assume equality
      return true
    }
  }
}

Are there any good design pattern suggestions where some sort of work is being done, but a secondary object collects information about how well that work was done which can later be retrieved and displayed?

Avoid use of new Class inside a method to test

I have a simple class in PHP without dependency injection. I would like to know a best practice to avoid use of new History() to mock it inside tests. So my goal is to have History mockable. This is my code:

class TrelloCycleTime
{
    private $historyCards;

    public function __construct()
    {
        $this->historyCards = [];
    }

    public function getAll()
    {
        $this->historyCards = new HistoryCards('some params');
    }
}

A way is to create a method setHistoryCards and pass my historyCards mocked, but I don't like it so much.

Another way it could be to have a factory.

Any suggestions?

Should Builder.build() return a default state?

Using the Builder pattern there is always the question whether the fields do have a default value or not? I cannot find a reliable source where that's clearly defined...

The problem is readability: What is Car.Builder().build() returning? I always need to check the specific implementation of the Builder to see which default values are used. Shouldn't Builder be used to create complex objects which do not have a simple default state by definition?

An alternative would be to check whether all mandatory fields are set inside of the build() method:

fun build() : Car {
    return if (doors != null && hp != null) Car(doors, hp, color) // color can be null
    else throw IllegalArgumentException("Door count and HP is mandatory!")
}

...or is this considered bad practice?

Adapter pattern with Angular and Http request

Based on this article : https://blog.florimond.dev/consuming-apis-in-angular-the-model-adapter-pattern

I'm trying to adapt to my current code.

In the article :

   export interface Adapter<T> {
    adapt(item: any): T;
}

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

@Injectable({
    providedIn: 'root'
})
export class CourseAdapter implements Adapter<Course> {

  adapt(item: any): Course {
    return new Course(
      item.id,
      item.code,
      item.name,
      new Date(item.created),
    );
  }
}

----------------------------
export class CourseService {

  private baseUrl = 'http://api.myapp.com/courses';

  constructor(
    private http: HttpClient,
    private adapter: CourseAdapter,
  ) { }

  list(): Observable<Course[]> {
    const url = `${this.baseUrl}/`;
    return this.http.get(url).pipe(
      // Adapt each item in the raw data array
      map((data: any[]) => data.map(item => this.adapter.adapt(item))),
    );
  }
}
----------------------------

But me I don't use Observable, I tried to adapt this request but I don't find the solution

In the service :

 list(){   

    const url = `${this.baseUrl}/`;
    return this.http.get<CourseModel>(url);

  }

In the component :
  this.courseService.list().subscribe((data) => {
      console.log(data);
    });

jeudi 30 mai 2019

Event-Sourcing: How to handle Projections?

I have a two aggregates, one for a Task and another for a User Group. Both aggregates are event-sourced. I also have a Task List which is a projection. Currently, the Task List is built using the Task events. However, my users want filter the Task List based on User Groups. What approach should I take?

implement pattern desing FACTORY

I have this code in which I think two types of participants, the code becomes very long and I think I can apply the FACTORY pattern, but it is not implemented, should I create a class of specific classes "ParticipantOWner" and "ParticipantNormal"?

enter the description of the image here enter image description here

I want to create those classes based on that image of FACTORY PATTERNS, in the category that there are specific classes LusuryCar, SmallCar and SedanCar

 public Meet createRelacion(Long idOwner, Long idUser) {
            Meet currentMeet = new Meet();
            Bet bet = new Bet();
            bet.setInversion(100);
            currentMeet.setBet(bet);
            currentMeet.setState(State.start);
            currentMeet.setName(Math.random() + "");

            User user = userRepository.findById(idUser);
            User owner = userRepository.findById(idOwner);

            Bet betParticipant = new Bet();
            betParticipant.setInversion(0);
    ///////////////////   PRIMER PARTICIPANTE/////////////////
            Participant participant = new Participant();    //
            participant.setRol(Rol.NORMAL);            //
            participant.setMeet(currentMeet);               //
            participant.setUser(user);                      //
            participant.setBet(betParticipant);             //
  ////////////////////////////////////////////////////////////  
            participantRepository.save(participant);
    ///////////////////   SEGUNDO PARTICIPANTE//////////////////
            Participant participantOwner = new Participant();///
            participantOwner.setMeet(currentMeet);           /// 
            participantOwner.setRol(Rol.OWNER);              ///
            participantOwner.setUser(owner);                 ///
   /////////////////////////////////////////////////////////////
            participantRepository.save(participantOwner);
            return currentMeet;
        }

Is there anyway to design more complex GUIs

I am trying to program my own timer manager, for that I need a calendar, with a kind of week-view. Now I want to design a GUI that look like this:

https://imgur.com/WhAeE2u [1]

Do anyone know how I could design this? Whit which program, etc.

MVC controller-view binding in a view hierarchy

I'm developing a game which has several interdependent models, a view hierarchy where the top level view creates it's own inner views and so forth. Right now the views are tightly coupled with logic, directly modifying the state of the corresponding model. There are also aggregating models somewhat resembling a composite pattern, through which a communication between different models is done. My obvious concern is to separate the logic from the views and move it to the view controllers thus creating MVC architecture. But the problem is how to properly get the view instance from the potentially very deep view hierarchy to the corresponding controller. Since this is a game , the view hierarchy can frequently change, so I don't think that relying on getters is a good idea . Is MVC even a good solution in my case ? P.s I'm writing the game in js , but an example in any imperative language is ok

Should my classes have the same constructor using a factory pattern?

Actually I am using the factory pattern with classes that need different constructors.

Am I using this type of design pattern correctly or do I need to use a different design pattern for my problem?

Let's say that I have the following code:

public interface IProcessJob
{
   bool TryProcess(out StatusType status);
}

public class InitializationJob : IProcessJob
{ 
   public InitializationJob() { //Some code here... }
   public bool TryProcess(out StatusType status)
   {
     //Some code here...
   }
}

public class RelocationJob : IProcessJob
{ 
   public RelocationJob (IRepository<Item, Guid> _itemRepository) 
   { 
     //Some code here... 
   }
   public bool TryProcess(out StatusType status)
   {
     //Some code here...
   }
}

public class CleanUpJob : IProcessJob
{ 
   public CleanUpJob (IRepository<Processed, Guid> _processedRepository) 
   { 
     //Some code here... 
   }
   public bool TryProcess(out StatusType status)
   {
     //Some code here...
   }
}

Here I have my factory class that creates the instances with different constructors.

public static class ProcessJobFactory 
{
   public static IProcessJob GetProcessJob(
       ProcessJobType processJobType
       IRepository<Item, Guid> _itemRepository,
       IRepository<Processed, Guid> _processedRepository)
   {

       switch(processJobType)
       {
          case ProcessJobType.Initialization:
            return new InitializationJob();
          case ProcessJobType.Relocation:
            return new RelocationJob (_itemRepository);
          case ProcessJobType.CleanUp:
            return new CleanUpJob (_processedRepository);
       }
   }

}

callback function is not giving desired output

As per below code snippet shared in coliru link, Each time the user clicks the i’th button, the m_clicks[i] and m_total_clicks should both get incremented. To achieve this, the class MyFrame will register a "on_click-handler" callback with each button. Trying to register button_clicked as the callback doesn’t work.
m_pushbuttons[i].on_click_handler(MyFrame::button_clicked);// Doesn't give expected result

Below is the coliru link for source code. https://coliru.stacked-crooked.com/a/c15865d59b41341f

Here is the expected output based on below test cases for both f1 and f2 objects with print_stats method.

//MyFrame f1(2)
//f1.m_buttons[0].click();
//f1.m_buttons[0].click();
//f1.m_buttons[0].click();
//f1.m_buttons[1].click();
//f1.m_buttons[1].click();

//f1.print_stats();

//MyFrame f2(3);
//f2.m_buttons[2].click();
//f2.m_buttons[2].click();
//f2.m_buttons[2].click();
//f2.m_buttons[1].click();
//f2.print_stats();
// Should print:
// Total Clicks: 4
// Button[0] clicks: 0
// Button[1] clicks: 1
// Button[2] clicks: 3

So basically I need to write a client class so that when instantiated, will create N such buttons (where N is a constructor time parameter). The client class wishes to register a callback to keep track of button clicks but in current implementation, There are couple of issues.

(1) std::vector MyFrame :: m_clicks (2) is initialized statically and initialize value should be same as MyFrame initialized object value instead of static value .

(2) Without declaring static m_total_clicks and m_clicks , Is there any other way to achieve the same.

(3) on line no. 20 ,m_ftr pointer needs to be properly initialized.

Could you suggest any proper design/implementation for this callback implementation.

Replace Function with a serializable object

I have a class called FooFunctionRepository with the method void save(Function<Foo, Foo> fooFunction) which save in a map the given function and creates a snapshot (not always) of Foo object, so when I want to fetch an object Foo by id I don't have to parse the list of functions and "recalculate" the object state, I just fetch the last snapshot and then apply the saved functions after snapshot was taken.

var repository = new FooFunctionRepository();
var fooId = UUID.randomUUID();

repository.save(fooId, none -> new Foo());
repository.save(fooId, foo -> foo.withAmount(new BigDecimal(50)));
repository.save(fooId, foo -> foo.withAmount(foo.getAmount().add(BigDecimal.TEN)));
repository.save(fooId, foo -> foo.withStatus("shipped"));

I have to replace the in memory map Map<UUID, Function<Foo, Foo> from repository with a database table. My question is how to save the lambda let's say using Hibernate? Or should I replace the function with a DTO? But how the DTO is going to know what to change in my object?

Single request with many ResultSets vs many requests with one ResultSet each?

I have a Java Web Application using Spring MVC. The objects usually have lists of other objetcts as their properties. We build the objects using a single query returning multiples ResultSets, and treat it in the DAO.

Example: My Deck has a list of cards.

public class Deck{
   private int id;
   private String name;
   private List<Card> cards;

   //Constructor and Getters & Setters
}

public class Card{
   private int id;
   private String name;
}

To build it we use a query thar returns a ResultSet for the deck properties, and other ResultSets to build the cards and put the list in the deck.

Deck deck = null;

List<Card> cards = new ArrayList<Card>();
this.ps = this.conecction.prepareStatement("SP_SELECT_DECK ?");
this.ps.setInt(1, 1);

boolean isResultSet = this.ps.execute();

int nResult = 0;

do{
    if(isResultSet){
        this.rs = this.ps.getResultSet();

        while(this.rs.next()){
             switch (nResult) {
         case 0:
                     //Build the deck using the ResultSet
             deck = new DeckBuilder().newInstance(rs);
             break;                                      case 1:
                     //Add a new card built using the resultset
             cards.add(new CardBuilder().newInstance(rs));
             break;
         }
    }

        this.rs.close();
   }else{
       break;
   }            
   nResult++;
} while (this.ps.getMoreResults());

deck.setCards(cards);

Is this the better practice? Or is it better to do a query with the deck informations, return to the java application and call another query to fill the list of cards?

The question is about Patterns, Good Practices, Performance and Network Traffic

Why doesn't TryAddTransient return an IServiceCollection?

Most of the Microsoft Dot Net Core Dependency Injection static extensions return the IServiceCollection, for example AddTransient

Returning the IServiceCollection allows building up the dependencies fluently:

services
    .AddTransient<IThing,Thing>()
    .AddTransient<IOtherThing,OtherThing>()

But the TryAdd variants of these return void, for example TryAddTransient. This is irksome because it breaks the method chaining approach.

I can't think of a reason why the API is designed this way, but I doubt it's an omission. Am I missing something, why does it return null?

How to implement multhithread/task observer pattern?

I am working on a DAQ/instrumentation suite that should push large amounts of (double type) array data from/to HW devices e.g. DAQ boards or soundcards. Each HW device has a buffer, and will invoke callbacks when input buffer is full. The buffer should be pushed the buffer to several SW instruments e.g. oscillosope and spectrum analyzer. Each instrumennt as well as device driver should run in separate threads/tasks. My intention is to process about 1 Million doubles point per second.

For pushing data I have looked at IObservable/IObserver and I made an initial test which works without threads. The data type looks like this

public interface IAnalogInArrayData
{
        int NumberOfChannels { get; }
        int NumberOfPoints { get; }
        string[] XUnits { get; }
        string[] YUnits { get; }

        double[][] GetXData();
        double[][] GetXYata();
}


The double[][] could be up to [8][10000] and be updated every 100 msec.

Now I want to move to multi-threading (or tasks). I did some research and I am somewhat confused over the available alternatives:

  • according to an old SOF post (unfortunately I lost it), IObservable/IObserver should be replaced with Reactive extensions and Subject. However according to MSDN the Rx intro page is not updated anymore, but there is no suggestions to what should be used instead.
  • TPL: this seems to be a very high performing multithreading framework but I got lost in all options,

How can I make IObservable/IObserver thread safe? Should I skip threads and use tasks directly? Should I use Rx, TPL or am I missing any alternatives? What are the pros and cons of each approach? Feedback is greatly appreciated.

For pushing data I have looked at IObservable/IObserver and I made an initial test which works without threads, see attached code.

Callable Command Design Pattern Solution For Below Code

I have code block like below and I want to escape from repeated code with Callable design pattern. Is it possible?

    @GetMapping("")
    public ResponseEntity<?> getUserRules(HttpServletRequest request)
    {
        String integId = helper.getIntegId(request);
        String orgId = helper.getOrgId(request);
        return ResponseEntity.ok(service.getUserRules(integId,    orgId));
    }

    @GetMapping("/{ruleId}")
    public ResponseEntity<?> getRule(HttpServletRequest request, @PathVariable Long ruleId)
    {
        String integId = helper.getIntegId(request);
        String orgId = helper.getOrgId(request);
        return ResponseEntity.ok(service.getRule(integId, orgId, ruleId));
    }

    @PutMapping("/{ruleId}")
    public ResponseEntity<?> updateRule(HttpServletRequest request, @PathVariable Long ruleId,
                                        @RequestBody @Valid Object object)
    {
        String integId = helper.getIntegId(request);
        String orgId = helper.getOrgId(request);
        service.updateRule(integId, orgId, ruleId, object);
        return ApiResponse.ok();
    }

And I want to try execute it with Callable method.

public ResponseEntity execute(HttpServletRequest request)
{
    ? Actually, I could not find an exact solution here.
}

mercredi 29 mai 2019

what are the best online platform tu learn designing petern ..pls suggets

what are the best online platform tu learn designing petern ..pls suggets

Is there interceptor or filter in Hibernate, just like before advice in spring AOP

I have a Spring Application and use Hibernate5. I add a column dept_code for many tables, and I want to add dept_code query condition on the basis of the original query logic. For example:

before add dept_code column

select * from msg_template where status = "enable" and name like "test%";
select * from mini_page where groupId = -1 order by last_updated desc;
select * from customer where deleted = 0 order by last_updated desc limit 0 10;

after add dept_code column

select * from msg_template where status = "enable" and name like "test%" and (dept_code is null or dept_code = 'A');
select * from mini_page where groupId = -1 and (dept_code is null or dept_code = 'A') order by last_updated desc;
select * from customer where deleted = 0 and (dept_code is null or dept_code = 'A') order by last_updated desc limit 0 10;

There are so many query sql need to be add dept_code query condition, and the query sql will become very difficult to maintain if I modified all original query sql by adding dept_code query condition simply.

Is there a relatively good solution like sql intercetor that I do not need to modified query sql directly?

Is creating deeply nested objects which get modified a good practice?

In an attempt to learn Javascript, I'm building a simple browser game. I have certain objects in the game in the following hierarchy:

  • Locations
    • Locations...
      • Elements
        • Interactions
      • ...
    • Elements
      • Interactions
        • Items
      • Other information (e.g. stats)

Basically, each location has a parent location, and possibly children locations. Each location has elements, which has interactions, which hold items, as well as other identifier objects.

Each location, element, and interaction is unique, and can only have one parent (e.g. element 10 will only be in the child of only one location). Items and identifier objects can have multiple parents. Then, I build the game, and JSON stringify the data, and only rebuild when prompted to do so in the web app.

During the build, I'm pretty okay with it taking longer, but would like to optimize for speed and memory during gameplay.

What is the best practice to store the hierarchical relationships?

Currently, I'm doing the following: Each location has the unique location id of its parent, children, and elements. Each element has the parent location id and the id of the interactions and other identifiers. Each interaction has its parent element id, and the id of the items, if applicable. Each item and identifier objects do not have parents or children. Then the game build is a map of the following:

Location: Map of each location id to the data

Element: Map of each element id to the data

Interaction: Map of each interaction id to the data

Item: Map of each itemId to the data.

Identifier objects: Map from each identifier id to the data

In some pseudocode this is:

let _LocNames = {};
function _Location(locationId, parentId, context) {
    this.locationId = locationId;
    this.parentId = parentId;
    this.children = []; // array of strings
    this.elements = []; // array of strings
    // ... other stuff
    _LocNames[locationId] = this;
}

_Location.prototype.addChild = function(childId) {
    new _Location(childId, this.locationId, context);
    this.children.push(childId);
};

_Location.prototype.addElement = function(elementId) {
    this.elements.push(elementId);
};

let _ElementNames = {};
function _Element(elementId, parentId, context) {
    this.elementId = elementId;
    this.parentId = parentId;
    this.interactions = []; // array of strings
    // ... other stuff
    _LocNames[parentId].addElement(elementId);
    _ElementNames[elementId] = this;
}

_ElementNames.prototype.addInteraction = function(interactionId) {
    this.interactions.push(interactionId)
}

let _InteractionNames = {};
function _Interaction(interactionId, elementId, context) {
    this.interactionId = interactionId;
    this.elementId = elementId;
    this.items = context.items; // array of itemIds (strings)
    // ... other stuff
    _ElementNames[elementId].addInteraction(interactionId);
    _InteractionNames[interactionId] = this;
}

let _ItemNames = {};
function _Item(itemId, context) {
    this.itemId = itemId;
    // ... other stuff
    _ItemNames[itemId] = this;
}

let Data = {};
Data["Location"] = _LocNames;
Data["Element"] = _ElementNames;
// so on so forth

// The game build would then be
JSON.stringify(Data)

Then, suppose I want to do something with all elements at a location:

Data.Loc[locId].elements.map(elementId => foo(Data.Element[elementId]))

This works fine, but would a better design pattern be instead to make a more deeply nested hierarchy? For example something like:

function _Location(locationId, parent, context) {
    this.locationId = locationId;
    this.parentId = parent;
    this.children = {};
    this.elements = {};
}

let _baseLocation = new _Location("BASE", null, null);

function _findParent(id) {
    // Do something starting at the root node (_baseLocation)
    // and find the parent using some kind naming / design.
    return parent; // Note: the object, not the parentId
}

addChild(childId, context) {
    let parent = _findParent(childId);
    parent.children[childId] = new _Location(childId, parent, context);
}

function _Element(elementId, parent, context) {
    this.elementId = elementId;
    this.parent = parent;
    this.interactions = {};
}

addElement(elementId, context) {
    let parent = _findParent(elementId);
    parent.elements[elementId] = new _Element(elementId, parent, context);
}

// so on for the others lower on the hierarchy. 
// Then the game build would look like
JSON.stringify(_baseLocation)

Then during the gameplay, as it is impossible to jump for more than one level in the hierarchy, if we go back one level, we can just go to the parent.

In the first design, the deepest object is 4 in (Data -> Object Type -> Object Name -> ifArray/Map -> only strings/numbers), while in the second it could be really deep.

It would seem to be that storing the names, and having a more shallow design is more beneficial, and useable. If that's true, would it also be for an extremely large dataset?

Writing data classes with builder pattern

I have a data class which uses a builder to create the object and stores the data in a buffer in serialized form. I am planning to change the class to add and remove some fields. There are systems that will use both version of the class to create data i.e. the current version with all fields and newer version with removed/added fields. I am trying to see what is the best way to do this so that this is backward compatible(without breaking any consumer)?

I have couple of suggestions on how to do this but I am having a difficult time to pick one over the other.

Existing code

public class A implements Comparable<A>, Serializable {

private final Buffer buffer;
public static final Builder {
  private Header header//header with version
  private long creationTime;
  private SomeObject someObject;//this is removed in next version
  private OtherObject otherObject;//this is added in next version

  public Builder() { }

 //bunch of getters setters for fields

  public A build() {return new A(this);}

  private A(Builder b) {
   //build the object and put into the buffer
   validate()
  }
  private void validate() {//validates the object}

  public A(Buffer buf) {
   this.buffer=buf;
   validate();
  }
  public A(String encodedString) {
   this(ByteBuffer.wrap(encodedString));
  }
}
// consumers use this to get creationTime for object A
public long getCreationTime() {
 return buffer.getLong(OFFSET_CREATION_DATE);
}
}


Solution1: add new fields in the builder and use version in the header to decide which fields to use at build time (in build method) to create the object. Problem with this approach is that all the methods will exist at compile time to the consumers and unless they test their code every object will be valid. So it will be difficult to reason about which fields are required for which version at build time.

Solution2: Add a new builder in the class with the fields that you want. There will be duplicate fields that are in the existing builder. Consumers can then use the builder that they want. This seems to be cleaner because builders will be completely independent. Problem with this approach is that since we are adding and removing fields, fields will be at different offsets so the getters will have to change to use an offset based on versionType. This is also problematic for future versions because then we will have this gigantic class with lots of builders and logic in getters for every version

Solution3: Create a new class (let's say B) that extends A and have its own builder. This way the code is more modular. Problem is that now there will need to be some logic somewhere to differentiate and know which constructor to call. For example , if a consumer is passing base64 to get an object A, it will need to figure out which version it is.

String encodedString = "someString form of A"
A a = new A(encodedString);

Is there a recommended way to code these data classes with builder patterns to make it both future and backwards compatible.

NodeJS query processing results design pattern avoid nested then statements

I am writing an application in NodeJS10 and Mongoose5. I am writing a custom server-side pagination function. I want to run the pagination in a controller for separation of concerns and reusability.

I have a query to get data and return it in a then() response handler. I am then calling the custom pagination function inside the then() handler. This works, but I am concerned about the "nested" then/catch patterns. I think this might be messy especially if there is any additional processing required on the data before returning the response.

Here is the "nested" structure. How can I improve this to make it no longer nested and more readable while still catching all possible errors and returning the response correctly? Note that this works just fine, it's just the design pattern is messy and I want to avoid the "nested" then() statements if possible.

  items.find({
    _id: id
  }).then(data => {

    uiCtrl.pagination(data, req.query).then((result) => {
      res.status(200).send(data);
    }).catch((error) => {
      console.error(`pagination failed ${error}`);
      res.status(500).send(`pagination failed ${error}`);
    });

  }).catch((error) => {
    console.log(`${origin} ${error}`);
    res.status(404).send('Not found');
  });

Here is the custom async function being called inside the query result above.

const uiCtrl = {};

uiCtrl.pagination = async (data, query) => {

  // pagination logic here
  return data;
}

module.exports = uiCtrl;

Writing a Factory method for STL random number generators

I'm trying to provide an interface — through a config file — for my users to choose a distribution for some of the parameters that they are using. I would like to use STL random number generator algorithms for this purpose.

Let's assume that my program reads a JSON from a command line. For the JSON provided below, the program needs to realize that it should generate a random number from the normal distribution with given mean and standard variation. (I'm using the same parameter names as STL library for clearance.)

{
    "dist": "normal_distribution",
    "mean": 0.1,
    "stddev": 0.5
}

So far, I can parse the JSON easily, and use each distribution's param_type to initialize the distribution. I use the name to decide which distribution to decide the param_type and the distribution.

What I don't know is how to implement this nicely. I know that I should provide some sort of factory method for this, pass the JSON, and spit out a function or a class. If I want to return an instance of a class, let's say a unique_ptr of the generator, I need to define an abstract class, e.g., RandDist and write some sort of adaptor to incorporate my input, .... I generally don't need a lot from the class, just a gen() method should be enough.

I'm wondering if anyone have thoughts on this. Or, if anyone knows a library that can do this.

P.S. Input doesn't have to be a JSON object, any hash table would work per se.

How to handle many modal types with different callback functions in a global component in React

I want to have a global Modal Component (let's call it a wrapper for the sake of the conversation, meaning that it renders a white box inthe center of the screen and greys out the backround), which essentially displays different nested modals and is controlled by redux state and also can be toggled through dispatched actions. The hard part is that I cannot simply hardcode those modals into the parent component and switch between them basing on the action payload (modalType property, for instance), because due to the application requirements I need to somehow pass a callback to some of those nested modals, so they know how to behave when users click Yes/Ok in a given situation. And also this behavior varies, depending on the current context. Sometimes pressing OK means dispatching a series of other actions, sometimes it navigates to another page etc. Essentially, the desired functionality is to somehow "continue" the process that is frozen by the modal appearance. Is there a built-in mechanism that somehow allows for a rather generic approach that does not violate good practices and React architecture? I don't want to keep callbacks in the redux store, neither I want to pass whole components as action arguments and link the wrapper to state. The latter is the current solution I found in the application when I've joined the project and I want to refactor it, because it's considered anti-pattern. Is there a possibity to somehow reference the components from which the showModal action is being called and then manipulate their inner methods?

Design for javaFX application

I'm currently developing an application with javaFX using FXML Windows. the scope of the application is the following:

Get User Inputs (e.g. credentials) -> use these credentials to retrieve information using Web Services API calls -> use the collected information to either create a file or visualize in a table.

Currently, I am using the Main class to launch each FXML Window, return the info to the Main class and pass it to the next FXML Window and so on (e.g. Main -> FXMLWindow_1 -> Main -> FXML_Window_2 -> Main -> ...).

My question is is this correct from a design / workflow stanpoint? Or would it be better / same to launch each FXML Window sequentially from the previous one (e.g. Main -> FXMLWindow_1 -> FMXLWindow_2...)?

Bash - check if any of the files within a folder contain a pattern then return filename

I'm writing a script that aim to automate the fullfill of some variables and i'm looking for help to achieve this:

I have a nginx sites-enabled folder wich contain some reverses proxied sites. I need to: 1: check if a pattern $var1 is found in any of the files in "/volume1/nginx/sites-enabled/" 2: return the name of the file containing $var1 as $var2

Many thanks for your attention and help!

i have found some lines but none try any files in a folder

if grep -q $var1 "/volume1/nginx/sites-enabled/testfile"; then echo "found" fi

mardi 28 mai 2019

MVP in windows forms

I want to implement MVPO pattern in my windows forms application. As you know there is 1:1 means there is one presenter for one view.

So basicly we can have:

public class MainPresenter
{
       IMyView _myView;
       public MainPresenter(IMyView myView)
       {
             _myView = myView;
       }
}

My question is can one presenter use other presenter so for instance:

public class MainPresenter
{
       IMyView _myView;
       ISomeOtherPresenter _otherPresenter;
       public MainPresenter(IMyView myView, IOtherPresenter otherPresenter)
       {
             _myView = myView;
             _otherPresenter = otherPresenter;
       }
}

As a reference i went through video tutorial by Robert Marquez. At his 10 video serie at 10th one he used one rpesenter inside other one

Reference link

at 35:39 you will see his MainPresenter has dependency to IHelpAboutPresenter.

How Can I Organize and Reduce The Amount of Classes in My Application

I guess this is more of a Design Pattern question than coding question. So here we go... I have an android application that contain many classes and activities. I have classes grouped inside directory according to their function eg: DownloadTask, ScanTask inside the AsyncTask directory. Then I have all all activities inside the activity directory and so on. But I notice that a lot of my code is repeated. For example, I have 3 Activities PingActivity, NetstatActivity, WhoisActivity that basically look entriely the same from the point of view of the code. The only difference is the command their using eg: ping host for PingActivity, netstat -ant for NetstatActivity and so on.. they all instanciate the views from an xml layout that looks very similar since all I have is EditText, button, and TextView. And the classes Call AsyncTask to perform the background process separate from the main thread. With the exception of WhoisActivity which use rest api service to query for domain name. So my question is how can I simplify my design? can I use one single class and pass the command or api depending what menu option the user selected? how can I do that? thanks

Are the "Prototype pattern" and the "Virtual constructor" the same patterns?

Does the Virtual constructor - implementing virtual function clone():

class X {
public:
     virtual X* clone() {
         return new X(*this);
     }
};

mean the same concept as the Prototype design pattern?

Email Regaular Expressions - Failing for domains less than 3 chars

I have a regular expression which is good with all my rules except that it fails to validate email addresses with less than 3 characters in its domain. Eg It considers sample@q.com and sample@me.com as invalid emails

Regex can be found here https://regex101.com/r/XcXIaL/1

Could anyone suggest a modification to this existing regular expression

It should accept sample@q.com, sample@me.com and sample@mes.com

Is there a way to do Object Composition similar to Concatenative Inheritance?

I've been learning how to do Object Composition in Javascript using Concatenative Inheritance and wondered how I could accomplish something similar in VBA (which doesn't have inheritance).

I've created a simple example to demonstrate what I'd like to accomplish.


Testing Module

This is just an example use of the Fighter class. The Fight method is actually calling the Fight method in the CanFight class. It debugs a message and reduces stamina by 1.

Private Sub StartGame()

    Dim Slasher As Fighter
    Set Slasher = New Fighter
    Slasher.Name = "Slasher"

    Slasher.Fight '-> Slasher slashes at the foe!
    Debug.Print Slasher.Stamina '-> 99

End Sub


Fighter Class

This class has two public properties Name and Stamina.

This class also contains FightAbility which is an instance of the CanFight class. This is my attempt at trying to accomplish composition.

Option Explicit

Private FightAbility As CanFight
Private pName As String
Private pStamina As Long

Private Sub Class_Initialize()
    pStamina = 100
    Set FightAbility = New CanFight
End Sub

Public Property Get Name() As String
    Name = pName
End Property

Public Property Let Name(ByVal Value As String)
    pName = Value
End Property

Public Property Get Stamina() As String
    Stamina = pStamina
End Property

Public Property Let Stamina(ByVal Value As String)
    pStamina = Value
End Property

'This is the function that uses the ability to fight.
'It passes a reference to itself to the `CanFight` class
'giving it access to its public properties.
'This is my attempt at composition.
Public Sub Fight()
    FightAbility.Fight Me
End Sub


CanFight Class

This is the class that can be reused for other characters. An Example is a Paladin class might need to also have the ability to fight.

The obvious issue with how this is laid out is that state is an Object. The user won't know it needs to have Stamina and a Name property unless they look at the code.

Option Explicit

Public Sub Fight(ByRef State As Object)
    Debug.Print State.Name & " slashes at the foe!"
    State.Stamina = State.Stamina - 1
End Sub


My example feels broken since there is no structure in place as far as what properties are needed in order to use it. At the same time, I want to make sure my game characters can be flexible in having their own distinct properties as well (for example a Paladin class might have a Mana property).

My question is how do I achieve structured Composition like this in VBA?

How to print this pattern using asterick?(plz view the image)

How to print this pattern in python taking input from user?in this case the user input was 4 (https://i.stack.imgur.com/QvzJA.jpg)

Abstraction of API client

How do you deal with abstractions for the API clients, when you need to create multiple nested builders for staff like request builders.

I need to use an external payments service in a business logic to deposit user's internal account. Generally I need to send a JSON that looks like this:

{
  "amount": {
    "value": "200.50",
    "currency": "RUB"
  },
  "description": "Some text",
  "confirmation": {
    "type": "redirect",
    "return_url": "https://site.ru"
  },
  "payment_method": "bankcard"
}

I make a bunch of contracts (interfaces) that allows me to do this:

$request = $gateway->createPayment()
    ->setAmount('200.50', 'RUB')
    ->setDescription('some text')
    ->confirmation()
        ->redirect()->setReturnUrl('https://site.ru')

$request->paymentMethod()->bankcard();

return $request;

confirmation() and paymentMethod() are problems. These are separate interfaces but also they contain methods like redirect() inside them, which return another interfaces.

There are another request options that can contain bigger depth of nesting. And for the every nested level I should create an interface.

It would be more comfortable if I will use something like $payment->setConfirmation(new Redirect('https://site.ru')) where Redirect is an implementation of ConfirmationInterface, but I cannot do this, because the Redirect is a concrete implementation, but I want to fully decouple my business logic services from implementations, so I cannot create any instances that doesn't rely on the business services layer.

So maybe you know another ways how to make it robust and beautiful?

JavaScript JSON API Parser w/ Default Values?

When consuming an external JSON API I expect certain values but I need to guard against bad inputs since I cannot control the external API.

Writing a local parser class is an option but seems pretty tedious. I need to check that the properties exist and that they are the right type (e.g. that the API did not return a string instead of an array or object) and this quickly adds up to a decent chunk of code.

Are there any standard ways of dealing with this? Any popular libraries? I tried a Google search but could not find anything.

Is it wrong to call component methods passed as arguments inside of redux actions?

I'm struggling with one task I've been appointed to and the only workaround I found is to call the action argument callback inside the action. Is this a bad idea from a design point of view, because the code itself works and passes numerous tests? The general purpose of this solution is to somehow trigger the component function when a certain logic is being followed.


export function myAction(componentClb: () => void): any {
  return (dispatch: Dispatch<AppStore>): void => {
    someRESTAPIcall()
      .then((condition) => {
        condition
          ? dispatch(anotherActionThatTakesCallbackAsArgument(componentClb))
          : componentClb();
      })
      .catch((error: Error) => {
        dispatch(myErrorAction());
      });
  };
}


Javascript/Node backend project with plugin architecture

Im currently building a javascript project that should include optional plugins. Is there a best practice architecture or a module that can help me?

c# Simple Injector inject decorator in a class only from one client

Hy guys,
I have a problem, I have an interface like this:

public interface ICommand<in TRequest, out TResponse> 
    where TRequest : class
    where TResponse : BaseResponse
{
    TResponse Execute(TRequest request);
}

then I two class that implements this interface like this:

public class ExternalAddUser : ICommand<ExternalAddUserRequest, ExternalAddUserResponse>
{
    private readonly ICommand<AddUserRequest, AddUserResponse> _command;

    public ExternalAddUser(ICommand<AddUserRequest, AddUserResponse> command)
    {
        _command = command;
    }

    public ExternalAddUserResponse Execute(ExternalAddUserRequest request)
    {
        var response = _command.Execute(Mapper.Map<AddUserRequest>(request));

        return Mapper.Map<ExternalAddUserResponse>(response);
    }
}

and this:

public class AddUser : ICommand<AddUserRequest, AddUserResponse>
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IMessageService _messageService;
    private readonly IDefaultSettings _settings;
    private readonly IMessageFactory _messageFactory;

    public AddUser(IUnitOfWork unitOfWork, IMessageService messageService, IDefaultSettings settings, IMessageFactory messageFactory)
    {
        _unitOfWork = unitOfWork;
        _messageService = messageService;
        _settings = settings;
        _messageFactory = messageFactory;
    }

    public AddUserResponse Execute(AddUserRequest request)
    {
        // My implementation here
    }
}

The Interface IMessageFactory is a "Factory/Template" Pattern that creates an IMessage interface with only property like: Body, Subject, Language. I have registered my class with simple injector like this:

container.Register(typeof(ICommand<,>), businessLayerAssembly);   
container.Register<IDefaultSettings, DefaultSettings>(Lifestyle.Singleton);
container.Register<ISecuritySettings, SecuritySettings>(Lifestyle.Singleton);
container.RegisterConditional<IMessageFactory, ActivationMessageFactory>
            (c => c.Consumer.ImplementationType == typeof(AddUser) 
                  || c.Consumer.ImplementationType == typeof(SendActivationEmail));
container.RegisterConditional<IMessageFactory, RecoveryMessageFactory>
            (c => !c.Handled);

Now I have another class that is Decorator of ActivationMessageFactory like this:

public class ActivationMessageWithoutLinkFactory : IMessageFactory 
{
    private readonly IMessageFactory _messageFactory;

    public ActivationMessageWithoutLinkFactory(IMessageFactory messageFactory)
    {
         _messageFactory = messageFactory;
    }

    public IMessage CreateMessage(MessageData messageData)
    {
        // Implementation
    }
}

My question is:
Is possible to inject ActivationMessageWithoutLinkFactory decorator in AddUser class when this class is called from ExternalAddUser class? Smell code example:

public class ExternalAddUser : ICommand<ExternalAddUserRequest, ExternalAddUserResponse>
{
    public ExternalAddUserResponse Execute(ExternalAddUserRequest request)
    {

        ICommand<AddUserRequest, AddUserResponse> command = new AddUser(new SqlUnitOfWork(), new EmailService(), 
            new DefaultSettings(), new ActivationMessageWithoutLinkFactory(new ActivationMessageFactory()));
    }
} 

Thank you for you answer, I hope i was clear.

Decorator pattern for a Customer class

Suppose I have a Customer class. A customer can have multiple kinds of loyalty points. For one promotion, the customer may be collecting Rewards. In another, the customer may be collecting Miles. And there is no fixed number of kinds of loyalty points that the Customer is built for. I am sure this is a common use case. Is the decorator pattern a good fit given below sample code?

    public interface ICustomer
    {
        void Display();
    }

    public class SimpleCustomer : ICustomer
    {
        public void Display()
        {
            Console.WriteLine("I am simple customer");
        }
    }

    public abstract class CustomerDecorator : ICustomer
    {
        protected ICustomer customer;

        public CustomerDecorator(ICustomer customer)
        {
            this.customer = customer ?? throw new ArgumentNullException("customer");
        }

        public abstract void Display();
    }

    public class RewardsDecorator : CustomerDecorator
    {
        private int rewards;
        public RewardsDecorator(ICustomer customer, int rewards) : base(customer)
        {
            this.rewards = rewards;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + rewards.ToString() + " rewards");
        }
    }

    public class MilesDecorator : CustomerDecorator
    {
        private int miles;
        public MilesDecorator(ICustomer customer, int miles) : base(customer)
        {
            this.miles = miles;
        }

        public override void Display()
        {
            Console.WriteLine("Now I have " + miles.ToString() + " miles");
        }
    }

Building modular asp core angular application

I'm here because i'm facing an issue. At our company, we decided to build an asp core with angular front end application. And we want to publish it to our intégrators. But they may want to add specific developpement on their side on our applications for specifics clients needs. So how is it possible for them to add code to our application, on the front end part (angular )as well as the backend part (asp core) knowing that we will give them a compiled application. We do not want them to have access to the source code ...

It's like for odoo for example you can add pluggin to it we would like to do something similar. Do you guys know how it is possible in asp core + angular 7 ?

Thanks in advance, Looking forward for your advices A.MOULAY

lundi 27 mai 2019

Pattern Command - Explanation Please

I am a beginner in Java and currently I am learning a little bit about patterns. I've learnt about Factory Pattern, Sigleton, etc

Past week was Command Pattern, but I couldn't undestand in which way I have to use it. I've googled it but my brain is fried.

Can any of you help me in simple words about this pattern?

Thanks in advance!

Gonzalo

Dynamically choose implementation of logger in Scala

I have a library in which I use log4j to log things. For some particular classes of my library (all classes extending Component) I want that the log statement contain the suffix [component_name] at the beginning.

I don't want to mutate how a log statement usually looks like. Therefore, within one of these special component named 'foo' the statement log.info("message") should output [foo] message in the logging system.

This is what I did so far and where I am stuck:

object Logging {
   val logger = Logger.getLogger("my_logger_name")
}

This is the basic logger, which I call all over the code using Logging.logger.info("message")

I thought the best thing to do would be to build the enriched logger using a trait

trait WithEnrichedLogger {
   this: Component =>
   val logger = new EnrichedLogger(this.name)
}

class EnrichedLogger(name: String) {
   def info(msg: String): Unit = Logging.logger.info(s"[${name}] $msg")
}

and my component simply looks like

abstract class Component with WithEnrichedLogger {
     def name: String
     ....

     def some_method: Unit = { 
        logger.info("log statement") \\ it should print the '[name]' at the beginning 
     }
 } 

The problem in this setup is that at the moment of Component creation, the WithEnrichedLogger trait gets initialised and the value of name is still null. For this reason, the statement is "null log statement"

This solution looked to me the most elegant one, but please propose me different ones if better

What does Liskov Substitution Principle preserve?

As I've read the substitution of objects of a concrete type by instances of a subclass of that concrete type must preserve a program's correctness, a program's invariants.

I'd like to know what exactly is meant by correctness and invariants of a program?

How to use Spring Constructor DI in classes implementing an interface

So I want to achieve something like this::

@Component
public class ComponentA {}


@Component
public class ComponentB {}


public interface MyInterface

void doSomething();


public class MyInterfaceImplA implements MyInterface

private final componentA;

@Inject
public MyInterfaceImplA(ComponentA componentA){
this.componentA = componentA;
}

public void doSomething(){
    componentA.doThis();
}


public class MyInterfaceImplB implements MyInterface

private final componentB;

@Inject
public MyInterfaceImplB(ComponentB componentB){
this.componentB = componentB;
}

public void doSomething(){
    componentB.doThat();
}

What I basically want is to use different Components to execute things in the implementing classes. But as the components are different classes so this is not possible.

My question is if there is a good way to set this architecture up in this or a similar way? Or is there a pattern to achieve this in a better way?

Java - Mapping DTOs with Circular Dependencies

Currently settings up classic mappers, converting Entities to DTOs. Some of the entities (and thus DTOs) reference each other (after specific JPA entity definition).

Let's say:

public class Person {
  private String name;
  private List<State> states; // All states with this person
  // Getters & Setters
}

public class State {
  private String name;
  private List<Person> persons; // All persons with this state
   // Getters & Setters
}

With such circular dependencies I have to set up mappers like so:

public class PersonMapper {
   public PersonDTO toDTO(Person p) { // not null
     PersonDTO dto = new PersonDTO();
     dto.setName(p.getName());
     dto.setStates(p.States().stream().map(stateMapper::toDTO).collect(Collectors.toList());
     return dto;
   }

public class StateMapper {
   public StateDTO toDTO(State s) { // not null
     StateDTO dto = new StateDTO();
     dto.setName(s.getName()); 
     dto.setPersons(s.getPersons().stream().map(personMapper::toDTO).collect(Collectors.toList());
     return dto;
   }

One way to easily avoid this is to create a new method in PersonMapper or StateMapper and make it NOT map the persons or states. But I was wondering if there was a known design pattern or a more generic way of doing this?

Thanks

Building an activity and notification stream for a social network application

As the title suggests, currently my social network backend is in NodeJs with MongoDB and I am looking to add celery + RabbitMQ with Postgres/Cassandra for the activity feed/notification as message queue on fanout based. Do I am approaching my problem in correct way or do I have to look for something like Kafka or else? I am also in mixed of doubts where does my broker should be like my backend serves REST API for different clients. Do clients directly updates data by producing and consuming simultaneously or just consume data while using REST for adding "post/comments"

Need some insight on the way to approach realtime feed problem like the way of Facebook, Instagram or Reddit, etc

dimanche 26 mai 2019

How to associate a Class with more than one behavior with other Class?

I have some objects that need two types of behavior at the same time when are associated with a Game Class. How is the best way to do this? I'm not seeing any of the GoF Patterns here to help but maybe i'm just with my brain overloaded.

interface Actor {}

class Man implements Actor {}

class Woman implements Actor {}

class Game {
    private Map<Actor> actors;
}

How to include Player, Referee or LineJudge behavior to this code.

Example:

Game 1, Actor 1 Woman and Referee, Actor 2 Woman and Player Game 2, Actor 1 Woman and Player, Actor 2 Man and Player Game 3, Actor 1 Man and Player, Actor 2 Man and Referee, Actor 3 Woman and LineJudge

...

yield return IEnumerator or IEnumerable

I'm new to C#, just a question on yield keyword which confuses me a lot. It seems that yield can return an IEnumerator and IEnumerable

//case 1
static IEnumerator YieldReturn()
{
   yield return 1;
   yield return 2;
   yield return 3;
}

and

//case 2
static IEnumerable YieldReturn()
{
   yield return 1;
   yield return 2;
   yield return 3;
}

how come one thing can return two different return types?

can I use generic services in domain service with different business or not?

I have problem in create generic domain service or not?? I have "BaseEntity" that inherit any entity from it and has been every moment set value when update or insert method called in repository .my domain service layer that implements every entity business. my problem is what I have to do when I have one business that implement in every Services in domain service.can I use generic class and interface to manage BaseEntity and then change business for example for Update method override base update method or I used for every entity one service class with one interface with separate business???

Java: Design patter for pre and post processing like Servlet filters offer

I have this unique requirement where I have to allow for some processing before and after a method call in Java 8 and version onwards. No requirements of backward compatibility. Also, both pre processing hooks and post processing hooks needs to be extensible. Extensible here means, that any developer should be able to chain the preprocessors and post processors. Also, actual APIs are all asynchronous. I have observed that Servlet filter provide similar kind of functionality but I want this in simple Java application which will not run on server.

samedi 25 mai 2019

Need an optimized way to handle combination of entities to improve performance

So, I am working on a feature in a web application. The problem is like this- I have four different entities. Let's say those are - Item1, Item2, Item3, Item4. There's two phase of the feature. Let's say the first phase is - Choose entities. In the first phase, User will have option to choose multiple items for each entity and for every combination from that choosing, I need to do some calculation. Then in the second phase(let's say Relocate phase) - based on the calculation done in the first phase, for each combination I would have to let user choose another combination where the value of the first combination would get removed to the row of the second combination.

Here's the data model for further clarification -

EntityCombinationTable
(
  Id
  Item1_Id,
  Item2_Id,
  Item3_Id,
  Item4_Id
)

ValuesTable
(
  Combination_Id,
  Value
)

So suppose I have following values in both values -

EntityCombinationTable
Id -- Item1_Id -- Item2_Id -- Item3_Id  -- Item4_Id
1     1           1           1            1
2     1           2           1            1
3     2           1           1            1
4     2           2           1            1

ValuesTable
Combination_Id -- Value
1                 10
2                 0
3                 0
4                 20

So if in the first phase - I choose (1,2) for Item1, (1,2) for Item_2 and 1 for both Item_3 and Item4, then total combination would be 2*2*1*1 = 4.

Then in the second phase, for each of the combination that has value greater than zero, I would have to let the user choose different combination where the values would get relocated.

For example - As only combination with Id 1 and 2 has value greater than zero, only two relocation combination would need to be shown in the second dialog. So if the user choose (3,3,3,3) and (4,4,4,4) as relocation combination in the second phase, then new row will need to be inserted in EntityCombinationTable for (3,3,3,3) and (4,4,4,4). And values of (1,1,1,1) and (2,2,1,1) will be relocated respectively to rows corresponding to (3,3,3,3) and (4,4,4,4) in the ValuesTable.

So the problem is - each of the entity can have items upto 100 or even more. So in worst case the total number of combinations can be 10^8 which would lead to a very heavy load in database(inserting and updating a huge number rows in the table) and also generating all the combination in the code level would require a substantial time.

I have thought about an alternative approach to not keep the items as combination. Rather keep separate table for each entity. and then make the combination in the runtime. Which also would cause performance issue. As there's a lot more different stages where I might need the combination. So every time I would need to generate all the combinations.

I have also thought about creating key-value pair type table, where I would keep the combination as a string. But in this approach I am not actually reducing number of rows to be inserted rather number of columns is getting reduced.

So my question is - Is there any better approach this kind of situation where I can keep track of combination and manipulate in an optimized way?

Note - I am not sure if this would help or not, but a lot of the rows in the values table will probably have zero as value. So in the second phase we would need to show a lot less rows than the actual number of possible combinations

Unity. Different interface versions for different platforms

There is a rather large project on Unity, in which there are many different UI windows, elements. There was a problem with two versions of the interface (one for PC, one for phones). How in this case to organize all this? I think divided into scenes: Init (manager initializer), Core (all game managers), UI_Win, UI_Mobile. Only with the full independence of all these scenes. Do I have the right thoughts? Or can it be split into one UI window by one scene: (Scenes / UI_Mobile / AuthScene, SettingsScene)? Which option is preferable? Or there are other options you have.

PS: Google Translate

Design pattern recommendation needed

I need to create new file with new specifications each time for a new integratoon.which design pattern is best suitable for this.each time a new method is needed so as to implement a new file as it's different.

Way to segregate data with components

My react.js components get data from separately hosted graphQL service. Currently, the components are tightly coupled with service's schemas. For ex: component need item-name and read it from response.items.item[0].name.

Now, I have to change the source service and schema for this new service is quite different. For ex: item-name is now present in response.products.product[0].item.name.

I want to have some confidence with this service migration. Ex: item-name is same and present with new source service.

I wish to have this data source migration to be testable at data level rather than leaking the schemas to component level. Two questions -

  • Is there any general pattern to hold source data at one place and use wrappers in components?
  • How to test it side-by-side with old versus new data services?

Spring Rest API Design pattern

I got requirement for design a Rest API with spring boot. Once we designed the API completely , don't touch the rest API entry point in future or any further enhancement even adding new rest API endpoint. Instead of touching rest API entry point class, we have to use other Java class for customisation or adding new API by dynamically.

I'm wondering how to do this stuff.

Please help me what design pattern used for this scenario...

How add multi database to UnitOfWork and generic repository in Entity Framework

I have a Windows Forms application and generic Entity Framework (latest version) method and multi-layer design pattern.

i was write this code . load first db is good but cant load second db and shiow this error : Invalid object name 'dbo.Section'.but dbo.section is exist

Repository layer:

private readonly DbSet<T> dbSetGlobalERP;
    private readonly DbSet<T> dbSetHamkaranSystem;        
    private T Entity;
    private IEnumerable<T> Entities;

public Repository(GlobalERPEntities dbcontextGlobalERP, HamkaranSystemEntities dbcontextHamkaranSystem)
{
    base.dbContextGlobalERP = dbcontextGlobalERP;
    dbSetGlobalERP = base.dbContextGlobalERP.Set<T>();

    base.dbContextHamkaranSystem = dbcontextHamkaranSystem;
    dbSetHamkaranSystem = base.dbContextHamkaranSystem.Set<T>();
}

   public virtual IEnumerable<T> GetAll()
    {
        return dbSetGlobalERP.ToList();
    }

    public virtual IEnumerable<T> GetAll2()
    {
        return dbSetHamkaranSystem.ToList();
    }

UnitOfWork layer: call get all method from repository layer

public UnitOfWork(GlobalERPEntities dbContextGlobalERP, HamkaranSystemEntities dbContextHamkaranSystem)
{
    base.dbContextGlobalERP = dbContextGlobalERP;
    base.dbContextHamkaranSystem = dbContextHamkaranSystem;
}       

public IRepository<T> Repository<T>() where T : class
{
    if (repositories == null)
    {
        repositories = new Dictionary<Type, object>();
    }

    if (repositories.Keys.Contains(typeof(T)) == true)
    {
        return repositories[typeof(T)] as Repository<T>;
    }
    Repository<T> repo = new Repository<T>(dbContextGlobalERP, dbContextHamkaranSystem);
    repositories.Add(typeof(T), repo);
    return repo;
}

 public bool SaveChanges()
    {
        bool returnValue = true;
        using (var dbContextTransaction = dbContextGlobalERP.Database.BeginTransaction())
        {
            try
            {
                dbContextGlobalERP.SaveChanges();
                dbContextTransaction.Commit();
            }
            catch (Exception)
            {
                returnValue = false;
                dbContextTransaction.Rollback();
            }
        }
        return returnValue;
    }

BLL layer: call get all method from UnitOfWork layer

private readonly IUnitOfWork unitOfWork;
public static List<HRPersonView> personFullName = new List<HRPersonView>();

public Service_HR_Person(IUnitOfWork unitOfWork)
{
    this.unitOfWork = unitOfWork;
    FillList();
}

public virtual IEnumerable<HRPerson> GetAll()
{
    return unitOfWork.Repository<HRPerson>().GetAll().ToList();
}

public virtual IEnumerable<Section> GetAll2()
{
    return unitOfWork.Repository<Section>().GetAll2().ToList();
}

how add multi database to this pattern?

vendredi 24 mai 2019

How do I validate multiple inputs for a function?

I have a "Validator" class which allows us to set values of its member variables (mostly boolean) - mv1, mv2, mv3 etc. with setter methods. Lets call all these variables "settings". All the setter methods return this Validator instead of the usual void.

The Validator has a validate(Input input) method which takes an "Input" object and validates it based on the values of settings of Validator. There are some dependencies between the various settings. For example, if mv1 = true, then mv3 cannot be true etc. Also, I cannot always use enums to restrict the values of the settings !

I validate all the inputs with validateInputs(). The validate(Input input) calls it before doing the validation. I want to find out all the invalid inputs, display them all at once and then prevent the validation until the inputs are fixed. What is the best way to do this in Java ?

What did I try ?

I don't want to throw an IllegalArgumentException right after I find the 1st setting with invalid value. I want to avoid writing custom code which will handle these exceptions and then list them all at once. I also don't want to use Java's assert because it can be disabled at run time.

To solve my problem, I simply use TestNg library's SoftAssert to validate the member variables. The code inspects some of the the member variables, asserts that the variables have valid values and finally does softAssert.assertAll() to list all the wrong values at once. But, I wonder if Java has any in-built features to do this.

class Validator {

//Validator settings
boolean mv1;
boolean mv2;
MyEnum mv3;
boolean mv4;...etc.

//Setters - One example.
public Validator setMv1(boolean ){
this.mv1 = mv1;
return this;
}

//Validation logic
public void validate(Input input){
validateSettings();
//Now, validate the input.
}

//Validate the settings of this Validator.
private void validateSettings(){
SoftAssert assertz = new SoftAssert();//From TestNg library.
//No need to validate all settings ! Only some needed.
//Assert that if mv1 = true, then mv3 can't be true;
//Assert other things.
assertz.assertAll();
}

}

How to make big classes more elegant?

In my Objective-C app some view controllers have dozens of IBOutlets and 40+ methods. It's getting really hard to read through the code. I tried to limit the number of properties and methods by declaring them in separate controller classes.

Is there some good practice to limit the amount of code in a class or do I have to just accept it as my class has many tasks to control ?

jeudi 23 mai 2019

Parameter transfer for Class called within another Class

My problem is that I have a Class A with some Parameters that I use in a few other Classes but during initializing one of these Classes I always have to set the parameters for Class A as well. I not know how to solve these redundancies. Let me give you an example.

I have a big dataset that I reduce, using some calculations to one column depending on some input parameter

Class ColumnCreator
    Sub New(a,b,c,d)

This ColumnCreater is a Class I use in different other Classes. E.g. for a special Report:

Class SpecialReport
    Sub New(e,f,g,a,b,c)

    Sub Create_Columns()
        dim myColumn = ColumnCreator(a,b,c)

I created a GUI so a User can create his own report depending on the arguments he sets. BUT I always have to set the Parameters a,b,c that I need for the Create_Columns Class in the Constructor of the Class that uses these Class as you can see in the constructor of SpecialReport New(...,a,b,c). This must be a problem many programmers are facing and I do not know how to handel this. My first Idea was to write some kind of Parameter Container Class.

Class ParContainer
    Sub(a,b,c)

But this does not make the code better at all. I hope I made myself clear. Any ideas how to solve this? C# code is ok too.

How do I organize a UI hierarchy and inform elements of events correctly?

Libraries like GLFW only inform the using programmer through certain callbacks of the type of "This is where the mouse moved: (x,y)" about userinput.

A "TLDR what is your meta-question?" ahead of time: Is there any tutorial, guideline, handbook or any other resource on what the implementors of software or frameworks like, Java Swing, JavaFX, QT, SWT, GTK, etc. thought, deliberated and decided on when it came to implementing their GUI toolkit / library /framework? Where can I find people that think about this stuff?

Going from here, getting the (x,y) coordinates of the mouse curser, calculating the difference from the previous instance of the call to get a (dx, dy) value, I would need to now inform UI Elements in my UI of what has happened so they can be updated accordingly.

The first question is, what kind of special UI Elements can exist in a generalized UI?

As one wants to organize their UI in a - possibly deep - hiearchy, the UI managing system only knows of a few top-level UI Elements. Because there are a lot of different ways to represent and order the UI Elements internally, the generalized UI Element type only supports answering one question: "What is the UI Element below this (x,y) coordinate for you?" (from now on called: get_hotspot(x,y) ). A UI Element that is not at this position will answer "Nothing", while a UI Element that is itself directly below the mouse cursor would return itself and a UI Element containing sub-elements that are themselves below the mouse-cursor would return the sub-element beneath if it is the case or itself if not.

In terms of what "special" UI Elements exist that need to be tracked separately, I can think of the following:

  • The Element directly below the mouse cursor: The HOTSPOT
  • The Element the user started a mouse-click on (but did not release yet): One DRAGGED Element for each mouse-button. Should this rather be called a GESTURE SOURCE Element?
  • The Element that receives Keyboard or Gamepad Input, the FOCUS

Organization like this would allow me to direct all non-motion mouse events to the hotspot - if one exists - or discard them if there is none below the mouse at all.

The only special cases are informing the elements on which were a gesture, with any mouse buttons, started of the motion of the mouse outside their boundaries, as this information might be interesting for them. They also need to be informed if, when and where a gesture that started on them ended.

The most complicated function therefore is the callback of the mouse-motion "event" (there is no event-wrapping yet here, this is bare bones): Before anything happens all the DRAGGED elements need to be informed of the motion.

After this I'd need to manage the current HOTSPOT, if it exists: - The mouse could have simply moved within its boundries. - The mouse could have moved outside of its boundries. - The mouse could have moved into an UI Element inside the boundries of the current hotspot.

The last case is confounding for me because of all the different cases that can happen here and need to be considered:

  • The mouse did not LEAVE the previous HOTSPOT, it just entered a new Element INSIDE of the previous one, so informing the previous HOTSPOT of the mouse leaving would be erroneous here.
  • If the mouse enters an element and at the same time enters a sub-element (because the borders of the two elements are the same for example) then both the containing and the contained elements need to be informed of the mouse entering them. This is difficult if the get_hotspot(x,y) function returns only the hotspot directly beneath the questioned element because the overlaying UI manager would never know that two whole elements were just entered by the mouse. Using a STACK of HOTSPOTS (explained below) would cause the STACK to be erroneous in case this happens.

Similar confounding issues arise when an element is left by the mouse:

  • Did the mouse leave the element into its parent? If so the parent does not need to be informed that the mouse now entered it because it never left.
  • Did the mouse leave the element AND its parent at the same time? If so the parent does need to be informed of the mouse leaving, too.

This second confoundment leads me to believe that using a STACK of HOTSPOTS is a way to deal with these questions. If an event needs to be processed by a child-entitiy I'd inform it of the mouse having left, pop it from the stack and then recursively call the notification routine again so the next element on the stack is informed until nothing else changes.

Other questions arise like:

  • Should an "enter"-notification be immediatly followed by a "move"-notification onto the very element the mouse just entered or should the motion be dispatched to it only upon the very next time the mouse is moved WITHIN the new HOTSPOT?

With this PREAMBLE complete I can provide some code of how I had deviced an INTERFACE for the UI Manager (Here in C++):

// Focus Management for Keyboard Focus
    void request_focus(UI::Element &focus);
    void release_focus();

//Drag and Drop
    void attach_element(MouseButton button, UI::Element &drag);
    void release_element(MouseButton button, UI::Element &drag);

//Callback functions from GLFW
    virtual void notify_movement(int x, int y, int dx, int dy, input::Mouse &from);
    virtual void notify_press(int x, int y, int button, input::Mouse &from);
    virtual void notify_release(int x, int y, int button, input::Mouse &from);
    virtual void notify_scroll(int x, int y, int dx, int dy, input::Mouse &from);

    virtual void notify_key_press(int key, int scancode, int mods, input::Keyboard &from);
    virtual void notify_key_release(int key, int scancode, int mods, input::Keyboard &from);
    virtual void notify_key_repeat(int key, int scancode, int mods, input::Keyboard &from);

    virtual void notify_typed(int codepoint, input::Keyboard &from);

//API to be used by the scene-manager
    void add_element(UI::Element &element);
    void remove_element(UI::Element &element);

//Keeping track of:
    std::set<UI::Element *> elements; //all top-level elements

    std::stack<UI::Element *> hotspot_stack;
    UI::Element *current_focus;
    UI::Element *current_dragged; //for left mouse button - repeat for all other supported mouse buttons ...

With the UI Elements having to support the following API:

    virtual void notify_motion(int x, int y, int dx, int dy, UI::UserInterface &from);
    virtual void notify_drag(int x, int y, int dx, int dy, int button, UI::UserInterface &from);

    virtual void notify_press(int x, int y, int button, UI::UserInterface &from);
    virtual void notify_release(int x, int y, int button, UI::UserInterface &from);

    virtual void notify_drop(int x, int y, int button, Element *dragged, UI::UserInterface &from);
    virtual void notify_scroll(int x, int y, int dx, int dy, UI::UserInterface &from);

    virtual void notify_key_press(int key, int scancode, int mods, UI::UserInterface &from);
    virtual void notify_key_release(int key, int scancode, int mods, UI::UserInterface &from);
    virtual void notify_key_repeat(int key, int scancode, int mods, UI::UserInterface &from);

    virtual void notify_typed(int codepoint, UI::UserInterface &from);

    virtual void notify_enter(int x, int y, UI::UserInterface &from);
    virtual void notify_leave(int x, int y, UI::UserInterface &from);

    virtual void notify_focus_gained(UI::UserInterface &from);
    virtual void notify_focus_lost(UI::UserInterface &from);

    //Looking deep into the Code of JFX I mentioned one can also support:
    virtual void notify_dragged_over([...]);

Why was all this thought put into it? Well if you have a ui-button that the user presses and holds with the left mouse button, then drags the mouse away from the mouse button, does NOT release the mouse button, reenters the ui-button within the same gesture and THEN releases the left mouse button, the button needs to be considered clicked, while the button needs to change states from "IDLE" to "FOCUSED" to "DEPRESSED" to "IDLE" (upon leaving) back to being "DEPRESSED" (upon reentering in the same motion)! (You can try this out for example on reddit when you do the motion mentioned above on the "fold down" buttons next to a post's meta-data).

And now for the actual question related to the title of this question:

Did I miss something? Do I think something horribly wrong? Is this approach at all feasable or is there some general way to do it that is accepted since the times of Windows 3.1 and I just can't find where this information is located?

How do I organize a UI hierarchy and inform elements of ALL events happening CORRECTLY?

Hysterix Request Cache Design

I am trying to read up on some code to study design patterns and I came across Hysterix. I am reading this class HysterixRequestCache and it does something particular. This class is a static factory class which creates an instance of itself with the method getInstance(), but the thing I am really confused about it that it also creates a concurrenthashmap that caches itself . What design pattern is this and what is the benefit of doing it this way?

https://github.com/Netflix/Hystrix/blob/master/hystrix-core/src/main/java/com/netflix/hystrix/HystrixRequestCache.java

Handle IoC configuration with shared dependencies between projects

I've a root project (root), some modules (A, B), and these modules have some external dependencies (Z). I'm using an IoC container.

I'm using C# here, but is a generic pattern question. Let say that my container is services, and I can initialize IoC configuration with use of extension methods. So in root project I'm writing:

services.AddModuleA();
services.AddModuleB();

On module A I've this method:

public static void AddModuleA(this IServiceCollection services)
{
    // Init module internal services.
    //services.AddScoped<IA1Service, A1Service>();
    //...

    // Init module external dependencies.
    services.AddDependencyZ();
}

On module B I've a similar method:

public static void AddModuleB(this IServiceCollection services)
{
    // Init module internal services.
    //...

    // Init module external dependencies.
    services.AddDependencyZ();
}

Obviously Z dependency was already been added, so this tells me that I should not configure it inside a module extension method, and I should rather declare its configuration in root project:

services.AddModuleA();
services.AddModuleB();
services.AddDependencyZ();

But doesn't this break the Least Knowledge principle? Importing and configuring a module A (or B) will bring to a cascade explicit declaration of all dependency configurations.

And related question, is declaring the extension methods AddModuleA() and AddModuleB() a bad pattern at all? Could be a better idea to configure directly on root only services that I will use? And in this case (a bit extreme), what about config of internal use only class?

How to modify Event in EventBus Design Pattern in java

I have a series of EventHandler which listens to the Events published by the EventBus. Now I have a usecase where I have to modify the event in one of the EventHandler and other consecutive handlers in the list may/may not get triggered on the basis of the modified event.

Are there better ways of doing Event Handling or design Patter which can be used for Event Handling.

Builder pattern for unit tests exposing properties to internal dependencies

I am using the builder pattern in my unit tests and I have come to a situation where I need to verify the behavior (with Moq verify) of a dependency that leaves inside the the builder.

The way I designed the builder, this dependency is hidden in the builder class for easier object creation. However, now my test method cannot access the mocked object for verification.

I thought about two different approaches, but not sure what would be the most common used in builder pattern:

Option 1: Expose mocks as a builder property.

//Setup
var equipment = equipmentBuilder
            .AddDevice("Device1")              
            .Create();

//act
equipment.SomeMethod();

//Verify
equipmentBuilder.DeviceStubs.ElementAt(0).Verify(v => v.Method(), Times.Once);

or inject dependencies on the builder methods

//Setup
var deviceStub = new Mock<Device>();
deviceStub.Setup(x=>x.Name).Returns("Device1");

var equipment = equipmentBuilder
        .AddDevice(deviceStub)
        .Create();
//Act
equipment.SomeMethod();

//Verfiy
deviceStub.Verify(v => v.Method(), Times.Once);

For me the second approach looks more robust with things more isolated. However, the construction of the equipment objects will have more code. In case I have several test methods, this will be a lot of extra code.

What would you do? A third option maybe...

Thanks.

C# Pattern Overlay and load image

I try to write a Window Form app for desktop with C#.

Window Form app function is load image and do image overlay like photoshop.

But I don't know how to load image outside function like:

enter image description here

I know C# has OpenFileDialog class can create function like photo below.

But I still need to create a struct to load image need image name or image ID for my function to call image to use.

Like C# property.resource.image(call my image name)

And I also face one more issues like How to achieve Image Ovelay

In C# I can just use panel and pictureBox to achieve put pictureBox on panel.

And Set panel backColor Transparent.

But In my Window Form something wrong.

Here is my code:

private void AddNewPhotoToolStripButton_Click(object sender, EventArgs e)
        {
            /*
            var fileContent = string.Empty;
            var filePath = string.Empty;

            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "c:\\";
                openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                openFileDialog.FilterIndex = 2;
                openFileDialog.RestoreDirectory = true;
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    //Get the path of specified file
                    filePath = openFileDialog.FileName;

                    //Read the contents of the file into a stream
                    var fileStream = openFileDialog.OpenFile();

                    using (StreamReader reader = new StreamReader(fileStream))
                    {
                        fileContent = reader.ReadToEnd();
                    }
                }//end if
            }
            MessageBox.Show(fileContent, "File Content at path: " + filePath, MessageBoxButtons.OK);
             */
            Panel backGround = new Panel();        
            backGround.Location = new System.Drawing.Point(67, 57);
            backGround.Size = new System.Drawing.Size(800, 480);
            backGround.BackgroundImage = Properties.Resources.fullground;
            backGround.BackColor = Color.Transparent;
            Controls.Add(backGround);
            backGround.BringToFront();
        }

        private void OvelayPhotolStripButton_Click(object sender, EventArgs e)
        {
            PictureBox a =new PictureBox();            
            a.Location = new System.Drawing.Point(200, 107);
            a.Size = new System.Drawing.Size(200, 50);
            a.BackgroundImage = Properties.Resources.needle;
            a.BackColor = Color.Transparent;
            Controls.Add(a);
            a.BringToFront();
        }
    }

So far I am not doing openFileDialog so I comment it and use resource to load image.

I can't achieve photo overlay by set panel backColor to transparent

the result is ike Photo below

enter image description here

All my fullGround and needle images are .png file but it can't achieve photo overlay.

How can I solve these two problems?

1.Create a function to load image like first image show and load in my struct to use?

2.Solve Photo overlay?

Thanks

Is this correct usage of Builder pattern

I have a scenario like this:

The system handles reservations from couple of different sources. All bookings come in the form of a json with differing formats for each source. Some JSON attributes are present in one JSON and not in the other etc.

In order to enter the reservation into the system, I am trying to centralize the Add Reservation logic into one method. To do this, I am trying to create a class called Reservation using the Builder pattern as such:

<?php

namespace App\Business\Classes\Reservation;


use App\Business\Classes\Utils\ReservationUtils;

/**
 * Class Reservation
 * Holds entire reservation details
 * @package App\Business\Classes\Reservation
*/
class Reservation
{
    protected $reference, $otaReference, $hotelCode, $customerId, $guestName, $couponId, $checkin, $checkout, $guests, $customerCountry,
    $commissionRate, $paymentStatus, $commissionOta, $commissionDifference, $rooms = [], $cityTax, $vat, $serviceCharge, $geniusBooker = false,
    $geniusAmount = 0, $taxes, $taxIncluded = false, $supplierAmount, $totalAmount, $specialRequest, $currency, $deviceType, $bookingSource,
    $otaRefId, $status, $source, $remarks;

    public function __construct()
    {
        // generates a reference
        $this->reference = ReservationUtils::referenceGenerator();
    }

     /**
      * @param mixed $otaReference
      * @return Reservation
     */
     public function setOtaReference($otaReference): Reservation
     {
        $this->otaReference = $otaReference;
        return $this;
     }

     /**
      * @param mixed $checkin
      * @return Reservation
     */
     public function setCheckin($checkin): Reservation
     {
        $this->checkin = $checkin;
        return $this;
     }

     /**
      * @param mixed $checkout
      * @return Reservation
     */
     public function setCheckout($checkout): Reservation
     {
        $this->checkout = $checkout;
        return $this;
     }

     /**
      * @param array $rooms
      * @return Reservation
     */
     public function setRooms(array $rooms): Reservation
     {
        $this->rooms = $rooms;
        return $this;
     }
     // and so on....
}

And I would use it like this:

$data= json_decode($result->jsonData);
$reservation = (new Reservation())
                  ->setOtaReference($data->otaReference)
                  ->setCheckin($data->checkin)
                  ->setCheckout($data->checkout); //...etc

This is probably not the textbook usage of the builder pattern in PHP or even Java but is there anything wrong with it?

Thanks

mercredi 22 mai 2019

Extending, Abstraction, Interfaces... Method Relationships between Classes designed for Scale

Curious as to someones opinion who's been through this rather steep curve in that of proper OOP design principles, into more advanced techniques of class relationships -- class inheritance, abstract classes, interfaces, traits, so on.

Me? First OOP project. Learning as I go. I've refactored, switched around, completely remodified my methods more time than I care to remember. Painful yet rewarding at the same time. Okay, enough of an intro, let's get into the meat of where I'm at.

PROJECT GOAL

Using chained curl responses to return the HTML of the requested page, pass that on to a DOM Class Handler which handles the parsing and extracting of sought information. This parsed information is then loaded into a DatabaseClass, which uses the information retrieved from the DOM parsing requests to appropriately store the data into the appropriate Database tables QL database.

I've only 3 Classes. Brief description immediately below each Class.

Class CurlHandler     {
//Methods to download data and images using cURL

Class DOMHandler      {
//Methods to parse the DOM from the cURL Results

Class DatabaseHandler {
// Methods to insert into a Database particular Data received from the DOM 

Here's the list of methods used in the class. I designed it as, for good or ill) an interface, providing for a more compact type for those with constantly changing the Dynamics

interface DOMInterface
{
    public function getNotice(\DiDom\Document $document): int;
    public function getStock(\DiDom\Document $document): int;
    public function getUPC(\DiDom\Document $xpath): int;
    public function getTitle(\DiDom\Document $document): int;
    public function getCurrentPrice(\DiDom\Document $document): int;
    public function getMSRP(\DiDom\Document $document): int;
    public function getPriceDiscount(\DiDom\Document $document): int;
    public function getImages(\DiDom\Document $document): int;
    public function getAttributes(\DiDom\Document $document): int;
    public function getTags(\DiDom\Document $document): int;
    public function getAttributes(\DiDom\Document $document): int;
    public function getLink(\DiDom\Document $document): int;
    public function pageCheck(int $page, int $pagelength): int;
}

And below are the ones I left out in the Interface, as these functions are more or less as is, static and designed to work in universal applications..

class DOMController implements DOMInterface 
{
public function setup (string $html);
public function write (string $file, string $producturl);
public function writeJSON (array $json, string $proxy, string $dir)
public function writeHTML (string $html, string $proxy,  string $dir)
}

As I stated earlier, aside from the obious reasions, one of the main reasons I get this down is crucial is scalability. As this project resolves around the parsing of different datasources and websites, my Classes must be conformed in a way that another website (Class) can easily be added and organized in an affluent way.

My other Classes are similar. I feel this post has reached close to it's maxim so I'll conclude, the similiarty between universal and specific are logical seperators that I've found, there's bound to be something I'm unaware of.

Tips, comments, why I'm wrong, how to be right.. I'd appreciate it. It's been a tough ride getting to this point.

Please suggest to print Number pattern in java

Please help to print the following pattern in java 1 3 4 6 7 8 10 11 12 13 15 16 17 18 19

Postgresql pattern matching

I want to get datas starting name and surname with 'Ib' But result shows just name starting with 'Ib'

select* from student where concat(name,surname) like '%Ib';

Job queue with job affinity

I am currently facing a problem for which I am pretty sure there is an official name, but I don't know what to search the web for. I hope that if I describe the problem and the solution I have in mind, somebody is able to tell me the name of the design pattern (if there is one that matches what I am going to describe).

Basically, what I want to have is a job queue: I have multiple clients that create jobs (publishers), and a number of workers that process these jobs (consumers). Now I want to distribute the jobs created by the publishers to the various consumers, which is basically doable using almost any message queue with load balancing across a queue, e.g. using RabbitMQ or even MQTT 5.

However, now things get complicated... every job refers to an external entity, let's say a user. What I want is that the jobs for a single user get processed in order, but for multiple users in parallel. I do not have the requirement that the jobs for user X always go to worker Y, since they should be processed sequentially anyway.

Now I could solve this using RabbitMQ and its consistent hashing exchange, but then I have a data race when new workers enter the cluster, because RabbitMQ does not support re-locating the jobs that are already in a queue.

MQTT 5 does not support this either: Here this idea is known as "sticky shared subscriptions", but this is not official. It may be part of MQTT 6, or it may not. Who knows.

I have also taken a look at NSQ, NATS, and some other brokers. Most of them don't even support this very specific scenario, and those that do use consistent hashing, which has the previously mentioned data racing problem.

Now, the problem would be gone if the broker would not sort the jobs into queues, once the jobs arrive, but if it would track if a job for a specific user is already being processed: If so, it should delay all other jobs for this user, but all jobs for other users should still process. This is, AFAICS, not possible using RabbitMQ et al.

I am pretty sure that I am not the only person with a use case for that. I could e.g. think of users uploading videos to a video platform, and although uploaded videos are processed in parallel, all the videos uploaded by a single user are processed sequentially.

So, to cut a long story short: Is what I describe known under a common name? Something such as distributed job queue? Task dispatcher with task affinity? Or anything else? I have tried lots of terms, but didn't succeed. This may mean that there is no solution for this, but as said, it's hard to imagine that I'm the only person on the planet with this problem.

Any ideas what I could look for? And: Are there any tools that implement this? Any protocols?

PS: Just using a predefined routing key is not an option, since the user ids (which I just used as a made-up example here) are basically UUIDs, so there can be billions of it, so I need something more dynamic. Hence, consistent hashing is basically the correct approach, but as said, the distribution has to work piece by piece, not upfront, to avoid data races.

Cascade calls on override virtual methods

I'm working on a large software, that heavily relies on the call supper antipattern.

Basically, an interface defines an "init()" virtual method that is then overridden in every classes that inherits it. When init() is called on the class, EVERY overloaded init methods are cascaded, from the base class to the top daughter class, and all in between.

But the user HAS to call its direct parent's init() method in its own, which results in code like this:

class myClass : public Base
{
    virtual void init()
    {
        Parent::Init() // often forgotten, or misplaced by the developer
        // Do some init stuff
    }
}

An alternative to this is usually to use delegates. The Base class has stuff to do in init, that is declared final in Base, and delegates part of it to an "onInit()" method that inheriting classes should override. But this does not cascade the calls to all parent classes as I'd like it to.

The alternative I've first implemented is a variant of the delegate approach. Both daughter classes and Base implement a onInit() and a init() method. init() calls Parent::init() followed by a call to onInit() on itself, and is auto-generated uing template metaprogramming & macros. and onInit() contains the class-specific code.

# define DELEGATE(T, Parent) \
     virtual void init() { Parent::init(); T::onInit(); }

struct Base
{
    virtual void init() { onInit(); }
    virtual void onInit() {}
};

struct A : public Base
{
     DELEGATE(A, Base)
     virtual void onInit() { /* MyCustom code for A */ }
}

struct B : public A
{
     DELEGATE(B, A)
     virtual void onInit() { /* MyCustom code for B */ }
}

This works pretty well.. except that multiple inheritance becomes a mess, and even if handled, diamond inheritance causes issues with duplicated calls.

Which leaves me wondering: I can't be the only person looking for a design pattern solving my issue, and the stackoverflow community must know about it :)

Have you ever encountered a design pattern for this? I'm really looking forward to your ideas!