samedi 31 octobre 2020

Can we give a concreate class an interface after the concreate class is built?

I'm learning the software design currently, for the observer pattern, according to my notebook, I need an observer interface, a concrete observer class; a subject interface, a concrete subject class. However, if I currently do not have an interface for the observer, is that necessary I give it an interface? (i.e are all the 4 interfaces mandatory in the observer pattern)

How to print the following pattern in java? [closed]

Sample Input:

4

Sample Output:

1 2 3 4 5 6 7

1 2 3 4 5

1 2 3

1

What is the best way to set object properties when filling a complex form in React

I'm new in React. I have what seems like a standard task: fill in the form data about a user and send it to the server. The form is a set of components, such as: Basic information, Passport data, Hobbies, etc. + Save button.

I did it in the following way. There is a class describing the model. When creating a component, I create an instance of this class in useRef. Further, I pass this model variable to all child components through their props. Model properties are populated in components. So when I click on the Save button I have the model properties filled in. Here's an example.

Please tell me, is this a good approach for filling in the data of a complex object? Maybe it's better to do it different way? Are there any best practices? Maybe I should use redux for this task?

model.ts

 class Model {
      // Component 1
      firstName: string;
      lastName: string;
    
      // Component 2
      passport: string;
      address: string;
    }
    
    interface IComponent {
      model: Model;
    }
    
    export { Model, IComponent };

index.tsx

export const App: React.FunctionComponent<{}> = () =>
{
 const model = useRef<Model>(new Model());

 const save = () =>{
   console.log(model.current);
 }

return (
  <React.Fragment>
    <Component1 model={model.current} />
    <Component2 model={model.current} />
    <button onClick={save}>Сохранить</button>
  </React.Fragment>
);
}
render(<App />, document.getElementById('root'));

Component1.tsx

export const Component1: React.FunctionComponent<IComponent> = ({ model }) => {

  const [firstNameValue, setFirstNameValue] = useState(model.firstName);
  const [lastNameValue, setLastNameValue] = useState(model.lastName);

  const changeFirstName = (e: React.ChangeEvent<HTMLInputElement>) => {
      model.firstName = e.target.value;
      setFirstNameValue(e.target.value);
  }

  const changeLastName = (e: React.ChangeEvent<HTMLInputElement>) => {
      model.lastName = e.target.value;
      setLastNameValue(e.target.value);
  }

  return (
  <React.Fragment>
   <div>
    <label htmlFor="firstName">FirstName:</label>
    <input name="firstName" value={firstNameValue} onChange={changeFirstName} />
   </div>
   <div>
    <label htmlFor="lastName">LastName:</label>
    <input name="lastName" value={lastNameValue} onChange={changeLastName}/>
   </div>
  </React.Fragment>);
};

Component2.tsx

export const Component2: React.FunctionComponent<IComponent> = ({ model }) => {
   const [passportValue, setPassportValue] = useState(model.passport);
   const [addressValue, setAddressValue] = useState(model.address);

  const changePassport = (e: React.ChangeEvent<HTMLInputElement>) => {
      model.passport = e.target.value;
      setPassportValue(e.target.value);
  }

  const changeAddress = (e: React.ChangeEvent<HTMLInputElement>) => {
      model.address = e.target.value;
      setAddressValue(e.target.value);
  }

  return (
  <React.Fragment>
   <div>
    <label htmlFor="passport">Passport:</label>
    <input name="passport" value={passportValue} onChange={changePassport} />
   </div>
   <div>
    <label htmlFor="address">Address:</label>
    <input name="address" value={addressValue} onChange={changeAddress}/>
   </div>
  </React.Fragment>);
};

Screenplay pattern - common methods among actions

I'm currently trying out the screenplay pattern. My question regards how to deal with common methods across several actions?

So as an example I have a method for my homepage actions that looks if a checkbox is checked. If the checkbox is not checked it checks the checkbox. If it is checked it does nothing and move to the next step. Now this type of method is needed in other action classes aswell.

My question is what is the best approach to keeping DRY in this case? Should I implement a helper class and create an instance of that class in the action classes that require that method? Or should I create a base class and have my action classes inherit from that? Or is there a better approach altogether?

I want to work according to SOLID but i'm not sure what the best approach is in this case.

Implementing Screenplay pattern for automated testing in swift

I'm currently learning the screenplay pattern but i'm having trouble with the Given keyword. For my current use case it seems that it should be a question.

Given(user).has(OpenedTheApplication.successfully())

has is defined as a task

func has(_ task: Task) {
    perform(task)
}

The gherkin keyword is defined as follows:

class Given: GherkinKeyword {
    func has(_ task: Task) {
        actor.has(task)
    }
}

So if I understand screenplay correctly then tasks should not create a query about the state of the system.

So rather I would like to define this:

Given(user).wasAbleTo(OpenTheApplication.toTheHomePage())

and then

func wasAbleTo(_ question: Question) {
    ask(question)
}

and the gherkin keyword is updated too:

class Given: GherkinKeyword {
    func has(_ task: Task) {
        actor.has(task)
    }
    func wasAbleTo(_ question: Question) {
        actor.wasAbleTo(question)
    }
}

is this a correct way of thinking for asserting that the application was launched correctly?

How to design a class holding a collection and a map which associates further data to some elements of the collection?

This is mostly a design question, so maybe it's best I state it explicitly here: in the following I describe a class I'm designing and some concerns I have about my design choices; I'd like to no if there's already some design pattern or, in general, a "way of doing it" which I am not aware of.

I need to write a class MyClass { /* ... */ };

  • representing an ordered collection of "things", which can also be repeated,
  • some of which have another "piece" of information associated to them.

For simplicity, let's say that the "things" are ints and the "piece" too is an int.

As regards the first point, I'm pretty sure a std::vector is fine, as I don't need to reorder the entries, to insert at the front, or things like these. Therefore a good start seems to be

class MyClass {
    std::vector<int> v;
    // ...
};

As regards the second point, however, I'm a bit puzzled about how to do that.

Since I need to associate something else to some elements of v, it seems natural that a use a map for that, for instance a std::unordered_map. However, since the ints in v can be repeated (v could be {1,2,2,2,3,4,0,3,2}), I cannot use them as the keys. Therefore maybe I could use their addresses, and so the class could be like this:

class MyClass {
    std::vector<int> v;
    std::unordered_map<int*, int> m;
};

However I feel this opens to a lot of issues or bugs down the road, due to this class explicily dealing with pointers. Well, not even that down the road, actually. The simple fact of delegating the construction of v and m to other function(s) could trigger UB if the the std::vector from which the addresses are taken is copied into v rather than moved.

Design pattern for slightly changed classes

I have 3 classes. All classes are very similar but their implementation slightly differs.

class StrategyA {
  double do() {
    double d = method1();
    method2();
    return method3(d);
  }
}

class StrategyB {
  double do() {
    double d = method1();
    method2();
    return method4(d);
  }
}

class StrategyC {
  double do() {
    double d = method1();
    method3();
    return method4(d);
  }
}

All classes are very similar, most of the logic is the same, but at the end of implementation all classes have slightly different return method. This is only example with single method, there are much more duplicate logic.

How to reduce this implementation to avoid duplication?

vendredi 30 octobre 2020

My code giving the same expected output but tester is marking It incorrect?

I have posted my code below which is in fact giving the same output as expected.Please help me with this problem as I am constantly experiencing this type of problems in other platforms also such as HackerRank and HackerEarth etc...I think this type of problems arises as the tester instead of Evaluating the Final output evaluates the Code thereby limiting the scope of Creativity.I am currently a beginner in coding any help will be highly appreciated.

Expected pattern my code output

#include <stdio.h>int main()
 {
int num;int i=1,j,x;
scanf("%d", &num);                          
x=num-1;
printf("Input number is %d.\n", num);       
for(i=1;i<=num;i++)
{
    if((i==1)||i==num)
    {
        for(j=1;j<=num;j++)
        {
            printf("*");
        }
    printf("\n");
    x--;
    }
    
    else
    {
        for(j=1;j<=x;j++)
        printf(" ");
        printf("*");
        printf("\n");
        x--;
    }

    
}

}

Command Pattern?

I keep running into the same problem, and I'm still not sure the best way to solve it.

Scenario: A set of command objects, and a manager to execute the commands.

Command:

The interface that defines the Command contract.

public interface Command {
  
  public String getSignature;

  public Results execute(Object stuff);

}

Command implementation:

One or more objects that implement the Command interface.

public class KillCommand implements Command {
    
    public String getSignature() {
        return "kill";
    }

    public Results execute(Object stuff) {
        do stuff...return results...
    }
}

Manager:

A manager that knows of all the commands, and accepts a signature to run one of the commands.

Bad manager:

public class CommandManager {
  
     private List<Command> commands;

     public CommandManager(List<Command> commands) {
          this.commands = commands;
     }

     public Results executeCommand(Object stuff, String signature) {
      
         for (Command command : commands) {
             if (command.getSignature().equals(signature)) {
                  return commmand.execute(stuff);
             }
         }
    }
}

Better Manager:

public class CommandManager {
  
     private Map<String,Command> commands = new HashMap<>();

     public CommandManager(List<Command> commands) {

          for (Command command : commands) {
              this.commands.put(command.getSignature(), command);
          }
     }

     public Results executeCommand(Object stuff, String signature) {
      
         this.commands.get(signature).execute(stuff);
    }
}
     

My question, what is the best way of solving this scenario? Is there a design pattern/industry norm to solve this scenario?

Consumer Producer design

I am looking for advice on how the following problem is handled in solutions that use Pulsar.

The scenario is: A producer is sending messages (in JSON) and the consumer is taking them and inserting data into database tables (specified in the message).

Suddenly the producer changes the structure of the data sent in the messages (let's say because the table structure in the database has a new column).

So for a moment, Pulsar has messages with the old data structure and now starts receiving messages with new data structure.

My doubt is regarding how the consumer should handle this scenario. What to do with the messages with old structure that are now invalid since they cannot be inserted in the database table since the table structure changed. Retry and then permanently fail (dead letter Q?).

Also, do you usually opt to sent the metadata along with your messages or do you normally handle this in a separate topic or other form.

Thanks for any advice

How to write react child component to decide what to render in parent without redirecting

Simpler version of my code is as below, I would like the child component to held responsible for rendering "this page is not found", redirecting from the child component is not what I am looking for. We re-use this child component and adding the check every where is not the correct solution.

const parentComponent = (props) => {

    if(!props.hasImage)
       return <div> this page is not found </div>

       return (
         <div>
           <h1> Header with Image </h1>
           <childComp image={props.image}>  Child component 2 </childComp>
           <div> Footer with Image <div>
         </div>
)}

const childComp = (props) => <div> {props.image} {props.children} </div>

Python threading - How to wait for data from multiple senders to merge the result?

My ImageStitcher class is receiving multiple image messages from different threads. Another thread will then call the get_stichted_image() and this works. But it doesn't look good and seems kinda slow.

Is there a better way to handle multiple incoming messages from different threads and wait for all queues (or something else) to contain something?

class ImageStitcher:
    def __init__(foo):
        self.image_storage = {
            Position.top: queue.Queue(maxsize=1),
            Position.bottom: queue.Queue(maxsize=1)
        }
        foo.register(image_callback)

    # will be called from different threads
    def image_callback(self, image_msg):
        if self.image_storage[image_msg["position"]].full():
            self.image_storage[image_msg["position"].get()
        self.image_storage[image_msg["position"].put(image_msg)

    def get_stichted_image(self):
        try:
            top_image_msg = self.image_storage[Position.top].get(timeout=0.1)
            bottom_image_msg = self.image_storage[Position.bottom].get(timeout=0.1)
            return self.stitch_images(top_image_msg, bottom_image_msg)
        except queue.Empty:
            return None

Can i use the DAO pattern for analysis class diagram?

I am new in this forum. I am studying the differences between analysis and design class diagram. I have a doubt: can I use the DAO pattern for analysis class diagram?

Thanks

Two threads, how to implement communication between them. (Pseudocode)

I have two threads:

  1. Main thread :

    • Main thread is listening for HTTP requests,
    • Main thread registers handler to HTTP request used for long polling
  2. Second thread:

    • Getting data from different socket.
    • if it finds something in data from socket, updates thread local storage, and IF Main thread has HTTP request pending it sends data to it somehow.

How do I make Main thread and second thread communicate to each other?

Main Thread http handler pseudocode:

function mg_handler(request){

   var handle = parseHandle(request.data);
   var storage_name = parseStorageName(request.data);

   var response = WaitForResponse(handle,storage_name);

   mg_printf(rasponse);

   return;

}

Second thread pseudocode:

 var storage
 
 function t_run()
 {
   var buf
   while(1){
       recvfrom(socket,buf);
       var result;
       bool found_something = search(buf,result);
       if(found_something){
          update(storage,result);
          //if WaitForResponse is waiting let it continue by sending storage to it somehow.
          //???
       }
    }

    cleanup:

    return;
 }

What design pattern to use for switching between Microservices application modules having same endpoints?

In my web application "Payments aggregator" designed as Microservices I have a modules called "user-payments" and "charges-adapter-old". Module "user-payments" refers to "charges-adapter-old" by invoking its method accessible through endpoint "/internal/charges". Module "charges-adapter-old" in its turn refers to external service "Charges" with request for user charges.

In near future "Charges" support team will offer a new specifications for communication with their service. So I would like to add several things into my application:

  • develop a new module "charges-adapter-new" with same endpoint "/internal/charges" as module "charges-adapter-old" has;

  • keep both new and old adapters and be able to switch between them using specific variable in configuration file.

What design pattern and configuration file variables can I apply?

Observer as Observable in design patterns

Is it ok to use Observer as Observable for another observer? I mean something like this:

TotalPrice (observator)
    ItemPrice  (observator / observable for TotalPrice)
        ItemCharacteristic1 (observable for ItemPrice)
        ItemCharacteristic2 (observable for ItemPrice)
        ItemCharacteristic3 (observable for ItemPrice)
    ServicePrice  (observator / observable for TotalPrice)
        ServiceCharacteristic1 (observable for ServicePrice)
        ServiceCharacteristic2 (observable for ServicePrice)
        ServiceCharacteristic3 (observable for ServicePrice)

or is there better design pattern for that?

Creating Costume trading algorithms

I'm working on an automated trading system. On of the most challenging tasks I have faced is as follows:
The system is created with ease of use in mind, so there is a client side application with type-script/java-script. I want the users to easily create their trading algorithms with some predefined parameters and indicators and execute them. The tricky part is to convert what the user wants to an object that can be used by the execution service.
Since the above problem is complicated I rather start with something simpler: Users can write .* files(like .go .js .java) which implement their desired algorithms. Ideally I want to add this strategies in runtime(hence might want to use reflection) but for an MVP, creating custom strategies before compiling and compiling the whole project with some new strategies is also an option.


Most of the problems I'm facing are int implementation:

  1. What should be my approach to the architecture of the strategy parsing system?
  2. How can I implement some simple interface that can be easily be used to create and new algorithms and strategies and easily be executed by the program?
  3. In the above problem how can I add this new algorithms at runtime

I have some general Ideas:
Since there might be multiple micro-services, I was thinking of creating a separate micro-service for strategies! This micro-service can register new strategies and exposes some API so other services can check whether the current market triggers any strategy. This design makes the task much simpler since the service can be written with the same language as the client application, also there are many merits to a micro service approach. How ever the overhead of network calls can be a problem if the trade frequency is high! Another approach is the create a library or SDK that can be used in other services,the con here is that all the back-end source code the needs the SDK, should have same language . I don't that is there any other way or not but I would appreciate any help.
Also, considering the building and execution process it self I don't know what is the best practice here. I was thinking of the Builder and Strategy patterns but I think there are better options.

Thanks

Py. Implement design patterns

Im new in python and I have a sample UML diagram here.

Sample UML diagram

How to implements this in python, using Prototype Design Pattern.

This is my code.

from abc import ABCMeta, abstractmethod
import copy

class Shape:
    def __init__(self, x, y, color):
        self.x = x
        self.y = y
        self.color = color

How to code the + Shape(source) and + clone()

jeudi 29 octobre 2020

R search a character vector using a pattern vector [duplicate]

I have been experimenting with grep to identify a pattern in a character vector with the aim of 'fishing out' the name of a file from the character vector. For example, for a small and simplified case, let's say:

vec <- c("Fast.file1", "Fast.file2", "Med.file3", "Medium.file4", "Slow.file5")

I can search for the files with the pattern "Fast" by simply writing:

> Fast_files <- vec[grep("Fast", vec)]
> Fast_files
[1] "Fast.file1" "Fast.file2"

But let's say I have a vector of patterns, whose length can vary depending on user input via a file read. I would like to feed the pattern vector to the search so that each element of the pattern can be cross-checked against vec, and I want to return all compatible hits. For example,

checkAgainst <- c("Fast", "Medium", "Med")

If I try to use grep with checkAgainst as a pattern, I get:

> find_files <- grep(checkAgainst, vec)
Warning message:
In grep(checkAgainst, vec) :
  argument 'pattern' has length > 1 and only the first element will be used
> find_files
[1] 1 2
> 

So, it appears grep can't take a vector pattern. It takes the first (i.e. "Fast").

My wish is to have an outcome where find_files includes "Fast.file1", "Fast.file2", "Med.file3" and "Medium.file4".

I can write a for-loop where I can overcome this problem, but I was wondering if R provided a more succinct and elegant solution?

Thank you for your consideration.

Maziar.

DDD - clean architecture vs clear workflow

We are writing in a DDD manner, meaning we do not "follow DDD as a bible" but rather make use of the benefits it offers, and bend it when it forces us to do stuff thats not "common sense" for us - after all one of DDD's main point is that the code stays close to the real life use cases.

And here is one place where the techniquetook us a little off track:

Adding an item to a basket user story: (I'm keeping it short here...)

"when a customer adds an item to the basket, if sale is over limit (1000$), user will get a "Maximum sale is 1000$" popup If this item appears in the basket more times than allowed user will get a "Product exceeded max amount allowed in one order" popup And the item does not exist in the stock user will get a "Product XXX is out of stock" popup If all terms are ok, add the item to the basket"

Application code may look like this:

func basketapp.AddItem(basketId, productId, quantity){

   myBasket := BasketRepo.LoadByID(basketId)      //load the basket
   Product := ProductService.GetByID(productId)   //get the requested product 
   myBasket.AddItem(Product, quantity)            //runs internal domain business logic to add the item
   BasketRepo.Save(basketId, myBasket)            //Persist/add event source
}

Where domain business logic would look like this:

func model.basket.AddItem(product, quantity){
   if basket.total() > maxTotalPerBasket {
       return maxItemsPerBasketExceededError
   }

   if basket.CountItem(product.id) > product.MaxRepeatsPerSale {
       return productCountLimitExceededError
   }
   .....
   item := newBasketItem(product, quantity ....)
    basket.Items.Append(item)
}

The problem starts when I wish to validate the product is in stock after the simple validations To the human (customer, product manager developer) mind, its another validation, so writing this as the user story suggests:

func model.basket.AddItem(product, quantity){
   if basket.total() > maxTotalPerBasket {
       return maxItemsPerBasketExceededError
   }
 
   if basket.CountItem(product.id) > product.MaxRepeatsPerSale {
       return productCountLimitExceededError
   }
        
   if !inventoryService.exists(product.Id,storeId ){
       return productNotInInventoryError
   }
        
   item := newBasketItem(product, quantity ....)

   basket.Items.Append(item)
}

But according the DDD concepts, model does not call another service (even not an injected scheme),

So the extra code would be a part of the app layer, and I would need to split model.AddItem in this manner:

func basketapp.AddItem(basketId, productId, quantity){

   myBasket := BasketRepo.LoadByID(basketId)        
   Product := ProductService.GetByID(productId)     
   //myBasket.AddItem(Product, quantity)            
        
        
   if !myBasket.ValidateItem(Product, quantity){    //Where ValidateItem is the model basket.total()+basket.CountItem code
      return ...
   } else if !StockLevelService.exists(productId, storeId ){
      return ...
   }
   myBasket.AddItem(Product, quantity)  //leaving lines from model.Additem after validation
        
          
   BasketRepo.Save(basketId, myBasket)         
        
}

Its cleaner code wise, but now the user story needs to change (and for that - people writing this user story should understand that architecture wise stockLevel is something done in a different service/domain".

We had some other mutations of this idea, yet we cant find a way that will "play by the technical rules" on the one hand, and "will read as the user story" on the other (and of course need to consider everyone on the team will easily understand where is the right place for everything, so we will not find mixed approaches and need to fix upon code review... as well as quickly know where to go when debugging each part etc)

Ideas are welcome :)

Best way to use a Singleton object in main method as well as other surrounded methods in Java [duplicate]

Say I have a simple Singleton class below that has one attribute, a String variable. What's the best way to set up this Singleton class in my MainClass if I want to use it all throughout the code, not just the main function, but in all other functions (and other classes) as well?

public class Singleton
    {
        private static Singleton instance = null;
        public String text = null;
    
        private Singleton(){}
    
        public static Singleton getInstance(){
            if(instance == null){
                instance = new Singleton();
            }
            return instance;
        }
    
        public void setText(String text){
            this.text = text;
        }
    }


    public class MainClass
    {
        public static void main(String[] args){
            Singleton single = Singleton.getInstance();
            single.setText("asdf");
        }
        
        public void doStuff(){
            //....
            //....
            Singleton single2 = Singleton.getInstance();
            single2.setText("hello");
        }
    }

Would I do something like the following above where every new area I want to call the Singleton, I'd use getInstance and basically create a new variable (that seems repetitive), or should I create it at the top as a class variable of MainClass? That would mean it would throw errors since main is static and opens up a whole other can of worms as well I believe. I'm new to design patterns so any tips would be great!

Python – Break a string which is derived from pasting columns from excel to a text widget

When I am pasting two columns from excel (one with identifiers and one with values/numbers) into an ipy.widgets text box the output strings looks like:

'US78378X1072\t 0.500 EU0009658145\t 0.055 GB0001383545\t 0.445 '

I want to automatically break this type of string to two variables such as the below or create a dictionary. Is this possible?

b = ['US78378X1072','EU0009658145','GB0001383545'] c = np.array([0.500,0.055,0.445])

d = {'US78378X1072':0.500, 'EU0009658145': 0.055,'GB0001383545':0.445}

Modular event list and ensuring ID uniqueness

I am looking for a design pattern/documentations/leads to solve a complex problem my team and I are encountering. The question is flagged as C++ because the solution would be implemented in C++ but the question is less about the language and more about the design.

The goal is to build some sort of a modular event list. Each module will add events to a list that get consumed by a process. The problem is that in order to avoid an unmaintainable table of all possible events (due to modularity, adding or removing a module would change this table), each event should be flag by an unique ID. But we don't seem to find a way to ensure that the ID we generate is unique without such a table. Another constraint is that this is targeted to embedded system with limited amount of Flash and RAM, so it would be ideal if the final "event table" would not be included in the binary.

The general idea would be the following :

generic_header_file:

uint32_t someHashFunction(someParameter); // Ideally this would be a constexpr

// Adds an event to the list
void add_event_to_list(uint32_t value);

// Returns an event and consumes it
uint32_t get_next_event(void);

module_1_file

# include "generic_header_file.h"
void module_1_function(somePArameter)
{
    //...
    add_event_to_list(someHashFunction("Name_of_event_to_be_hashed1"))
    //...
}

module_2_file

#include "generic_header_file.h"
void module_2_function(someParameter)
{
    //...
    add_event_to_list(someHashFunction("Name_of_event_to_be_hashed2"))
    //...
}

process_file

#include "generic_header_file.h"
void myProcess(void)
{
    uint32_t event;

    event = get_next_event();

    switch(event)
    {
        case someHashFunction("Name_of_event_to_be_hashed1"):
        {
            //...
        } break;
        case someHashFunction("Name_of_event_to_be_hashed2"):
        {
            //...
        } break;
        case someHashFunction("SomeOtherEvent"):
        {
            // Should never be received because the associated module was not added
            //...
        } break;
    }
}

The interesting way this would work is that even if we remove a module, we don't need to modify to heavily an application. For example, if we remove the module responsible for generating the "SomeOtherEvent" event, since there is no access to a global array containing all the hashes, no out of array access can happen, and on simple and generic application this should also drastically improve development time, allowing us to heavily reuse already existing software.

The problem with the hash method, is that without a list of all the generated hash, we cannot guarantee no collisions occur. And since module shall be independent and of course in different files, I don't see a way to even build such a hash table.

I am open to any comments or leads on this matter (even a paper demonstrating such a solution is impossible, at least we would know).

How to avoid multiple if statements where result is add to list

I would like to ask you for an idea. I have class, where I have a lot of if statements, lets say it looks like that:

List<String> errors = new ArrayList<>();
boolean errorCodition1 = SuperUtils.calculateIfObjectIsCorrect(this); // rest of them same

if(errorCondition1){
    errors.add(errorsMessage.getSuperError());
}

if(errorCondition2){
    errors.add(errorsMessage.getMinorError());
}

if(errorCondition3){
    errors.add(errorsMessage.getAlmostCriticalError());
}

if(errorCondition4){
    errors.add(errorsMessage.getOverNineThousendError());
}

displayErrors(errors);

Maybe this code does not look super terrible, but lets assume that we will need to add more conditions. How would you avoid it?

This code is called always when class is initialize, so lets say for example in constructor.

Design pattern creation

Bale, an undergrad CSE student has recently learned design patterns. He has a class test next week on a syllabus of singleton, factory, adapter, composite design patterns. He wants to practice some code on design patterns. Now, he is searching for some design pattern assignments. Most of the assignments he found so far require framework knowledge, deep programming knowledge and huge time. He wants some small scale assignment which can be completed within a day using simple java language without integration of any graphical user interface(GUI) or any advanced packages or any other APIs.

Now, describe a simple design pattern assignment that satisfies his requirement. Also, provide a possible paper solution(without coding) showing that the assignment satisfies all requirements. Do not write any code.

mercredi 28 octobre 2020

How to load a concrete implementation dynamically and parameterize the object creation?

Context

I am building a Chrome Extension that can receive commands and it shall be based on TypeScript. I want to extract concrete implementations of a class into it's own file that can be dynamically loaded.

Typescript dynamic loading command pattern

Example

In my chrome extension I receive the following JSON.

{
    "action": "get_tasking",
    "tasks": [
        {
            "command": "ConcreteContentCommand",
            "parameters": "{'param1': 'bla', 'param2': 'bla2'}",
            "timestamp": 1578706611.324671, //timestamp provided to help with ordering
            "id": "task uuid",
        }
    ]
}

First I'll load the appropriate file from IndexedDB that can be named ConcreteContentCommand.js containing the ConcreteContentCommand-Implementation. Now I want to create an instance of ConcreteContentCommand using the parameters param1, param2 that can then be used by my invoker.

class ContentReceiver {
  targetURL: string;
  payload: string;

  constructor(targetURL: string, payload: string) {
    this.targetURL = targetURL;
    this.payload = payload;
  }

  InjectRunnable() {
    // inject the payload into tab
    console.log(`Do something with ${this.payload}`);
  }
}

interface Command {
  execute(): void;
}

abstract class ContentCommand implements Command {
  receiver: ContentReceiver;

  protected constructor(url: string) {
    this.receiver = new ContentReceiver(url, this.runnable.toString());
  }

  abstract runnable(): void;

  execute() {
    this.receiver.InjectRunnable();
  }
}

abstract class BackgroundCommand implements Command {
  abstract runnable(): void;

  execute() {
    this.runnable();
  }
}

// This class shall be extracted, my extension will not know about this class
class ConcreteContentCommand extends ContentCommand {
  param1: string;
  param2: string;

  constructor(param1: string, param2: string) {
    super("https://staticurl");
    this.param1 = param1;
    this.param2 = param2;
  }

  runnable() {
    // Do Concrete Stuff here
  }
}

What options do I have to do this?

How register a transaction decorator for database Command with simpleinjector

I need some help to understand what it's wrong in my configuration of the container. I based this implementation by using this example

Basically i need to implement some use case as database command based on that interface

public interface IDatabaseCommand<TResult, TParam>
{
    TResult Execute(TParam commandParam);
}

and i want to use a decorator that add the transaction safe functionality.

Every command need to use a dedicated DbContext and the transaction has to be executed on that context

To do this i have implemented

//Transactional Decorator
public class TransactionDatabaseCommandDecorator : IDatabaseCommand<DatabaseResult, BusinessCommandParams1>
{
    private readonly Container _container;
    private readonly Func<IDatabaseCommand<DatabaseResult, BusinessCommandParams1>> _decorateeFactory;

    public TransactionDatabaseCommandDecorator(Container container, Func<IDatabaseCommand<DatabaseResult, BusinessCommandParams1>> decorateeFactory)
    {
        _container = container;
        _decorateeFactory = decorateeFactory;
    }

    public DatabaseResult Execute(BusinessCommandParams1 commandParam)
    {
        DatabaseResult res;
        using (AsyncScopedLifestyle.BeginScope(_container))
        {
            var _command = _decorateeFactory.Invoke();

            var factory = _container.GetInstance<IDesignTimeDbContextFactory<WpfRadDispenserDbContext>>();

            using (var transaction = factory.CreateDbContext(new[] { "" }).Database.BeginTransaction())
            {
                try
                {
                    res = _command.Execute(commandParam);
                    transaction.Commit();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    transaction.Rollback();
                    throw;
                }
            }
        }

        return res;
    }
}

//Example of implementation
public class WpfRadDispenserUOW : IUnitOfWork<WpfRadDispenserDbContext>
{
    private readonly IDesignTimeDbContextFactory<WpfRadDispenserDbContext> _factory;
    private WpfRadDispenserDbContext _context;
    private IDbContextTransaction _transaction;

    public bool IsTransactionPresent => _transaction != null;

    public WpfRadDispenserUOW(IDesignTimeDbContextFactory<WpfRadDispenserDbContext> factory)
    {
        _factory = factory ?? throw new ArgumentNullException(nameof(factory));
    }

    public WpfRadDispenserDbContext GetDbContext()
    {
        return _context ?? (_context = _factory.CreateDbContext(null));
    }

    public IDbContextTransaction GetTransaction()
    {
        if (_transaction == null)
            _transaction = GetDbContext().Database.BeginTransaction();

        return _transaction;
    }

    public void CreateTransaction(IsolationLevel isolationLevel)
    {
        GetTransaction();
    }

    public void RollBack()
    {
        _transaction?.Rollback();
        _transaction?.Dispose();
    }

    public void Commit()
    {
        _transaction?.Commit();
    }

    public void Persist()
    {
        _context.SaveChanges();
    }

    public void Dispose()
    {
        _transaction?.Dispose();
        _context?.Dispose();
    }
}


public class BusinessCommand1 : IDatabaseCommand<DatabaseResult, BusinessCommandParams1>
{
    private readonly IUnitOfWork<WpfRadDispenserDbContext> _context;

      public BusinessCommand1(IUnitOfWork<WpfRadDispenserDbContext> context)
    {
       _context = context;
    }

    public DatabaseResult Execute(BusinessCommandParams1 commandParam)
    {
        //ToDo: use context
        return new DatabaseResult();
    }
}

//Registration of container
var container = new Container();
container.Options.DefaultScopedLifestyle = ScopedLifestyle.Flowing;


container.Register<IDesignTimeDbContextFactory<WpfRadDispenserDbContext>>(() =>
            {
                var factory = new WpfRadDispenserDbContextFactory();
                factory.ConnectionString = "Server=.\\SqlExpress;Database=Test;Trusted_Connection=True";
                return factory;
            });
container.Register<IUnitOfWork<WpfRadDispenserDbContext>, WpfRadDispenserUOW>(Lifestyle.Scoped);
container.Register<IUnitOfWorkFactory<WpfRadDispenserDbContext>, WpfRadDispenserUOWFactory>();



//Command registration
container.Register<IDatabaseCommand<DatabaseResult, BusinessCommandParams1>, BusinessCommand1>();

//Command Decorator registration
container.RegisterDecorator(
            typeof(IDatabaseCommand<DatabaseResult, BusinessCommandParams1>),
            typeof(TransactionDatabaseCommandDecorator),Lifestyle.Singleton);

The problem is that when i try to execute

var transactionCommandHandler =_container.GetInstance<IDatabaseCommand<DatabaseResult, BusinessCommandParams1>>();
usecase.Execute(new BusinessCommandParams1());

i receive correctly an instance of TransactionDatabaseCommandDecorator but when the i try to get the instance from the factory i receive this error

SimpleInjector.ActivationException
  HResult=0x80131500
  Messaggio=WpfRadDispenserUOW is registered using the 'Scoped' lifestyle, but the instance is requested outside the context of an active (Scoped) scope. Please see https://simpleinjector.org/scoped for more information about how apply lifestyles and manage scopes.
  Origine=SimpleInjector
  Analisi dello stack:
   in SimpleInjector.Scope.GetScopelessInstance(ScopedRegistration registration)
   in SimpleInjector.Scope.GetInstance[TImplementation](ScopedRegistration registration, Scope scope)
   in SimpleInjector.Advanced.Internal.LazyScopedRegistration`1.GetInstance(Scope scope)
   in WpfRadDispenser.DataLayer.Decorator.TransactionDatabaseCommandDecorator.Execute(BusinessCommandParams1 commandParam) in C:\Work\Git\AlphaProject\WpfRadDispenser\WpfRadDispenser.DataLayer\Decorator\TransactionDatabaseCommandDecorator.cs: riga 29
   in WpfRadDispenser.Program.Main() in C:\Work\Git\AlphaProject\WpfRadDispenser\WpfRadDispenser\Program.cs: riga 47

The problem here is that i want to use a dbcontext that it's created and controlled by his decorator. But the constructor injection it's handled by container so how i can inject the context created by the decorator inside the command?

Basically i want to having something like that made by the decorator of the command

var context = ContextFactory.GetContext();

try
{
    var transaction = context.database.GetTransaction();
    var command = new Command(context)
    var commandParams= new CommandParams();
    var ret=command.Execute(commandParams)
    if(!ret.Success)
    {
        transaction.Discard
        return;
    }
    transaction.Commit();
}
catch
{
    transaction.Discard()
}

but made with DI and simpleInjector

Maybe there is some issue or several issue on my design but i'm new on DI and i want to understand better how the things works.

Could you give me some advice on this?

Just to recap i need to use a lot of command database in which every command has to have an isolated context and the functionality of transaction has to be controlled by an extra layer inside the decorator.

Design pattern to avoid returning interfaces

My application has the following model that I simplified on purpose, and I think there is a lot of code smell in the way I am using interfaces:

  1. Libraries have Collections
  2. Collections have Items
  3. Libraries know where the location if Item is.

Let's say I have ten libraries (that will be implemented in separated packages, each one with its specificities).

I want to manipulate the libraries in handlers to serve requests. So, I defined the following interfaces:

type Library interface {
    ListCollections(prefix string) []Collection
    GetItemLocation(item Item) string    
}
type Collection interface {
    SearchItems(query string) []Item
}
type Item interface {
    Name() string
    Summary() string
}

I cannot define an Item struct as each one is different. However, with respect to the outer world, having the Item interface is sufficient.

As you can see, I have methods returning interfaces and I don't really like it. Moreover, I struggle with, in this example, the GetItemLocation part: it expects an Item, but I need to access fields of the Item (specific to each collection) so it forces me to type cast the argument inside the method.

Which patterns could I use to breakdown this complexity and write more diomatic go code?

Lookup lists in microservices

When developing microservices where each microservice has its own database, the issue of "sharing" lookup data becomes challenging. So I'm wondering what is the best practice for dealing with this?

  1. Create a separate Lookups Microservice which exposes the data through a Web API?
  2. Save the lookups which are relevant to each microservice in its own database?

If we go with the second option (which is my preferred one), do you think it's a good idea to share the lookups across all microservices through a distributed cache, or should this be restricted through the API of each microservice?

Any other suggestions?

Dictionary map in a handler function for class methods

I have a class that accepts a different number of inputs but achieves the same goal (Same output). It's a complex class and is used heavily for an API. I built a class handler that accepts inputs and maps them into the function based on the API request.

I'm not sure if this type of design is maintainable or if it's going to present other issues. So I have these inquiries:

  1. Is this design maintainable and scalable?
  2. Is this error-tolerant?
  3. Can I improve it?
  4. Am I following a design similar to any accepted design pattern?
  5. Any advice?

Please take a look at this very simplified code design:

Handler:

def class_handler(class_usage_type, class_object, kwargs):
    # Method inputs and procedures are different but output is the same
    Usage_FUNC_MAP = { 
        'use_method_x': class_object.method_x, 
        'use_method_y': class_object.method_y,
        'use_method_z': class_object.method_z,
        # ...
    }
    
    try:
        result = Usage_FUNC_MAP[class_usage_type](**kwargs)
        
    except Exception as e:
        result = {
            'output_elem1': kwargs
            'output_elem2': f'Error: {e}',
            'output_elem3': f'Error {e}'
        }

    finally:
        return result

Class

class some_class():
    # ...init
    def method_x(self, param1_for_x, param2_for_x):
        # ...procedure for x
        return same_output

    def method_y(self, param1_for_y):
        # ...procedure for y
        return same_output

    def method_z(self, param1_for_z, param2_for_z, param3_for_z, param4_for_z):
        # ...procedure for z
        return same_output

    # ...

API

# Main is in a different file as an API
# Route 1 for x
# ...
params_for_x = {"param1_for_x": '...', "param2_for_x": '...'}
result_for_x = class_handler(class_usage_type='use_method_x', class_object=some_class, kwargs=params)
#...

# Route 2 for y
# ...
params_for_y = {"param1_for_y": '...'}
result_for_y = class_handler(class_usage_type='use_method_y', class_object=some_class, kwargs=params)
# ...

# Route 3 for z
# ...
params_for_z = {"param1_for_z": '...', "param2_for_z": '...', "param3_for_z": '...', "param4_for_z": '...'}
result_for_z = class_handler(class_usage_type='use_method_z', class_object=some_class, kwargs=params)
# ...

# ...

mardi 27 octobre 2020

Recommended design pattern for config generator

I am writing an CLI application (or engine) that generates, validates, publishes and parses a single YAML or JSON configuration file (for end users). The idea is to parse user provided config file and perform user actions such as validate or publish commands. When config is not available, there is also initialize command to build config as user goes through interactive prompt.

The config items within the file can consist of types such as simple key value, object list, group and nested list of groups

What is the recommended design pattern in the context of Typescript?

Open page two inside the body of page one using Cupertino Segmented Control

I am using Cupertino Segmente Control , I created a tab using three swings and assigned three widgets to the front page body. When selecting any of the tabs, it displays the body of the new widget. So far, everything works fine. Products are loaded inside each page, and when we select a product, it must go to the second page .The second page opens, but inside the body of the first page. If you help me, thank you very much

this is my images app

Is it an anti-pattern to use the suffix "Template" for the class name of the template method pattern?

I am using the template method pattern.

My abstract class has a skeleton method processing iteration and logging.

like this:

abstract public class ImportingTemplate implements Importing{
    
    
    public void importArticles(List<Long> articleIds)
    {
        for(long articleId : articleIds)
        {
            Log log = importArticle(articleId);
            logService.save(log);
        }
    }
    
    protected abstract Log importArticle(long articleId);

}


I can't use "Importing" because it is a name for the interface.

I can't come up with a better name than using "Template" on the suffix.

Is it an anti-pattern to use the suffix "Template" for the class name of the "template method pattern"?

Is it better to use "ImportingContext"

Money pattern implementation in Java

Are there any techniques on implementing a simplified version of the money pattern in Java with Classes? With my current implementation there are three classes- Money, Rate and Currency which hold variables and references to other tables by referencing the object inside the respective class. Which currently only are implemented in Money and Currency. Currency has a relationship to MyClass1 that contains lists for currencies and the various exchange rates to convert the currencies into other rates vice versa from the amount specified in the Money class.

What would be the correct design patterns in using the money pattern in a simplified way or use the classes later for doing financial operations such as converting account money from one currency to another when withdrawing from an ATM abroad. Or using the same code for calculating loans with the same principles specifiec in those classes without really changing any logic it contains? There is Fowler Money which does calculations and stores the values in a class. Might there be a way to construct or design such a money object that would allow easily employ it in ways described above.

Current code has the following attributes;

public class Rate {
    
public float Rate;
public string TargetRate;
public string BaseRate;

}

public class Currency {
    
public string Name;
public MyClass1 MyClass1;
public string ISOCode; // uses ISO 4127

}

public class Money {

public Currency currency;
public decimal amount; // incremented money from methods

public decimal TallyAmount(decimal newamount) {
    
    return amount = amount + newamount;
   }

public decimal ReduceMoney(decimal amountToReduce) {

    return amount = amount - amountToReduce;
   }
}

Implementation is invoked in tests where list initialization also works via unit tests. Would it be reasonable to include a list of Rates in MyClass1 where the then MyClass1 would implement those classes using those class objects and using operations such as converting and receiving the exchange rate from the list that is inside the same class mimicking real currency data which will be populated with API calls in the future from another class.

public class MyClass1 { 

public List<Currency> currencies= new ArrayList<Currency>();

public List<Rate> exchangeRates = new ArrayList<Rate>();

public Currency AppendCurrency(Currency toAdd) { // to add a currency into the list from test setUp
       
       currencies.Add(toAdd);
       // ... currencies
       return toAdd;
  }

public decimal Transform(Money money) {
       // convert between currencies using exchange rate list
     
       // ...  calculations            

       return convertedMoney; // convertedMoney is typeof Money 
                              // Money contains relationship mappings into Currency and Currency
                              // into MyClass1. So money can be accessed both ways.
  }

public decimal GetRate(Currency for) {
 
       // .. exchange rates using the rates list.
       return decimalReturn;// Rate better?
       
  }

public decimal ChangeRate(Rate rate) {
 
       // .. change a current rate in the system
       return newRateInTheRateList; // typeof(Rate) or decimal
       
  }



}

The currencies will be populated from the tests right now. Would this behaviour be sufficient in managing this pattern with external devices when the usage of this class will be improved in the future. Mainly hesitant on how to do the conversions between exchange rates from unit tests. The list must be popultate with rate data as well into MyClass1. Would this simplified version of the money pattern suffice or how to design it better so it would be useful in deploying and injecting it for development as a simplified archetype pattern?

Would this be a good beginning to start using that in an enterprise as a simplified model for the money.(loan.bank account.). Are there any ways on how to improve this or what sources to read for creating a cleaner and durable pattern that would not be so prone to change. Would storing lists in MyClass1 a great idea? GoF. Grasp patterns.

lundi 26 octobre 2020

How to reuse a common panel?

I have a panel for adding an item to the cart. For example:

public class SomePanel extends JPanel {

    private static final long serialVersionUID = 1L;

    private JLabel firstLabel;
    private JLabel secondNameLabel;
    private JLabel thirdLabel;
    // and more..


    private JTextField firstTextField;
    private JTextField firstTextField;
    private JTextField thirdTextField;
    // and more..


    private void init() {
        firstLabel = new JLabel("First label");
        secondLabel = new JLabel("Second label");
        thirdLabel = new JLabel("Third label");     
        // and more..

        firstTextField = new JTextField("first field");
        secondTextField = new JTextField("second field");
        thirdTextField = new JTextField("third field");
        // and more..
    }

This panel is located in the dialog. When I select "Add" in the menu, a dialog and this panel appear. There I can enter information about the product and add the product.

The problem is that I have another three areas on the main form. These areas also display the same panel as above. How can I reuse an existing SomePanel and would this be a good practice? Maybe it's better to create singletons for each element (JLabel and JTextField) instead? Maybe there is some special pattern for solving this problem?

How to name Cache-Aside function according to CQS principle

For example, I have a function that retrieves data from cache or if the cache is empty, the function gets the result from DB or third-party API, and before returning, store the result to the cache (it looks like a primitive example of the Cache-Aside pattern).

public function getProductById(string $id): IProduct
{
    try {
        return $this->cache->getProductById($id);
    } catch (ProductDoesntExistException $e) {
        $product = $this->db->getProductById($id);
        $this->cache->saveProduct($product);

        return $product;
    }
}

So, according to the Command–query separation principle, we shouldn't do like this, but, let it be an exception. When seeing the name like getSometing we expect that we don't change anything, but here we actually save cache. So, what is the best way of naming functions like this?

What are the best design Patterns for React Native apps

I am new to React Native and only recently picked it up, I am using it to make an app for my final year university project, learning the framework as I go using different examples from online.

So far I have been using function components with everything for one component in the same class, eg. view, functions and styles. - So far this has been working and seems to preform efficiently.

My question is aimed at any experienced React Native developers. - Is my current approach of function components a good coding practice for React Native apps or should I be using class components. From my little experience it seems function components are easier and I have done some research that shows function components are becoming more common with hooks etc. - I'm just not sure if its the best approach for a full application.

Another question I have is aimed at design patterns. - Should functionality, view and styles all be in the same class or would it be better practice to split them out and just import as appropriate - similar to Angular. The reason i ask this is because all examples that I have seen/followed up to now take the approach of everything in the same class but that may just be for presentation purposes.

How to Model data using UML for this situation?

The Situtation is that there is a data named Progress which has 2 valid values (suppose 'A' and B). this means Progress = 'A' or Progress = B. A is just a string, but B is not string. B itself has some valid values (suppose strings: 'V1', 'V2', 'V3'). progress can be A which is a string or can be B which is 'V1', 'V2' or 'V3'. How to model this data?image

If B is just a simple string (just like A) so we can define Progress as a string but i think one solution is defining progress as a class which has two children: Class A & Class B. Class B has 2 fields: Id & state so we have 3 IDs which correspond to 3 states: 'V1', 'V2' and 'V3' and Class A with a const field called state with fixed value 'A'. so with this solution progress can be objects A or B which has a state.

Please help me if such design is not good or if there is any design pattern for such situation.

Visitor design pattern for enums

I receive a Response of a given type and value. Based on the type I know how to build the Parameter.

I would like to find a design pattern that allows me to get rid of the line:

if (paramType != reponse.paramType)

I thought to use the Visitor design pattern, but I believe it is not going to work because ParameterType is a enum.

Model:

enum ParameterType {
    NAME, 
    PHOTO;
}

class Response {
    PamarameterType paramType;
    String value;
}

interface IParameter {}
 
class ParameterName implements IParameter {
    static PamarameterType paramType = ParameterType.NAME;
    ParameterName fromReponse(response) {
        if (paramType != reponse.paramType) {
            throw new Exception();
        }
        return parse(response);
    }
    ParameterName parse();
}

class ParameterPhoto implements IParameter  { 
    static PamarameterType paramType = ParameterType.PHOTO;
    ParameterPhoto fromReponse(response) {
        if (paramType != reponse.paramType) {
            throw new Exception();
        }
        return parse(response);
    }
    ParameterPhoto parse();
}   

Service:

ParameterName getParameterName() {
    var response = client.getName();
    var param = ParameterName.fromResponse(response);
    return param;
}

ParameterPhoto getParameterPhoto() {
    var response = client.getPhoto();
    var param = ParameterPhoto.fromResponse(response);
    return param;
}

Does changing parameter and return types in a child class, means breaking SOLID design principles?

I am building an application which uses API to retrieve data from a third party source. The data that is consumed needs to be formatted so I have decided to create an ConvertTypeInterface that forces child classes to implement convert($data) method which will convert/format any data into any other format.

ConvertTypeInterface

interface ConverterTypeInterface
{
    public function convert($data);
}

Now the problem with this I think I might be breaking Liskov's Substitution principle by not forcing stricter types on parameters or return types, however in this case I can't use type hinting for a parameter or a return type because $data parameter can be anything: string, integer, object, array etc. same with the return type.

Converter Example

class ConvertToInteger implements ConverterTypeInterface
{
    public function convert($data)
    {
        return (int) $data;
    }

}

Usage Example

/* I have an array of data field names and type of conversion that should be made for that field,
 * I loop through each of the fields that need to be converted and based on a converter type conversion 
 * changes the value of that field.
 */
    foreach ($convertFields as $field=>$type){
       if(isset($this->converters[$type])) {
           $data[$field] = $this->converters[$type]->convert($data[$field]);
       }else {
           throw new \Exception("Converter type `".$type."`` doesn't exist");
       }
    }

Question

Is this breaking Liskov's substitution principle or another SOLID design principle? Is there a way to improve this ?

dimanche 25 octobre 2020

Name of Parameterize Constructor pattern alternative

I'm not sure how to ask, or title this question effectively (so reviewers, please have at it)

Given that a default constructor looks akin to:

class Foo{
  Foo();
};

when the need arises to configure this instantiation, a typical approach often referred to as the "Parameterize Constructor" pattern might look like:

class Foo {
  Foo(int param1, double param2);
};

There exists a common alternative for which I do not know its name -- Essentially the signature remains default, but the body of the constructor method calls out to one or more data sources to configure itself. Such as:

class Foo{
  Foo();
};

Foo::Foo() {
  int param1 = parseFileOnDisk(...);
  ...
  double param2 = queryConfigurationDatabase(...);
}

All qualitative judgment aside, is there a name for the latter approach? I have encountered this pattern in multiple contexts, but never quite know how to refer to it.

How to provide an argument when importing a Python module containing class definitions?

I have a Python module which contains class definitions that needs to take an argument to configure these class definitions.

More specifically, the module contains SQLAlchemy ORM models, and the argument should e.g. be the string length for String() columns.

I don't think it's possible to provide an argument to the import mymodule statement, so what's the canonical (or best-practice) way for achieving similar functionality?

How to create weak alias default definition for interface function with multiple implementations

Objective

  • Create a generic interface with default implementations of each function pointer used in the interface.
    • This is desired in part so that we never have a null pointer reference when using an interface function pointer.
  • Support multiple "instances" of this interface (particularly for different implementations of this interface).
    • This means that we should be able to create generic interface instance of type A and a generic interface instance of type B where either instance may have function pointers using default definitions.

Result

I am using weak aliases for the default implementations however it seems as though this does not allow me to have multiple implementations of my interface and when I try to compile them in either I get static declaration follows non-static declaration errors. Removing the static keyword results in multiple definition errors.

Example code

My interface, specific and default implementation can be simplified to the following example.

dfltDef_Header.h

#ifndef __DEFAULTDEF_H_
#define __DEFAULTDEF_H_
#include <stdint.h>
#include <stdbool.h>
#define _weak_alias(old, new) \
        extern __typeof(old) new __attribute__((weak, alias(#old)))

typedef struct {
    int  (*getVal)(void);
    bool (*isTrue)(void);
} myIF_t;

int getVal(void);
bool isTrue(void);

#endif // __DEFAULTDEF_H_

dfltDef_impl.c

#include <stdint.h>
#include <stdbool.h>
#include "dfltDef_header.h"

bool dflt_isTrue(void) {
    return true;
}

int dflt_getVal(void) {
    return 3;
}

_weak_alias(dflt_isTrue, isTrue);

_weak_alias(dflt_getVal, getVal);

someInterfaceImpl.h

#ifndef __SOMEINTERFACEIMPL_H_
#define __SOMEINTERFACEIMPL_H_
#include "dfltDef_header.h"

myIF_t *getInterface(void);

#endif // __SOMEINTERFACEIMPL_H_

someInterfaceImpl.c

#include "someInterfaceImpl.h"
#include "dfltDef_header.h"

bool isTrue(void) {
    return false;
}

static myIF_t thisInterface = {
    .getVal = getVal,
    .isTrue = isTrue,
};

myIF_t *getInterface(void) {
    return &thisInterface;
}

anotherInterfaceImpl.h

#ifndef __ANOTHERINTERFACEIMPL_H_
#define __ANOTHERINTERFACEIMPL_H_
#include "dfltDef_header.h"

myIF_t *getOtherInterface(void);
#endif // __ANOTHERINTERFACEIMPL_H_

anotherInterfaceImpl.c

#include "anotherInterfaceImpl.h"
#include "dfltDef_header.h"

static int getVal(void) {
    return 1;
}

static myIF_t thisInterface = {
    .getVal = getVal,
    .isTrue = isTrue,
};

myIF_t *getOtherInterface(void) {
    return &thisInterface;
}

dflDef_App.c

#include "dfltDef_header.h"
#include "someInterfaceImpl.h"
#include "anotherInterfaceImpl.h"

int main() {
    /* DFLT_FUNC(getVal) */
    myIF_t *IF = getInterface();
    printf("%d %d\n", IF->isTrue(), IF->getVal());

    myIF_t *otherIF = getOtherInterface();
    printf("%d %d\n", otherIF->isTrue(), otherIF->getVal());

    return 0;
}

When compiled with

gcc dflDef_App.c someInterfaceImpl.c anotherInterfaceImpl.c dfltDef_impl.c -o dfltExample

I get the following:

anotherInterfaceImpl.c:4:12: error: static declaration of ‘getVal’ follows non-static declaration
    4 | static int getVal(void) {
      |            ^~~~~~
In file included from anotherInterfaceImpl.h:3,
                 from anotherInterfaceImpl.c:1:
dfltDef_header.h:13:5: note: previous declaration of ‘getVal’ was here
   13 | int getVal(void);
      |     ^~~~~~

Key questions

  • Is there a way to use static function definitions to override weak aliases?
  • Can I make one strong symbol hidden from the others (via static libraries or otherwise)?
  • Is this simply not possible or bad practice ?

It would be great to do this in such a way that the interface function definitions can only be used via the interface and if non is defined then we fall back on the default definition. Any and all help/advise is much appreciated.

What is the best pattern for event notification with different arguments?

I'm looking for an alternative pattern to the following (method 1):

public interface IEventListener {
    void onFoo(String string, Integer integer, ObjectB objectB);
    void onBar(Double d, ObjectA objectA);
}

I'm thinking something like this (method 2):

public interface IEventListener {
    void onEvent(Event event);
}

public enum EVENT_TYPE {
    FOO, BAR
}

public abstract class Event {
    EVENT_TYPE type;
    abstract EVENT_TYPE getType();
}

public class FooEvent extends Event {
    private String string;
    private Integer integer;
    private ObjectB objectB;

    @Override
    EVENT_TYPE getType() {
        return EVENT_TYPE.FOO;
    }
}

public class BarEvent extends Event {
    private Double d;
    private ObjectA objectA;

    @Override
    EVENT_TYPE getType() {
        return EVENT_TYPE.BAR;
    }
}

But I'm not sure how it is easy to use. To handle the event I need to check the event type and cast the event to the correct one, etc.

Maybe there is no alternative to method 1?

What type of design pattern is this and is a good one (approach)?

I have a Spring-based application where I have to support two types of credentials at config time which are determined at runtime and need to be passed to two types of requst builders (SOAP with JAX-WS (+ JAXB models) and plain HTTP via Apache HttpClient with a custom RPC-style XML-based approach) which will provide the rest for a client to complete the request. Most is already in place, but the credentials are tricky:

  • I don't want the builders to see the actual implementing classes of the credentials. Ideally, interfaces only.
  • I don't want to leak implemenation details of the request into the credentials too because they are fundamentally different.

What I have for the moment is (simplified) the following: SOAP requests have a builder hierarchy:

public abstract class RequestBuilder<T> {

  protected static enum AuthType {
    PLAIN, SSO;
  }

  /* Builder properties */
  protected AuthType authType;
  protected String username;

  // Plain auth
  protected String password;

  // SSO auth
  protected String ssoToken;
  protected URL ssoLoginUrl;
  protected String ssoAppId;

  ...

  public RequestBuilder<T> plainAuth(String username, String password) {
    check();
    this.authType = AuthType.PLAIN;
    this.username = validateAndReturnString("username", username);
    this.password = validateAndReturnString("password", password);

    return this;
  }

  public RequestBuilder<T> ssoAuth(String username, String ssoToken, URL ssoLoginUrl,
      String ssoAppId) {
    check();
    this.authType = AuthType.SSO;
    this.username = validateAndReturnString("username", username);
    this.ssoToken = validateAndReturnString("ssoToken", ssoToken);
    this.ssoLoginUrl = validateAndReturnObject("ssoLoginUrl", ssoLoginUrl);
    this.ssoAppId = validateAndReturnString("ssoAppId", ssoAppId);

    return this;
  }

  protected void validateAuth() {
    validateObjectState("authType", authType);

    switch (authType) {
    case PLAIN:
      validateStringState("username", username);
      validateStringState("password", password);
      break;
    case SSO:
      validateObjectState("ssoLoginUrl", ssoLoginUrl);
      validateStringState("ssoAppId", ssoAppId);
      validateStringState("username", username);
      validateStringState("ssoToken", ssoToken);
      break;
    default:
      // Cannot happen
      break;
    }
  }

  public abstract T build() throws RequestBuildException;

}

and a concrete implementation:

public class ImportRequestBuilder extends RequestBuilder<ImportRequest> {

  // Builder properties
  private Input input;

   public ImportRequestBuilder input(Input input) {
    check();
    this.input = validateAndReturnObject("input", input);

    return this;
  }

  public ImportRequest build() throws RequestBuildException {
    ImportModelObjectFactory tcOf = new ImportModelObjectFactory();

    validateAuth();
    validateObjectState("input", input);

    ImportRequest request = tcOf.createImportRequest();

    switch (authType) {
    case PLAIN:
      request.setUsername(tcOf.createUsername(username));
      request.setPassword(tcOf.createPassword(password));
      break;
    case SSO:
      request.setSsoUrl(tcOf.createSsoUrl(ssoLoginUrl.toExternalForm()));
      request.setSsoAppId(tcOf.createSsoAppId(ssoAppId));
      request.setUsername(tcOf.createUsername(username));
      request.setSsoToken(tcOf.createSsoToken(ssoToken));
      break;
    default:
      // Cannot happen
      break;
    }

    ...

    request.setInput(tcOf.createInput(sw.toString()));

    return request;
  }

}

The plain requests do not have builders at all, they basically load a template for the XML content, interpolate properties in that template and pass on to HttpClient:

HttpPost login = new HttpPost(LOGIN_PATH);

Map<String, String> vars = new HashMap<>();
vars.put("username", username);
vars.put("password", (password));

HttpEntity entity = requestUtils.mergeAndCreate(loginBody, vars);
login.setEntity(entity);
...

For SSO accordingly different along with a different loginBody.

The credentials shall be provided through an abstract factory (singleton):

public abstract CredentialsFactory {

  Credentials createCredentials();

}

along with two implementations PlainCredentialsFactory and SsoCredentialsFactory, plus

interface Credentials {

  AuthType getAuthType();

  String getUsername();

  void populate(RequestBuilder bulder);

}

Everything else is implementation private to the PlainCredentials and SsoCredentials. Now, as mentioned earlier, I don't want RequestBuilders to be aware of these two classes, but the interface only neither do I want to the opposite.

My initial design is to apply some kind of director pattern (you have to judge now) via the populate method, but this will only satisfy the SOAP builder, not the plain HTTP one. I am not happy with this design because I have to please two builder types, ugly and the Credentials have to be aware of the builder interface.

Is the above a director pattern at all or just bad coupling? An alternative approach is to use an adapter/transporter pattern with a CredentialsReceiver which could be implemented by builders and reside in the same module as the Credentials class:

interface CredentailsReceiver {

    void plainAuth(String username, String password);
 
    void ssoAuth(String username, String ssoToken, ...);

}

with that the Credentials interface would not depend on the builder interface, but any object implementing the receiver which is an adapter/transformer.

To make it a bit clearer, the plain credentials will reside in a simple properties file while the SSO credentials will require certificate-based authentication which will in turn trigger some SAML action finally issuing the username based on the client cert and along with a time-constraint token. But should not matter to the request builders at all.

WDYT?

Override function in source file

I'm building a cross platform application, and I have this:

// Gui.h
class View {
protected:
    virtual void doSomething();
};

class Window : public View {
public:
    void doSomethingElseUnrelated();
};

Now for each platform, I have my own Gui.cpp file. So there is one Gui.h file, and a Gui.cpp for each platform.

Now on the windows platform, I can just call the Window class function doSomething. However, on Mac platform, the implementation for Window class and View class doSomething is different.

So on Mac platform I have to override the doSomething function in the Window class.

That means I have to add the doSomething Window class override in the header file. This will then affect all platforms, even though it is only needed on Mac platform.

Is it possible to add the override of doSomething in the Window class only for Mac platform?

How to organize async fetching code in Reactjs

In many components, I need to fetch some data and I'm ending up with a lot of similar code. It looks like this:

const [data, setData] = useState();
const [fetchingState, setFetchingState] = useState(FetchingState.Idle);

useEffect(
    () => {
        loadDataFromServer(props.dataId);
    },
    [props.dataId]
);

async function loadDataFromServer(id) {
    let url = new URL(`${process.env.REACT_APP_API}/data/${id}`);
    let timeout = setTimeout(() => setFetchingState(FetchingState.Loading), 1000)
    try {
        const result = await axios.get(url);
        setData(result.data);
        setFetchingState(FetchingState.Idle);
    }
    catch (error) {
        setData();
        setFetchingState(FetchingState.Error);
    }
    clearTimeout(timeout);
}

How can I put it into a library and reuse it?

Simple worker thread in C++ class

Assume that there is a class which contains some data and calculates some results given queries, and the queries take a relatively large amount of time.

An example class (everything dummy) is:

#include <vector>
#include <numeric>
#include <thread>

struct do_some_work
{
    do_some_work(std::vector<int> data) 
        : _data(std::move(data))
        , _current_query(0)
        , _last_calculated_result(0) 
    {}
    void update_query(size_t x) {
        if (x < _data.size()) {
            _current_query = x;
            recalculate_result();
        }
    }
    int get_result() const {
        return _last_calculated_result;
    }
private:
    void recalculate_result() {
        //dummy some work here     
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        _last_calculated_result = std::accumulate(_data.cbegin(), _data.cbegin() + _current_query, 0);
    }

    std::vector<int> const _data;
    size_t _current_query;
    int _last_calculated_result;
};

and this can be used in the main code like:

#include <algorithm>

int main()
{
    //make some dummy data
    std::vector<int> test_data(20, 0);
    std::iota(test_data.begin(), test_data.end(), 0);

    {
        do_some_work work(test_data);
        for (size_t i = 0; i < test_data.size(); ++i) {
            work.update_query(i);
            std::cout << "result = {" << i << "," <<  work.get_result() << "}" << std::endl;
        }
    }
}

The above will wait in the main function a lot.

Now, assuming we want to run this querying in a tight loop (say GUI) and only care about about getting a "recent" result quickly when we query.

So, we want to move the work to a separate thread which calculates the results, and updates it, and when we get result, we get the last calculated one. That is, we want to change do_some_work class to do its work on a thread, with minimal changes (essentially find a pattern of changes that can be applied to (mostly) any class of this type).

My stab at this is the following:

#include <vector>
#include <numeric>
#include <mutex>
#include <thread>
#include <condition_variable>
#include <iostream>

struct do_lots_of_work
{
    do_lots_of_work(std::vector<int> data) 
        : _data(std::move(data))        
        , _current_query(0)
        , _last_calculated_result(0)
        , _worker()
        , _data_mtx()
        , _result_mtx()
        , _cv()
        , _do_exit(false)
        , _work_available(false)
    {
        start_worker();
    }
    void update_query(size_t x) {
        {
            if (x < _data.size()) {
                std::lock_guard<std::mutex> lck(_data_mtx);
                _current_query = x;
                _work_available = true;
                _cv.notify_one();
            }
        }        
    }
    int get_result() const {
        std::lock_guard<std::mutex> lck(_result_mtx);
        return _last_calculated_result;
    }

    ~do_lots_of_work() {
        stop_worker();
    }

private:
    void start_worker() {
        if (!_worker.joinable()) {
            std::cout << "starting worker..." << std::endl;
            _worker = std::thread(&do_lots_of_work::worker_loop, this);
        }
    }

    void stop_worker() {
        std::cout << "worker stopping..." << std::endl;
        if (_worker.joinable()) {
            std::unique_lock<std::mutex> lck(_data_mtx);
            _do_exit = true;
            lck.unlock();
            _cv.notify_one();            
            _worker.join();
        }
        std::cout << "worker stopped" << std::endl;
    }

    void worker_loop() {
        std::cout << "worker started" << std::endl;
        while (true) {
            std::unique_lock<std::mutex> lck(_data_mtx);
            _cv.wait(lck, [this]() {return _work_available || _do_exit; });
            if (_do_exit) { break; }
            if (_work_available) {
                _work_available = false;
                int query = _current_query; //take local copy
                lck.unlock(); //unlock before doing lots of work.
                recalculate_result(query);                
            }
        }
    }

    void recalculate_result(int query) {
        //dummy lots of work here
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        int const result = std::accumulate(_data.cbegin(), _data.cbegin() + query, 0);    
        set_result(result);
    }

    void set_result(int result) {
        std::lock_guard<std::mutex> lck(_result_mtx);
        _last_calculated_result = result;
    }
    
    std::vector<int> const  _data;
    size_t                  _current_query;
    int                     _last_calculated_result;
    
    std::thread             _worker;
    mutable std::mutex      _data_mtx;
    mutable std::mutex      _result_mtx;
    std::condition_variable _cv;
    bool                    _do_exit;
    bool                    _work_available;
};

and the usage is (example):

#include <algorithm>

int main()
{
    //make some dummy data
    std::vector<int> test_data(20, 0);
    std::iota(test_data.begin(), test_data.end(), 0);

    {
        do_lots_of_work work(test_data);
        for (size_t i = 0; i < test_data.size(); ++i) {            
            work.update_query(i);
            std::this_thread::sleep_for(std::chrono::milliseconds(500));
            std::cout << "result = {" << i << "," << work.get_result() << "}" << std::endl;
        }
    }
}

This seems to work, giving the last result, not stopping the main function etc.

But, this looks a LOT of changes are required to add a worker thread to a simple class like do_some_work. Items like two mutexes (one for the worker/main interaction data, and one for the result), one condition_variable, one more-work-available flag and one do-exit flag, that is quite a bit. I guess we don't want an async kind of mechanism because we don't want to potentially launch a new thread every time.

Now, I am not sure if there is a MUCH simpler pattern to make this kind of change, but it feels like there should be. A kind of pattern that can be used to off-load work to a thread.

So finally, my question is, can do_some_work be converted into do_lots_of_work in a much simpler way than the implementation above?

samedi 24 octobre 2020

OOD: Design a scheduler with different needs of activity frequency

I have an OOD/OOP problem, where I need to design a scheduler to output the date for certain activities with different frequencies.

For example, I can have this event to schedule every one hour, every 4 hours, every day, or every week, even every month.

I can also set the event to happen at noon, at dinner time, or before bed.

What's more, you can also set the event to happen randomly.

The output would be a list of time which will be scheduled in the future.

My original plan was, to use enum to set the frequency:

class TimeUnit(enum):
    hour
    day
    week
    month

class Scheduler():
    def __init__(self):
        self.time_table = []

    def update_timetable(self, time_unit: TimeUnit, frequency: int, start_data: datetime):
        pass
    

scheduler = Scheduler()
# As a result, the following means to set the event to happen 3 times a day.
scheduler.update_timetable(TimeUnit.day, 3, Oct.25.2020) 

But I am not sure how to design the scheduler to elegantly meet the needs of scheduling the event at a certain fixed time, like dinner time, or several fixed times like at 9 am 4 pm, and 10 pm every day.

Thank you in advance.

Share data across classess

I'm currently writing a program to read and parse ext2 filesystem C++. I split my program to a few classes, e.g. Ext2 as the main class, Superblock, etc. I have some data that I'll retreive once and I want it to be avilable to all the classes, e.g. block size, etc. What is the best way to achieve data sharing among several classes in a program without using globals (which I know are notorious)?

One way that crossed my mind is to keep those data bits as members in the main Ext2 class, and then pass reference to that instance to each class that needs to access this information via getter methods. Is there better way?

Is there a design pattern, to handle processes with multiple sets and possible failure?

I'll start with a example of the problem, for which I'm wondering if there is a actual design pattern or how to build a good "architecture" for such problems.

  • So lets say there is a resource a user can load, which has a few dependencies.
  • These dependencies can be available on the users machine, available on a server, or not available at all.
  • If a dependency is available it should be loaded - This is the default process.
  • If a dependency is not available the user should be able to load this dependency from the server, if it is available there (maybe trough a global setting event automatically)
  • If a dependency is not available on locally or on the server, the users should be able to provide it himself.
  • Also the dependency can be a different version then the users should be able to say he wants to load a different version instead ....

So just to clarify i don't want a solution to this concret problem, I'm just wondering, is there a design pattern or something, to handle such problems?

To me it seams like a multi step procedure, where every of theses steps can fail, such failures can be fixed trough some interaction, also this fixes could fail which can possible fixed aswell.

What I am thinking right now is, to encapsulate these steps, like the loading of the dependency into own objects and have have each of these objects to have a execute function, also a state which determines the failure. These failure objects themselfs can be a step object, which if succesfully continues the whole process with the next step otherwise the whole process fails.

So I'm just wondering is there a good pattern to handle suche problems, or does this has to be a complete custom solution every time? I really won't to avoid having a complete customized solution with hundereds of if/else statements and after some time no one knows how to add additional conditions or change somethings because it is a huge mess.

I'm really curious what you guys have to say about this!

Should I use singleton?

I am writing a C++ program that can read and process info of a ext2 filesystem. I figured that I should create a class named Device that will hold the file descriptor of the device and provide a method for reading from the device. An instance of this class should be instantiated once in the beginning of the program and used across multiple classes, e.g. BlockGroup, SuperBlock, etc.

Logically I shouldn't have more then one instance of this Device class, and that's a pro to use singleton. But I wonder: What risk am I taking if i don't use singleton, and just make sure that I create only one instance of this class across my application?

data validation between microservices

Lets say i have 3 micro-services books, authors, attachments.

Author wants to add cover image for book

  1. Once author select image from gallery, file gets uploaded in attachments service with author-id(user-id) which return some metadata such us {id: 1}.

  2. Second API will associate attachment to book like follow.

PUT /books/1/cover-image
payload: {id: 1}

Now Book service has to validate the following

  1. Attachment with id 1 exists or not.
  2. If exists it should verify current author(user) is owner of the attachment.

Approach 1:

  1. Create API endpoint in attachment service to verify both cases. but it endup in multiple API calls for single attachment upload.

Approach 2

  1. Once the user upload the image, instead of returning attachment id in metadata such us {id: 1} return signed id {id: sign(authorId, attachmentId, secret)}.

  2. Book review have same secret where it can decode and verify attachment-id and author-id which avoid multiple API calls.

Is there any cons with approach 2?

A OOD design question, how to elegantly prevent building duplicate stuff

I have a problem, I enum with several types of certain object

class Type(Enum):
    TYPE_A
    TYPE_B
    TYPE_C
    TYPE_D
     ....
class Something():
    def __init__(self):
        self.TYPE_A_list = []
        self.TYPE_B_list = []
        self.TYPE_C_list = []
        self.TYPE_D_list = []
        ...


    def add_data(self, type: Type, value: int):
        if type == TYPE_A:
            self.TYPE_A_list.append(value)
        elif type == TYPE_B:
            self.TYPE_A_list.append(value)
        elif type == TYPE_C:
            self.TYPE_A_list.append(value)
        elif type == TYPE_D:
            self.TYPE_A_list.append(value)
        ....

I am wondering is there any way to prevent this type of duplicate initialization? Different types can have a parent class, but how to deal with the list I need to create? Any suggestion would be helpful. Thank you in advance.

vendredi 23 octobre 2020

Convention for sharing data between web app and native apps

When you have a native app and a web app that both use the same data, what is the best/conventional way of retrieving that data? This question was partly answered here, but it suggests creating a REST API. Why not just access the database directly from both apps?

how can I make a interactive chart?

I need to develop a chart with the same conditions and way to work like the below chart used for coronavirus data:

https://ourworldindata.org/coronavirus-data-explorer?yScale=log&zoomToSelection=true&time=2020-02-01..latest&country=USA~KOR~DEU~URY~IND~BRA~ITA~IDN~ZAF~MEX~NZL~TWN~NOR&region=World&casesMetric=true&interval=smoothed&aligned=true&smoothing=7&pickerMetric=location&pickerSort=asc

who know where can I make it ?

Introduction of new concept of Linked entity in last phase of WPF application development

I'm working on a WPF desktop application with standard CRUD operations. Model of the entity which should be displayed, added, modified or deleted is pretty huge and I have a lot of view models that correspond model parts. And during development I overlooked requirement for "linked entities", which means that one entity can have (but not must) own linked entity, and while we displaying entity on UI, for properties which are missing value we displaying value of that property from linked entity. In this phase of project with 70+ view models, I really don't have idea what to do, so any suggestion will help me a lot.

Best regards, Nemanja

How to predefine the class in python? [duplicate]

I try to implement the Observer pattern with requests for subscribing and unsubscribing the updates and faced a problem. I cannot call the object of the class that was not still defined. It is a problem because I cannot just swap classes "observer" and "observable" because each of them calls another. I have something like that:

from abc import ABC, abstractmethod

class OBSERVER(ABC):
    def subscribe(self, observable: OBSERVABLE):
        observable.register(self)

class OBSERVABLE(ABC):
    def register(self, observer: OBSERVER):
        self.observers.append(observer)

How could I implement this? Is it possible?

Network Framework with Native Session Manager and different third parties support

I am creating a Networking framework which should supports native NSURLSessionManager and can adopt any third party also (Ex - Alamofire and AFNetworking) to fetch data.

Application layer will pass request to my Network manager and can instruct whether data is to be fetched from Alamofire manager or native session manager.

How can I achieve this without adding any third party code in my framework. If in future any application wants to use any other third party library that could also be supported.

Any help is appreciable.

Best way to save objects in database

The Story: I’m trying to develop a big application in PHP. The main problem is that I have to deal with the objects and I need to apply CRUD operations. Ex: Suppose we have class diagram (Compiler):

Project { name:string, statements:list …}
Statement{ type:string }
IfStatement exend Statement { condition:Exp, …}
…

The question (What is the best design for ERD or database) as I know I’ve two solutions:

  1. Serialize the main object and save it in the DB
  2. Make a table for each class in the class diagram and linking by foreign keys I’ve read about ORM but I think it’s similar to 1st solution

jeudi 22 octobre 2020

Is there a more C++ elegant implementation to complete the function jump?

In my daily work, I usually write my code like this:

int ret = 0;
ret = func1();
if(ret != 0) {
  return ret;
}
ret = func2();
if(ret != 0) {
  return ret;
}

But this means I need to complete a lot of "if(ret!=0){return ret;}",Is there a more C++ elegant implementation to complete the function jump? By the way, we are not allowed to use exception.

How to handle delete in microservice architecture?

I want to create a system for project management with task/issue/chat. This isn't anything commercial just for learning purposes. It is simplified description containing only things that are neccessary to present the problem.

First problem I had was how to add task using task service without asking project service everytime if user is a member of given project. I know that more beetwen services communications == more problems, more latency and generally AvoidBadTM. So I decided to use JWT for each microservice. User that want to add task with task service need to first ask Auth service: give me jwt for Task, projectX and include permissions. Auth would call Project service to verify if user is a member and generate proper JWT token. We still have communication beetwen services but it is a single call for a span of token lifetime instead of doing it every call to task service. Here comes the problem.

What if user is removed/banned from the project or project was deleted? If task service doesn't care about projects - it only cares if JWT is valid so user can create task X for project id Y then how to prevent banned(from project) user from accessing this service? Also if project is deleted and project service emit an event to event bus "I deleted project X" then task service read this event and removes all tasks assigned to project X. But what to do when some user still has valid access token and he creates another task after the event was processed? Task service doesn't check if project still exists and in the result we have dangling task in a database.

My solution to this problem would be to store in task service database info about existing projects. Only ids, so memory/storage footprint is minimal. So when project service emits "Project deleted event", task service would not only clear all task with given projectId but also removes stored projectId so task creation is not possible. Is this a good approach? What about banned users? Another entry in database and event to subscribe to?

How to make tinder like instant match taking caching in account (Cache and real time match)

I am working on POC for a tinder-like mobile application using flutter for mobile development and AWS serverless as the core for the business logic. Things are good so far although we experience a very interesting issue and I am not sure what is the best solution to handle it.

The problem is that I want to do a semi real-time matching like exactly in tinder. So when I open the app I will get some other users' cards to like/dislike and if I liked someone who had liked me before so it's a match. Up until now, it's straightforward as when I open the app I will get 10 users to like/dislike and each user entity includes even if he liked me or no and there is pagination so each time I get 10 users' cards from the server and caching them.

There is a scenario when for example I liked someone who just liked me 3 seconds ago so my cache isn't up to date? In this case, I will miss a match. Also, we are using Dynamodb so we are relaxing updating the records so that's means I will not do any comparison before updating the record on the server-side. Also, I don't want to send a request to the server to get cards one by one so the performance will be not that good. So what to do in that case?

Also, designing way, Is it better ideas on how to that using server caching, queues, long polling, or any simple idea? Also, I am delighted to know how that's already implemented in the tinder app itself?