lundi 31 août 2020

Handle duplication when application polling in cloud

We have a scenario that we need to check after some interval that whether all the results are completed/processed in db against a particular id or not, and if it is then we need to make a file and send it to some bucket.

This logic is written in spring application. Now the problem is I have a concern that once we deploy that application to cloud than if there are 10 instances running of an application then there is a chance that the file could be placed multiple times on the bucket.

I don't want to implement something outside of an application (but open to any suggestion if it's not possible). May be using some db flags could help but I think that is not right or messy as all instances would be processing something before checking at the end that the file is already processed.

Please let me know on this. Thanks!

P.S. I am using GCP as cloud provider.

Cant make an appropriate abstraction when dealing with generic method (C#)

Im trying to implement a wrapper for using System.Data.SQLite features in order to get rid of duplicate code in a good OOP manner. So, i have the following generic method:

    public T SendSelectQuery<T>(string sql, Func<SQLiteDataReader, T> processResult) where T : IDBResult
    {
        try
        {
            using (var dbConnection = new SQLiteConnection("path"))
            using (var cmd = new SQLiteCommand(sql, dbConnection))
            {
                dbConnection.Open();

                cmd.CommandType = CommandType.Text;

                using (SQLiteDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                {
                    return processResult(rdr);
                }
            }
        }
        catch (Exception ex)
        {
            return T??????
        }
    }

T is a result object, i.e.:

    public interface IDBResult
{
    bool Completed { get; set; }
    string Exception { get; set; }
}

public abstract class CustomDBREsult : IDBResult
{
    public bool Completed { get; set; }
    public string Exception { get; set; }

    public string Payload { get; set; }
    public CustomDBREsult(bool Completed, string exception, string Payload)
    {
        this.Completed = Completed;
        this.Exception = exception;
        this.Payload = Payload;
    }
}

public class SuccessCustomDBResult : CustomDBREsult
{
    public SuccessCustomDBResult(string Payload) : base(true, string.Empty, Payload)
    {

    }
}
public class ErrorCustomDBResult : CustomDBREsult
{
    public ErrorCustomDBResult() : base(false, "exception", string.Empty)
    {

    }
}

I want to call SendSelectQuery<CustomDBREsult>(...) and get an instance of CustomDBREsult child.

As you may have already noticed the problem occurs in catch segment where i need to return a T object, but i cant instantiate an approprite Error object derived from CustomDBREsult.

I could change return type of SendSelectQuery<T> to IDBResult and return in catch segment smth like this:

    public class DefaultDBError : IDBResult
    {
        public bool Completed { get; set; } = false;
        public string Exception { get; set; } = "db exception";
    }

But in this case i would need to cast the result of SendSelectQuery<T> from IDBResult to T. And it doesn't seem to be a very good practice.

    IDBResult res = DBMethods.SendSelectQuery<CustomDBREsult>("sql query", processResult);
    if (res is CustomDBREsult cdbres)
    {

    }
    else if (res is DefaultDBError ddberror)
    {

    }

The other option is to "lift up" try catch block and use SendSelectQuery<T> inside it, but i would need to duplicate this block everywhere i use SendSelectQuery<T> and still convert IDBResult to T.

If smn managed to understand me, would appreciate your comments. I guess my problem is making good abstractions of logic.

What design pattern to use for instantited objects containing permutations of a string?

I would like to know if there is a design pattern to cover making multiple objects representing mutiple permutations of a string. For example:

I have a database table containing item names. Each item has a sort of "signature" (can't think of a better word for it), which is all the letters of the item name, sorted in alphabetical order with the spaces removed.

Given a "soup string" of jumbled up letters, I would like to sort those letters in alphabetical order to match it to a signature in the database, but here's the catch...

Each soup string may contain a few extra letters. So what I'm looking for is a design pattern which would be suitable for taking a string and returning a list of objects, each representing a permutation of that soup string, which I can then fire at the database.

I was thinking about just using a factory, but isn't this outside of the scope of a factory? It does contain logic, (am I right in saying this is not business logic?), but perhaps this is acceptable for a factory or factory method? Then again, perhaps this is an perfect usecase for a factory.

Ultimately, I will probably just go with the factory method. I just wanted to see if there was a better option.

Thanks in advance.

Iterate over list of methods and take the first non null response

I have three functions. Input and output parameters of all three functions are same.

Let's say

public void String function1(String abc, String xyz);
public void String function2(String abc, String xyz);
public void String function3(String abc, String xyz);

I have a caller function which is implemented like

public void String callerFunction(String abc, String xyz) {
     String output = function1(String abc, String xyz);
     if(output == null) { 
          output = function2(String abc, String xyz);
     } 
     
     if(output == null) { 
          output = function3(String abc, String xyz);
     } 
     return output;
}

While this code works, what's the best way to write this kind of logic, i may want to add a new function4 also in the future.

One way that comes in my mind is

public interface functionInterface {
      public String fetchValue(String abc, String xyz);
} 

public class function1Class {
      public String fetchValue(String abc, String xyz) {
         // return some string.
      }
} 

public class function2Class {
      public String fetchValue(String abc, String xyz) {
         // return some string.
      }
} 

public class function3Class {
      public String fetchValue(String abc, String xyz) {
         // return some string.
      }
}


public void String callerFunction(String abc, String xyz) {
     List<functionInterface> flist = new Arraylist<>();
     functionInterface f1 = new function1Class();
     functionInterface f2 = new function1Class();
     functionInterface f3 = new function1Class();
     flist.add(f1);
     flist.add(f2);
     flist.add(f3);
     
     String output = null;
     for(functionInterface f : flist) { 
         output = f.fetchValue(abc, xyz);
         if(f.fetchValue(abc, xyz) != null) {
            return output;
         }
     }
     return output;
}
  • Is this over engineering ?
  • Is there a better way to handle this use case ?

While designing a State Machine what are the strategies for achieving consistent states?

Suppose I have a state machine that goes from state 1 to state 2 and to transition from 1 to 2 some actions need to be taken like performing CRUD operations on other services .Now suppose while transitioning from state 1 to state 2, the thread gets killed (some actions are performed and others are not) then in that case the State machine would be in a state that is neither completely state 1 nor state 2. What is the best way to handle these type of inconsistencies. One way that I can think of is making all the steps transactional (using patterns like 2PC or saga), other way is by making all the operations (involved in transition) idempotent and performing all the operations again. Is there any other better way to handle these type of inconsistencies in state machines?

Builder pattern deserialize with jackson not working

I try to handle request

{
  "city": "city",
  "date": "2020-08-26T12:15:54.428Z",
  "time": {
      "sum":"123"
  }
}

My goal is to process this request. The trick is that I try to use Builder pattern with optional parameter(according to Effective Java. Joshua Bloch). As I understand I dont have to send all time values. Only sum is required. I try to send Sport object in my RequestBody to my controller by Postman.

So I created POJO class for my Sport:

@Entity
@Table(name = "sport")
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Sport {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "date")
    private Date date;

    @Column(name = "city")
    private City city;

    @Type(type = "time")
    private Time time;
}

and Time builder:

package pl.project.model;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;

@JsonDeserialize(builder = Time.Builder.class)
public class Time {
    private final String bike;
    private final String run;
    private final String sum;

    private Time(Builder builder) {
        bike = builder.bike;
        run = builder.run;
        sum = builder.sum;

    }

    @JsonPOJOBuilder(withPrefix = "")
    public static class Builder {

        String bike = "-";
        String run = "-";
        final String sum;

        Builder(String sum) {
            this.sum = sum;
        }

        Builder bike(String bike) {
            this.bike = bike;
            return this;
        }

        Builder run(String run) {
            this.run = run;
            return this;
        }

        Time build() {
            return new Time(this);
        }

    }
}

And still getting error:

JSON parse error: Cannot construct instance of `pl.project.model.Time$Builder` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `pl.project.model.Time$Builder` (although at least one Creator exists): cannot deserialize from Object value (no delegate- or property-based Creator)\n at [Source: (PushbackInputStream); line: 14, column: 7] (through reference chain: pl.project.model.Sport[\"time\"])"

I tried many stackoverflow solutions but nothing works for me.

Does anybody could help me?

dimanche 30 août 2020

Best Practices for Streaming Service

I am new to Messaging queue tools and Design patterns,

My requirement is as follows:

  1. Consume a message from IBM MQ
  2. Retrieve a record from Oracle DB based on message received from IBM MQ
  3. Publish the record to Kafka Topic

All the above steps should happen in real time.

I am trying to create one artifact for each:

  1. Database: for db related stuff with JPA repositories and all
  2. Kafka: Which has Both kafka producer and consumer functionality
  3. IBM MQ: Similar to Kafka, Which has Both IBM producer and consumer functionality
  4. Service: Which contains the business logic like above (retrieves DB record and publish to Kafka topic)

In the above requirement my triggering point is MQ listener Where "IBM MQ" has "Service" artifact as one of its dependency, But if I want to publish something to MQ in future, I have to add "IBM MQ" as dependency to "Service" which leads to cyclic dependency So What's the best approach?

Any suggestions will be helpful, Thanks in advance.

How to apply Factory Pattern, Interface does not have method (belongs to implemented class)

I am applying Factory Pattern. There is an interface and two classes inherit from the interface.

Also, I created a class whose role is create an factory object. If I created factory object, there is an error. "No overload method". Because this method not in the interface.

How to implement factory method with factory object, for extra method.

        [Test]
    public void XML_Deserialize_ToObject_FromURL_WithRootAttirbuteName()
    {
        var xmlSerializerTCMB = GenericSerializer<Tarih_Date>.CreateSerializerObject(DataFormatType.XML);

        var kur = xmlSerializerTCMB.DeserializeFromLink("https://www.tcmb.gov.tr/kurlar/today.xml", "Tarih_Date");

        Assert.IsTrue(kur.Currency.Length > 0);
    }

Pieces of code listed below

Interface

public interface IGenericSerializer<T>
{
    void SerializeToFile(T objectData, string fileName);
    string SerializeToString(T objectData);
    T DeserializeFromFile(string fileName);
    T DeserializeFromString(string mediaTypeString);
    T DeserializeFromLink(string link);
}

XmlGenericSerializer, this method have extra method(DeserializeFromLink) which is not belongs to the interface.

public class XmlGenericSerializer<T> : IGenericSerializer<T>
{
    public T DeserializeFromFile(string fileName)
    {

    }

    public T DeserializeFromLink(string link)
    {

    }

    public T DeserializeFromString(string xmlString)
    {

    }

    public void SerializeToFile(T objectData, string fileName)
    {

    }

    public string SerializeToString(T objectData)
    {

    }

    public T DeserializeFromLink(string link, string xmlRootAttributeName)
    {

    }
}

JsonGenericSerializer

 public class JsonGenericSerializer<T> : IGenericSerializer<T>
{
    public T DeserializeFromFile(string fileName)
    {

    }

    public T DeserializeFromLink(string link)
    {
        
    }

    public T DeserializeFromString(string jsonString)
    {
       
    }

    public void SerializeToFile(T objectData, string fileName)
    {            
        
    }

    public string SerializeToString(T objectData)
    {
         
    }
}

Factory class

        public static class GenericSerializer<T>
{ 

    public static IGenericSerializer<T> CreateSerializerObject(DataFormatType dataFormat)
    {
        IGenericSerializer<T> serializer = null;
        switch (dataFormat)
        {
            case DataFormatType.XML:
                serializer = new XmlGenericSerializer<T>();
                break;
            case DataFormatType.JSON:
                serializer = new JsonGenericSerializer<T>();
                break;
            default:
                break;
        }

        return serializer;
    }
}

Factory method pattern & data abstraction in C++

I try to implement the Factory Method Pattern in C++ while keeping a good level of abstraction. In the sample provided in the link, all derived classes are in the same file, but this is usually not the case.

  1. Without header files for derived classes: To keep implementation details, I didn't provide a header file for the derived class (declaration & definition in the source file), then I don't see how to implement the factory method because the derived classes are not visible and forward declaration is not possible.

  2. With header files for derived classes: I can implement the factory method, but the implementation details of derived classes leak because the private members and methods have to be declared in the header.

Maybe using the PImpl idom can help to solve the problem in case 2) but I wonder if this is correct/reasonable approach. What is the usual/best way to implement this pattern in C++ ?

Here is my code:

//graphic-api.hpp

class GraphicApi {
public:

    enum class Type {
        //OPENGL,
        //DIRECTX,
        VULKAN
    };

    virtual void render() = 0;
    virtual ~GraphicApi() {};

    static std::unique_ptr<GraphicApi> make(const Window& window, Type type);

};

//graphic-api.cpp 

//need to include headers for derived classes
std::unique_ptr<GraphicApi> GraphicApi::make(const Window& window, GraphicApi::Type type) {
    switch (type) {
    case GraphicApi::Type::VULKAN:
        return std::make_unique<VulkanApi>(window);
    default:
        assert(0 && "Unsupported Graphic API");
    }
    return nullptr;
}

//vulkan-api.hpp
class VulkanApi : public GraphicApi {
public:
    VulkanApi(const Window& window);
    virtual void render() {};

private:

    // lot of private members & methods related to Vulkan API (not nice to see here)     
    vk::UniqueInstance instance;
    ...
};

samedi 29 août 2020

Printing company wants 300 dpi,but in adobe Illustrator there is 300 ppi

I have already created 96 pages for book with Ai,but there's only 300 ppi option. Printing company wants 300 dpi,what I need to do?pls help.. Do I need to start everything from begining with Photoshop.... And if no. what parametres I should put for exporting pdf?

How to apply MVC and Decorator Pattern correctly to JavaFX?

I'm working on a project in JavaFX where I have defined a sort of "window-container", with custom controls to close the application or minimize it to an icon. Inside the AnchorPane that defines the scene, I have put a BorderPane that replaces its center with other Nodes when the application needs to go from a view to another.

Since I'm applying (or trying to, at least) MVC-pull-model, for every scene that my application needs, I have a view composed of an FXML file + the class that extends the JavaFX.Application class, a controller split in Graphic-Controller (to manage graphical elements with @FXML annotations) and Logic-Controller (to manage business logic and request to the model through beans).

I think that the MVC pattern is applied correctly, but I really accept suggestions and corrections.

However, until now I used to do this thing inside the Window Container Controller to replace the center node of my window-container's BorderPane.

public class WindowContainerController {
     private BorderPane container;

     public void replace(View node){ 
          this.container.setCenter(node.getRoot);
     }
     
}

Where View is a class that load FXML files through the help of an enum (ViewType) that contains the FXML paths. I posted the code below.

Since this thing requires that every Logic or Graphic controller has a reference to the WindowContainerController in order to obtain the container attribute, I don't know if this violates MVC, due to the fact that I have relationships between controllers (I don't know if controllers can talk to each other in MVC)

In order to fix this thing, I thought to the Decorator Pattern, to "decorate" the window-container borderpane with other nodes, but I don't understand how to apply the pattern correctly with the JavaFX framework since it requires the start() method to start render the application.

Is it correct to apply Decorator, or I should use other patterns? If I'm right, how can apply Decorator with JavaFX?

public class View {
    private Parent root;
    protected View(ViewType view) {
        try {
            FXMLLoader loader = new FXMLLoader(ViewType.getUrl(view));
            setRoot(loader.load());
        } catch (IOException e) {
            AlertFactory.getInstance().createAlert(e);
        }
    }

    public Parent getRoot() {
        return root;
    }

    public void setRoot(Parent root) {
        this.root = root;
    }

}

Similar responsibility with different entities and better approach

I'm modeling a application that will send messages to users (sms,email, messaging apps and etc). Since i've made a similar project before, theres some problems i'm trying to avoid when modeling now. Some are:

1- The responsability for writing the message's text got along too many different classes

2- There were too many very-similar methods, like "sendWelcomeMail()" and "sendGiftMail()"

3- Message pojo accumulated way too many attributes

I'm looking ahead at those problems now and for future implementations.

That's my current implementation idea:

/** Interface that define behavior for all services reponsible for messaging */
public interface IMessageService{
   public String send(String to, String message);
   public String write(IMessage message, EventEnum events);
}


/** Example of a service*/
public class EmailService implements IMessageService{
 //... 
     @Override
     public String write(IMessage message, EventEnum event){
     if(event.getId == 1){
     return writeWecolme( (MailTemplate) message);}
     }
}


/** Interface that define a generic message template*/
public interface IMessage{}

/** Model that represent a Email message */
public class EmailTemplate implements IMessage{
 String emailAttribute;
 String otherAttribute;
 //getters and setters
}

/** Enum with possible events*/
public enum EventsEnum{
 WELCOME(1,"Welcome"), PRODUCT_SENT(2,"Product sent");
//...
}

There's some points to discuss about:

1- Is the actual IMessage a good design approach? Initially I had defined methods like toWelcome() and toProductSent(), but not all implements of a IMessage will have those behaviors

2- There's a cleaner alternative to the method write(...)? I thinks this method may get overwhelmed as Events increase

3- Should I define a POJO for each message template (eg WelcomeEmailTemplate) or a generic one for each kind of message(eg. EmailTemplate or TelegramTemplate)?

4- Should I define different interfaces for each pojo "family"?

PHP Regex special characters to include quotations

I have this JavaScript code which allows me to detect if a string contains any special characters including single and double quotations...

if (/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?`~]/.test(string) === false) {
    //...
}

However when I try to do this in PHP the regex is invalid since PHP regexes have to be in quotations.

if (!preg_match('/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?`~]/', $string)) {
    //...
}

How would I use this JavaScript regex in PHP? I cannot figure out a way to have a special character regex that includes quotations.

Operation in composite design pattern vs add a new visitor in visitor design pattern

Eric Gamma's Design Patterns book explains that a composite structure may declare operations:

https://i.stack.imgur.com/OGqbO.png

Such operations are propagated recursively by non-leaf operators.

On the other hand, we may get the same result by using a visitor design pattern to create visitors that visit the composite structure and do the operation.

So, is there any reason why one would chose to add an operation in the composite rather than creating a new visitor for each desired operation? Or vice versa?

Computer Science - learning materials needed [closed]

Can someone help me with some good learning materials/ links/ anything... for the subjects below?

  1. Microsystems. Main modules and their functional roles (Structure and function). Data transfer methods between the CPU and the I/O devices.
  2. Instruction-level parallelism and its exploitation. Scalar pipeline processors. Multiple instruction issue processors. Multi-processors. Methods for exploiting thread-level parallelism.
  3. Processes and threads: description, scheduling and synchronization. Virtual memory. Disk space management.
  4. Abstract data types: lists, stacks, queues. Classes. Encapsulation. Inheritance. Polymorphism. Operators overloading. Exception handling.
  5. General solving methods: backtracking, greedy, dynamic programming, A*.
  6. Design patterns. Object oriented design principles.
  7. Game trees. Search in game trees. Blind and heuristic search in state space. Rote learning.

Correct way to fetch data via API in React

I am learning javascript and React and the challenge (on Hackerrank practise) is to fetch data from an API which has multiple pages. There should be as many buttons as the number of pages and on clicking each button, the data from that particular page should show up below like: enter image description here

Here is the component that I wrote:

import React from 'react';

const url = "https://jsonmock.hackerrank.com/api/articles?page=";
const default_page = 1;

class Articles extends React.Component {
  state = {
    pageCount: 1,
    body: {},
    currentPage: 1,
    error: null,
    isLoading: false,
    data: []
  };

  componentDidMount(){
    this.setState({isLoading: true});
    fetch(url+default_page)
    .then(response => response.json())
    .then(body => this.setState({
      pageCount: body.total_pages, 
      data: body.data,
      body: body,
    }))
    .catch(err => this.setState({error: err}));
  }

  pageButtonGenerator(){
    if(this.state.body){
      let pageButtons=[];
      for(var i=1; i<=this.state.pageCount; i++){
        const id = i; //need this to use in event handler, BUT WHY DOES i NOT WORK (the value is always i=this.state.pageCount)
        pageButtons.push(<button data-testid="page-button" key={"page-button-"+i} onClick={(e) => this.buttonClickHandler(id)}>{i}</button>);
      }
      return pageButtons;
    }
    else{
      return <button data-testid="page-button" key="page-button-1">1</button>
    }
  }

  buttonClickHandler = (pageNum) => {
    // console.log(pageNum);
    this.setState({isLoading: true});
    fetch(url+pageNum)
    .then(response => response.json())
    .then(body => this.setState({
      pageCount: body.total_pages, 
      data: body.data,
      body: body,
      currentPage: pageNum
    }))
    .catch(err => this.setState({error: err}));
    // this.titlesGenerator();
  }

  titlesGenerator = () => {
    if(this.state.data){
      return this.state.data.map((element,index) => {
        if(element.title){ return <li key={"title-"+index+1} data-testid="result-row">{element.title}</li> }
        else{ return null }
      })
      // console.log(this.state.data);
      
    }
  }

  render() {
    return (
      <React.Fragment>
        <div className="pagination">
          {this.pageButtonGenerator()}
        </div>
        <ul className="results">
        {this.titlesGenerator()}
        </ul>
      </React.Fragment>
    );
  }
}

export default Articles;

Although my code passed the test cases, I am not very confident if I did it the right way. I have my doubts like:

  1. Should I be fetching all the pages in one go to avoid multiple network calls or should a call be made every time a page button is clicked?
  2. Am I generating buttons the right way (see the pageButtonGenerator)?
  3. Inside the for-loop in pageButtonGenerator, am I calling the onClick handler the right way? I was trying to directly pass the variable "i" but it was always = 6 (the exit value of the loop). I am struggling to understand why the variable i was also 6. I thought the closure would ensure that the value is always correct..
  4. How should I go about what to store in state and what should be derived and not stored?

Open to constructive criticism. Thanks

What is the difference between the builder design pattern and using classes that inherit from other?

Recently I'm studying design patterns and I've been seeing a pattern called builder that in theory is supposed to encapsulate the complexity of a class, and this is the example I've been practicing:

class ExampleBuilder
{
    static void Main(string[] args)
    {
        Kitchen kit = new Kitchen();

        // One pizza 
        kit.NextPizza(new FourCheeseBuilder("Family"));
        kit.PreparePizza();
        var FourCheesePizza = kit.PizzaComplete;

        // Another pizza
        kit.NextPizza(new HawaiianBuilder("Small"));
        kit.PreparePizza();
        var HawaiianPizza = kit.PizzaComplete;
    }
}

// Final Product
public class Pizza
{
    public string Dough { get; set; }
    public string Sauce { get; set; }
    public string Stuff { get; set; }
    public string Size { get; set; }
    public bool BeenFolded { get; set; }

    public Pizza()
    {

    }

    public Pizza(string Size, string Dough, string Sauce, string Stuff, bool BeenFolded) : this()
    {
        this.Size = Size;
        this.Dough = Dough;
        this.Sauce = Sauce;
        this.Stuff = Stuff;
        this.BeenFolded = BeenFolded;
    }
}

// Builder
public abstract class PizzaBuilder
{
    // Protected para que las clases que implementen puedan acceder
    protected Pizza _pizza;
    public string Size { get; set; }

    public Pizza ObtainPizza() { return _pizza; }



    // Un paso para cada una de las propiedades
    public virtual void PasoPrepararDough()
    {

    }

    public virtual void PasoAñadirSauce()
    {

    }

    public virtual void PasoPrepararStuff()
    {

    }

    public virtual void PasoDoblarPoizza()
    {

    }

}

// BuilderConcrete
public class HawaiianBuilder : PizzaBuilder
{
    public HawaiianBuilder(string size)
    {
        _pizza = new Pizza
        {
            Size = size
        };
    }
    public override void PasoPrepararDough()
    {
        _pizza.Dough = "Soft";
    }

    public override void PasoAñadirSauce()
    {
        _pizza.Sauce = "Sweet";
    }

    public override void PasoPrepararStuff()
    {
        _pizza.Stuff = "pineapple, tomato, ham";
    }
}

// Another BuilderConcrete
public class FourCheeseBuilder : PizzaBuilder
{
    public FourCheeseBuilder(string size)
    {
        _pizza = new Pizza
        {
            Size = size
        };
    }
    public override void PasoPrepararDough()
    {
        _pizza.Dough = "Coocked";
    }

    public override void PasoAñadirSauce()
    {
        _pizza.Sauce = "Roquefort";
    }

    public override void PasoPrepararStuff()
    {
        _pizza.Stuff = "mozzarela, gorgonzola, parmesano, ricotta";
    }
}

// Director
public class Kitchen
{
    private PizzaBuilder _pizzaBuilder;

    public void NextPizza(PizzaBuilder pizzaBuilder)
    {
        _pizzaBuilder = pizzaBuilder;
    }

    public void PreparePizza()
    {
        _pizzaBuilder.PasoPrepararDough();
        _pizzaBuilder.PasoAñadirSauce();
        _pizzaBuilder.PasoPrepararStuff();
    }

    public Pizza PizzaComplete
    {
        get { return _pizzaBuilder.ObtainPizza(); }

    }
}

I had to do all that staff to define two types of different classes, and I don't understand why is these better than do this:

 class ExampleBuilder
{
    static void Main(string[] args)
    {

        //One Pizza
        var FourCheesePizza2 = new FourCheese2("Family");

        //Another Pizza
        var HawaiianPizza2 = new HawaiianPizza2("Small");
    }
}

// Final product
public abstract class Pizza2
{
    public string Dough { get; set; }
    public string Sauce { get; set; }
    public string Stuff { get; set; }
    public string Size { get; set; }
    public bool BeenFolded { get; set; }

    public Pizza2()
    {

    }

    public Pizza2(string Size, string Dough, string Sauce, string Stuff, bool BeenFolded) : this()
    {
        this.Size = Size;
        this.Dough = Dough;
        this.Sauce = Sauce;
        this.Stuff = Stuff;
        this.BeenFolded = BeenFolded;
    }
}

public class HawaiianPizza2 : Pizza2
{
    public HawaiianPizza2(string size)
    {
        Size = size;
        Dough = "Soft";
        Sauce = "Sweet";
        Stuff = "pineapple, tomato, ham";
        BeenFolded = false;
    }
}

public class FourCheese2 : Pizza2
{
    public FourCheese2(string size)
    {
        Size = size;
        Dough = "Coocked";
        Sauce = "Roquefort";
        Stuff = "mozzarela, gorgonzola, parmesano, ricotta";
        BeenFolded = true;
    }
}

I get the same result but occupying much less lines of code, and that's why I don't know what the pattern builder is really for.

vendredi 28 août 2020

is it possible to predict next number in random card game? [duplicate]

i saw many questions about this topic. but it is not clear enough. i have a card game where user needs to chose between 1 to 5 number if the number is correct it will give him points. i have a large file contains numbers appears each time i ran the program. but how i could reverse it to find a pattern to predict the next winning number?.

example: first game:

-Choose number between 1 and 5!
user: 5
- the winning number is 1. no point added

second game:

-Choose number between 1 and 5!
user: 3
-the winning number is 3. 10 points added

Can you help me solve this algorithm? [closed]

enter image description here* The height and width will be entered on the keyboard.Create the pattern below. Height=Total number of lines Width=Number of character fields between "|" character *

How to serialize a buffer

I am given with a buffer of bytes like {0x01, 0x02, 0x02, 0x02, 0x12, 0x01, 0x02, 0x06, 0x01, 0x02, 0x03, 0x04, 0x02, 0x02, 0x12, 0x07, 0x08, 0x06, 0x09, 0x0A, 0x0B, 0x0C} here first byte stands for data type in this case 0x01 which stands for an array next byte is 0x02 means number of elements in the array, i. e. Here it is 2 means this array contains 2 elements, from next byte elements of array start in which first byte represent the datatypes followed by data in this case it is 0x02 which means a structure, next byte 0x02 means number of elements are 2 in this structure after that first element of the structure starts, 0x12 means unsigned int that has 2 bytes 0x01, 0x02, after that second element of the structure that is 0x06 which means unsigned long and has 4 bytes after that 2nd element of the array start that is again a structure same as first element of array.

In short, this buffer is a collection of different data types along with their data. Can some one help me to serialize this buffer.

Java class design for redundant variable property

Consider

Class A {
    private Map<String, String> AXMap;
    private Map<String, String> A1Map;
    private Map<String, String> A2Map;
    private Map<String, String> A3Map;
}
ClassB {
    public void someMethod() {

    List<ClassA> classAList = new ArrayList...
    for i..0 to n {
        ClassA classA = new ClassA();
        populate A1Map;
        populate A2Map;
        populate A3Map;
        classAList.add(classA)
    }
}

The crude logic above is just that A1Map, A2Map, A3Map are populated for each ClassA of the loop and added to the final list. My design question is AXmap remains the same for all the iterations. Even if I populate once, the same redundant AXmap is in every object of ClassA list. I do need the AXmap along with other maps. Is there a better java design principle. All I could think was in terms of inheritance, final or Move AXMap to separate class and add as composition etc

ssh request on old conection is giving EOF eventually

I work on agent demon which runs on a node. When we start the agent, all the ssh connections to the other nodes are built and later on at particular time intervals(weekly once) we create new sessions on these ssh connections to communicate with the other nodes. but it has been observed that after 1 month around the time frame, the session creation would give EOF error.

      User: config.Username,
      Auth: []ssh.AuthMethod{
         ssh.Password(config.Password),
      },
      HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
         return nil
      },
}
client, err := ssh.Dial("tcp", config.Host+":22", sshConfig)
session, err := client.NewSession()
defer session.Close()
b, err := session.CombinedOutput(command)

When this session creation gives EOF error, is there any way to get back the ssh connection in working state?

If I consider redialing or reconnect when only if I get error on read/write then which design pattren will be useful here.

Thanks

The struggle of the provider pattern

I have a split opinion to providers. On one hand it is very nice to just make data kind of "public" in a specific scope, but on the other hand it's very much not self-explanatory and kind of works against my understanding of "component driven design" which should ensure context-independent functionality of single components.

Example:

<ThemeProvider>
  // works since it has provided data
  <ThemedButton />
</ThemeProvider>

// does not work since provided data is missing
<ThemedButton />

In that example the developer needs to know about ThemeProvider and how to use it, if he wants to use ThemedButton.

I am a freelancer, so I face new projects quite often, and as soon as there is some usage of providers, I can't really find them by myself but have to get help of another developer that has advanced knowledge of the project.

I'm wondering if there is a way to actually make the provider pattern more self-explanatory, so a new developer can figure out about it easily by just reading the code.

Btw: I'm a JS developer preferring React if that helps.

Why do we need NoOp types?

Note: This is not a Swift-only question, it's related in every language with Optional type.

I see some Swift projects doing that: var foo: Foo = NoOpFoo() AFAIK this basically means "this foo does nothing" and can be also expressed as var foo: Foo? = nil

I'm wondering what can be the reason(s) behind NoOp-instead-of-Optional decision?

  1. I can think of performance first: Optional seems to add a few more lines to assembly output (but I'm not really convinced with that).
  2. The reason could be boilerplate of unwrapping optionals as well: but most of the examples I've seen are types that don't even return values, therefore call sites don't need to unwrap neither.
  3. There could be historical reasons too, for example in Java it's tricky to deal with NullPointerException so NoOps may come handy... but in Swift?

Here is an example from swift-log project:

public struct Logger {
    var handler: LogHandler
    internal init(_ handler: LogHandler) {
        self.handler = handler
    }
}
public struct SwiftLogNoOpLogHandler: LogHandler { ... }

Logger is designed to work with a LogHandler; to my understanding if you pass NoOpHandler to your Logger then you should probably turn your yourLogger: Logger into myLogger: Logger? = nil

Real-world use cases and/or your personal experiences would be much appreciated!

How to draw the below patterns on the path which is drawn using the Point

It was easy if we used the rectangle to connect.Since we used the points to draw path and set the strokeWidth to look like rectangle. Can someone please help us to draw the below 3 patterns on path (which is just 2 points connected with strokeWidth)

enter image description here

Design CacheService for Cassandra to get data by cluster keys

Overview: We are using Cassandra to store cache in our application.we have table itinerary having a (partition key, cluster key 1, cluster key 2) Primary key and payload column. The current implementation has CacheService[T: Key] which has 3 methods get, update, delete. We have ItineraryService[T: Key] which is implementing these 3 methods. In current get method implementation, we are getting data by using partition key only. This CacheService is also implemented by other services.

Problem: The problem is sometimes we need data by cluster key 1 or cluster key 2. Now we have only one itinerary service we can't change the implementation.

Solution: The solution that I have in my mind will create one more abstraction layer and there I will create method getByClusterKey1 and getByClusterKey2. I can't do in ItineraryCache Service as I explained CacheService is implemented by other services also.

Expected Solution: I wants to pass some Map[Key, ColumenName]. If I can fetch the data in Cassandra directly I will build query accordingly otherwise I will get all data and then will filter. I know about query order so I will check up to which cluster key I can build a query and then leave others and filter out later.

Please suggest me something if you guys already build something like this. I want to build a loosely coupled design.

jeudi 27 août 2020

flutter appbar borderRadius 1.20.0

i'm trying to give a little change in my flutter appbar design. I wanna give borderRadius to appBar and two important conditions are there. First, i want the appbar to have only two borderRadius, bottom-left and bottom-right. Second, i want that two borderRadius-edges are tipped over toward bottom(the main screen: body), so that the appbar looks like 'i have to legs under my bottom side!', ie the bottom left leg and bottom right leg, and these legs would look like a square subtracted by a quarter circle. If it is done, the body of scaffold would look like an iPhone XS screen without notch because they have default top-left&top-right borderRadius(== the two legs). I know this design is quite odd and uncommon, but i wanna know if it is possible, and if so, HOW!! If not possible, please let me know!

Thank you in advance [:

Facade Object having DataBase connection?

my application usecase has facade object as variable to handling some specific api, and i want to insert return of facade's method into database

here's my question is it OK to Facade Object has repository(database connection) by field or parameter? usecase object has database connect as field, and i used to handle database connection on my usecase Layer

pros facade can handle full process, usecase has more simple logic

cons idk, access database connection on two Layer(usecase, facade) may cause problem or software dept?

sry for poor english, i'm very novice for this and it confuse me as hell

How to model protobuf proto file

My application has various clients (say for example Client1, Client 2, Client3 ....and so on). Clients share some generic properties and has some unique data.

In my .proto file I want to model this kind of behavior. I came up with :

message MyClientsData {
    BaseClientData baseData;
    Client1SpecificData client1;
    Client2SpecificData client2;
... and so forth...
}

BaseClientData is the common data across all clients.

This works for simple use case when number of clients are very limited, but becomes hard to read if it grows. Is there some good practice on how to handle this kind of situation when there are unique data across different deserialization request?

Powershell multiline pattern matching and picking those lines

I am trying to pick the lines from a log file based on multi-line match. How do we achieve this with Powershell?

LogFile:
Date: 2020-05-06 2:30:33 PM
Name: ABC.txt
{text}
{text}
{text}
Date: 2020-04-08 3:30:33 PM
Name: PQR.txt
{text}

Pattern I am trying to match is -
Date:
Name:

I want to pull all the lines with this pattern. I tried the below line but it doesn't work.
get-content $log_file | select-string -pattern "(?ms)Date:.\nName:." -AllMatches

Output I am looking is -
Date: 2020-05-06 2:30:33 PM
Name: ABC.txt
Date: 2020-04-08 3:30:33 PM
Name: PQR.txt

After this I want to create an array or a tabular format data(preferred) as -
Date|Name
2020-05-06 2:30:33 PM|ABC.txt
2020-04-08 3:30:33 PM|PQR.txt

Thanks for all your support!!!!

Clarifications and Concrete examples of Software Architecture Patterns

I am studying Software Architecture Patterns and I am struggling to relate these patterns to modern development stacks and frameworks in a concrete way. It feels like there is a disconnect between learning design patterns / architecture patterns and then writing actual code.

For example, if you take the example of a react application, using redux for state management, with a Node / Express API, which uses mongoose as an ORM to access a MongoDB (so basically the MERN stack), which architecture is this? I could see making an argument for a layered / n-tier pattern, a service oriented pattern (or microservice if having multiple smaller APIs), possibly component-based structural pattern in the react client (or even MVC). Is this a hybrid, a Frankenstein or are patterns just out?

So my question is: Can someone explain, or point me towards, a concrete explanation of how these patterns apply to modern development stacks and frameworks?

I would greatly appreciate some clarification here.

it is possible to add repository or service interface/struct in this resolver struct?

I have project using gqlgen , and I am trying to migrate to using DDD pattern for this project, in my resolvers.go:

type Resolver struct{}

type mutationResolver struct{ *Resolver }
type queryResolver struct{ *Resolver }

func New() *Resolver{
    return &Resolver{}
}

func (r *mutationResolver) DeleteDocument(ctx context.Context, id string) (bool, error) {
           panic("not inplemented yet")
}

here for DeleteDocument was generated by gqlgen and in that DeleteDocument I do some logi and do data manipulation, I was using a function on another file like this:

/*
folder_document
  - delete_document.go
*/

func DeleteDoc(ctx context.Context, id string) (bool, error) {
     // some logic 
     // after pass logic delete document
     // return true if success
}

// and then on `resolvers.go` for function DeleteDocument
func (r *mutationResolver) DeleteDocument(ctx context.Context, id string) (bool, error) {
           success, err := folder_document.DeleteDoc(ctx, id)
           // return .....
}

you can see that I do logic and manipulation data in one function, and it might gonna have 10 - 100 lines or so, and it gonna hard for my team to read my code for it

so I am thinking about split it into struct like ddd pattern , example:

/*
folder_document
  - repository.go
  - service.go 
  - interfaces.go
*/

// interfaces.go 
type DocumentRepo interface {
   DeleteDoc(ctx context.Context, id string) (bool, error)
}

type DocumentService interface {
   DeleteNewDoc(ctx context.Context, id string) (bool, error)
}

// repository.go

type documentRepository {
  db *mongo.Client or *sql.db
}

func (useDB *documentRepository) DeleteDoc(ctx context.Context, id string) (bool, error) {
   // manipulation data
}

// service.go 

type documentService struct {
  docRepo DocumentRepo
}

func (userService *documentService) DeleteNewDoc(ctx context.Context, id string) (bool, error){
    _, _ = userService.docRepo.DeleteDoc(ctx, id)
}


it is possible to use that service in file resolvers.go ??

here is how I run the service on main.go:

func graphqlHandler() echo.HandlerFunc {
    config := resolver.Config{
        Resolvers: resolver.New(),
    }

    h := handler.NewDefaultServer(resolver.NewExecutableSchema(config))

    return func(c echo.Context) error {
        h.ServeHTTP(c.Response(), c.Request())
        return nil
    }

u can see that resolver.New() it got from resolvers.go

Realtime Model Datavalidation C# Server side Blazor. Exclude default/placeholder values from validation

Using server side Blazor I have several pages where i make use of the provided data validation tools in ASP to do realtime data validation. One example is as such:

<EditForm EditContext="PageEditContext">
  <DataAnnotationsValidator />
  <div class="form-row">
    <div class="form-group col-md-6">
      <label for="fooID">Foo ID</label>
        <InputNumber class="form-control" id="fooID" placeholder="fooID" @bind-Value=SelectedFoo.FooId />
        <ValidationMessage For="@(() => SelectedFoo.FooId)" />
    </div>
    <div class="form-group col-md-6">
      <label for="inputFooName">Foo Name</label>
        <InputText class="form-control" id="inputFooName" placeholder="Foo name" @bind-Value=SelectedFoo.FooName />
        <ValidationMessage For="@(() => SelectedFoo.FooName)" />
    </div>
  </div>
</EditForm>

The data-bound model, in this case, has the following properties along with validation attributes

[Required]        
[Range(1, int.MaxValue, ErrorMessage = "Only positive number allowed")]
public int FooId { get; set; }

[Required]        
[StringLength(20, MinimumLength = 5, ErrorMessage = "FooName should be between 5 and 20 characters")]
public string FooName { get; set; }

My reason for using EditContext instead of a direct Model definition is that I can implement realtime validation by calling the validate method when needed/on event raise.

To create a shared functionality I made a base class as such:

protected EditContext PageEditContext;

protected virtual void AttachEditContext<T>(T model)
{
  PageEditContext = new EditContext(model);
  PageEditContext.OnFieldChanged += EditContext_OnFieldChanged;
}

protected abstract void EditContext_OnFieldChanged(object sender, FieldChangedEventArgs e);

Then in my child I implement the EditContext_OnFieldChanged method to call the validation.

protected override void EditContext_OnFieldChanged(object sender, FieldChangedEventArgs e)
{            
  PageEditContext.Validate();
}

Which has the desired effect of doing the validation if a field is edited. And remains persistent, if I leave a field in an improper state and edit the next. It will keep displaying the error message.

However on the creation of a new object, in this case, a new Foo. My validation will fire after editing the first field.

private void CreateNewFoo()
{
  SelectedFoo = new Foo(0, null); //Foo(int FooID, string FooName)
  AttachEditContext(SelectedRole);
}

Which... I do not want, I do want validation on all fields if they have a value. But if they're on their default value and/or placeholder value in HTML. The validation should ideally be skipped (not succeeded, since my styling changes valid fields).

Now, this leads me to my actual question, how to achieve this? I feel like there should be a straight forward way, but the more research I've done, the less I'm convinced of this.

What I've thought of but run into problems with are:

  • Implementing a custom validation attribute. But I don't know how to short-circuit it (I do not want a valid/invalid state. It should simply be skipped if my value is 'default').
  • Using per field validation leads to problems with persistence where if FooName is considered invalid, and I start editing FooID, I lost my validation of FooName. (And I'm not sure how to work around this.)
  • Access the EditContext validations and deleting any 'false' invalids by checking if they have default values. But To my knowledge, this can't easily be done since the EditContext doesn't allow me to do so.

Other common 'solutions' that I know of (quoted because I don't see them fit the desired case).

  • Separate models for new objects. Where you loosen the validation and/or disable.
  • On submit validation only. Doesn't have realtime validation/feedback.

I'm now currently thinking in circles, and am wondering whether I should take a step back and take an entirely different approach. Unfortunately, I don't really have anybody to spar with about this level of problems. And I keep having the feeling I'm missing something more straight forward, or am simply going the wrong approach.

Any help or insights would be appreciated.

Understand the “Filter Pattern” with a real world example

I was studying the Filter Design Pattern as documented in tutorialPoints.

I am novice to Software Development and got my head banging while understanding the design patterns. Please, help me understand the Filter Pattern. Could someone give a use-case example of where this is useful in the real world?

How to implement retry pattern using c#?

I have a list of Proxy Servers. Using these Proxy Servers, I want to hit URL to get data programmatically. I want to apply retry pattern here. For example, If I cannot get data from Proxy Server 1, I would like to hit URL using Proxy Server 2 and so on. What should I write in ProxyHelper class GetData method as per good design practices.

Sample Code :

Interface IProxyServer {

    IResponse GetData(String URL);

}

public class ProxyServerA implements IProxyServer {

    public IResponse GetData(String URL)
    {
        //some code
    }

}

public class ProxyServerB implements IProxyServer {

    public IResponse GetData(String URL) {
        //some code
    }

}

public class ProxyHelper {

    public List<IProxyServer> _proxyservers = new List<IProxyServer>(); 
    
    public IResponse GetData(String URL)
    {
    
    // Following the best practices, what should be the code here which will implement retry mechanism
    // and call other available proxy server in case the request is failed.
    
    }
    
    public void Add(IProxyServer proxyserver)
    {
        _proxyservers.Add(proxyserver);
    }

}

void main() {

    ProxyHelper proxyHelper = new ProxyHelper();

    String URL = "www.google.com";
    
    proxyserver.Add(new ProxyServerA());
    
    proxyserver.Add(new ProxyServerB());

    var response = ProxyHelper.GetData(URL);

}

How to pause a thread for indefinite time until user resumes it manually

Let's say I have a class named Worker that has many methods and some of its methods have for and while loops. Something along these lines:

class Worker:
    def operation1(self):
        for i in range(5000):
            # performs some resource intensive operation 5000 times.

    def operation2(self):
        while some_condition:
            # another resource intensive operation in the while loop

I want to be able to pause the execution of an instance of the class at any given time and then be able to resume it. So this class should be running on one thread and GUI on another thread. The GUI will have two buttons: Pause and Resume that will pause and resume execution accordingly . How to make it happen? The only way I know how to pause execution of a thread is to use the sleep() method, but how to pause it until user resumes it?

Create a List of objects using Abstract Factory Pattern

I have a game with 2 types of characters, Hero and Monster. They will belong to one of the two following elements: Fire and Water. With the input choosing Fire or Water then choosing Hero or Monster creation. Output: Returns whether the object is created or not. I have developed it at the level of creating an object. I want to use List to create list of objects. What am I supposed to do with my code, because I really don't know where to put it

  • AbstractFactory
    public abstract class CharactersAbstractFactory
    {
        public abstract Hero CreateHero();
        public abstract Monster CreateMonster();
    }
  • ConcreteFactory
    class FireFactory: CharactersAbstractFactory
    {
        public override Hero CreateHero()
        {
            return new FireHero();
        }

        public override Monster CreateMonster()
        {
            return new FireMonster();
        }

  • AbstractProduct
 public abstract class Hero
    {
        protected int level = 1;
        protected int basicAttack = 50;
        public string Name;
        public Sect Sect;
        public Hero()
        {

        }
        public Hero(string name, Sect sect)
        {
            Name = name;
            Sect = sect;
        }
        public abstract void Create();

        public int Dame()
        {
            int dame = basicAttack * level;
            return dame;
        }
    }
    public enum Sect
    {
        ThieuLam,
        ThienVuong,
        NgaMy,
        YenMon
    }
  • Class Characters
    public class FireHero : Hero
    {
        public FireHero()
        {
        }

        public FireHero(string name, Sect sect) : base(name, sect)
        {
        }

        public override void Create()
        {
            Console.WriteLine("Create Hero with Fire Elements");
        }
    }
  • CharactersFactory
        public static CharactersAbstractFactory GetFactory(Elements elements)
        {
            switch (elements)
            {
                case Elements.Fire:
                    return new FireFactory();
                case Elements.Water:
                    return new WaterFactory();
                default:
                    Console.WriteLine("No elements");
                    return null;
            }
        }
  • Main
CharactersAbstractFactory factory = CharactersFactory.GetFactory(Elements.Fire);
Hero herofire = factory.CreateHero();
herofire.Create();
Monster monsterfire = factory.CreateMonster();
monsterfire.Create();

consuming rest api from springboot, architecture question

I want to write a REST API client with springBoot MVC. The client will send request to the API for data and will show them into the browser. For example, I'll have http://example.com/showItems mapped to itemsController.show method and rendered by an item.html (thymeleaf) template.

My question is where to put the API call and how to deal with the API response. I'm thinking about design, not just make it work. Let also imagine I want to extend to many API call returning different objects.

I'm thinking of several options:

  • a WebClient inside the controller. The controller deals with API calls that return an item Object.
  • the item class takes care of the API call. And maybe adapting the result for rendering. Different objects have different API calls. Maybe all have injected the same WebClient
  • I create an itemService that contains a "DAO", an itemDAO that calls the API and return item Objects. Similarly to DAO repository + models.

I'm not sure which solution to adopt. Is there another common way of doing this in spring, or some other design pattern? Or what could be the pros/cons of each solution?

mercredi 26 août 2020

Get wrong output in python Singleton design pattern

I was making a Singleton design pattern and everything goes fine.

Look at the code below:

class Singleton():
    def __new__(cls):
        if not hasattr(cls, 'instance'):
            cls.instance = super().__new__(cls)
        return cls.instance

s1 = Singleton()
s2 = Singleton()

print(s1 is s2)
# True

But this is not Singleton because user can use delattr(Singleton,'instance') between creating s1 and s2 and with this simple function s1 is s2 returns False

So I decided to change instance to __instance (to stop user using delattr(Singleton,'instance')) but when I do that I get False when printing s1 is s2 (My new code (__instance))

class Singleton():
    def __new__(cls):
        if not hasattr(cls, '__instance'):
            cls.__instance = super().__new__(cls)
        return cls.__instance

s1 = Singleton()
s2 = Singleton()

print(s1 is s2)
# False

But where is the problem? Why when I change instance to __instance the result I get is False?

(I know other methods of creating Singleton I Just want to know what is different in instance and __instance when I'm in the class and __instance is not private for myself)

Java - Avoid pattern duplication

Java In my server code, for each method I will have to do the following

    @Path("...")
    public Response function(...) {
        try {
            result = do some work to get result
            log the result
            return result
        } catch (Exception e) {
            log error
            return error
        }
    }

I will have to duplicate this pattern everywhere and only changing the do some work to get result part for new endpoint.

Is there a way that I can do to reduce this is duplication?

P.S. do some work to get result can be very something like getting a Json file, or accessing multiple database and calculate the result, and need to be in try-catch block.

Prototype Design Pattern Questions And Code Review - C++

I have just started reading the GO4 book to learn the OOD concepts. In order to practice the Prototype pattern, I implemented a small example (the idea for colored shapes was taken from "refactoring.guru"). Following is my code with some questions beneath.

Prototype definition:

enum class Shape
{
    Circle,
    Rectangle,
};

class ColoredShapePrototype
{
protected:
    std::string color_;
public:
    ColoredShapePrototype() {}
    ColoredShapePrototype(std::string color) : color_(color) {}
    virtual ~ColoredShapePrototype() {}
    virtual ColoredShapePrototype* Clone() const = 0;
    virtual void ShapeDetails() { std::cout << "Color: " << color_ << "\n"; } 
    virtual void UpdateColor(int color) { color_ = color; }
};

class ColoredCirclePrototype : public ColoredShapePrototype
{
private:
    int radius_;
public:
    ColoredCirclePrototype(std::string color, int raduis) : ColoredShapePrototype(color), radius_(raduis) {}
    ColoredShapePrototype* Clone() const override { return new ColoredCirclePrototype(*this); }
    void ShapeDetails() { ColoredShapePrototype::ShapeDetails(); std::cout << "Radius: " << radius_ << "\n"; }
};

class ColoredRectanglePrototype : public ColoredShapePrototype
{
private:
    int height_;
    int width_;
public:
    ColoredRectanglePrototype(std::string color, int height, int width) : ColoredShapePrototype(color), height_(height), width_(width) {}
    ColoredShapePrototype* Clone() const override { return new ColoredRectanglePrototype(*this); }
    void ShapeDetails() { ColoredShapePrototype::ShapeDetails(); std::cout << "Height: " << height_ << "\nWidth:" << width_ << "\n"; }
};

class ShapesPrototypeFactory
{
private:
    std::unordered_map<Shape, ColoredShapePrototype*> prototypes_;
public:
    ShapesPrototypeFactory() {
        prototypes_[Shape::Circle] = new ColoredCirclePrototype("White", 5);
        prototypes_[Shape::Rectangle] = new ColoredRectanglePrototype("White", 2, 3);
    }
    ~ShapesPrototypeFactory() {
        delete prototypes_[Shape::Circle];
        delete prototypes_[Shape::Rectangle];
    }
    ColoredShapePrototype* CreatePrototype(Shape shape) { return prototypes_[shape]->Clone(); }
};

Usage in main:

ShapesPrototypeFactory prototype_factory;
ColoredShapePrototype* circ = prototype_factory.CreatePrototype(Shape::Circle);
circ->ShapeDetails();
ColoredShapePrototype* rect = prototype_factory.CreatePrototype(Shape::Rectangle);
rect->ShapeDetails();
delete circ;
delete rect;

Questions:

  1. Interfaces in general - pure virtual functions and other variables are declared, and derived classes should implement those. Suppose I want to add a specific capability (with unique data member and member function) to the derived - Does it contradict the interface idea? (Because, if I have a pointer from base to derived, this pointer will not recognize the specific method...). If it is OK, Is there a way to execute a derived function through the interface(who doesnt have this function..)?

  2. while debugging and watching circ variable, I can see the variable in the memory window, and I see "white" color, but I cant find the radius there. Is there a way i can see specific data member address in the memory? (I have tried circ->radius_ etc. none was working..)

  3. I have seen that most implementations are using "unique_ptr". I know its basic usage, but how critical it is? and why not use it all the times rather than a regular pointer actually? and where are the places I should use it in the prototype pattern?

  4. Implementing Copy Constructor in case of non-stack variables (shallow/deep copying) for the clone operation - Is a CCtor in the base class is sufficient or the derived is required as well?

  5. Code review - better syntax/design/ideas/improvements?

Thanks in advance, I will highly appreciate your help!

What Design Principle is Violated, and Which Design Pattern can Fix It

In one recent exam, I was asked 2 questions regarding the code snippet below... The questions are as follows

  1. Identify the design principle violated by the code snippet

  2. Describe the design pattern that solves the design principle violated.

  3. Provide the UML class diagram of the design pattern described in (2) above (Optional)

  public class AI{
     public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        String choice = input.nextLine();
        
        if(choice.equals("some text"){
           // do something
        }
        else if(choice.equals("another text"){
           // do something
        }
        else if(choice.equals("extra text"){
           // do something
        }
        ...
        else{
           // do default
        }

     }
  }

Convert JSON file into proper format using python pandas

I want to convert JSON file into proper format. I have a JSON file as given below:

{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red",
    "details":"|seedless:true|,|condition:New|"

},
{
    "fruit": "Almond",
    "size": "small",
    "color": "brown",
    "details":"|Type:dry|,|seedless:true|,|condition:New|"

}

You can see the data in the details can vary.

I want to change it into :

{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red",
    "seedless":"true",
    "condition":"New",

},
{
    "fruit": "Almond",
    "size": "small",
    "color": "brown",
    "Type":"dry",
    "seedless":"true",
    "condition":"New",

}

I have tried doing it in python using pandas as:

import json
import pandas as pd
import re
df = pd.read_json("data.json",lines=True)

#I tried to change the pattern of data in details column as

re1 = re.compile('r/|(.?):(.?)|/')
re2 = re.compile('r\"(.*?)\":\"(.*?)\"')

df.replace({'details' :re1}, {'details' : re2},inplace = True, regex = True);

But that giving output as "objects" in all the rows of details column.

How to go about structuring Javascript code? [closed]

My question: What architecture is good for structuring the frontend (mainly javascript wise)? is MVC usually the go to?

Is this an anti pattern?

Currently I am confronted often with code that follows the pattern demonstrated by the code bellow. It is kind of a strategy pattern.

I am not fine with this, it feels somehow smelly. It breaks the actual strategy pattern and the additional indirection is confusing. Also it leads often to methods called similiar like in the example, because the purpose of the method in the derived class is very similar to the in the base class. On the other side I am not able to point with the finger to the problem core.

Am I the onlyone who finds this fishy? And if not, what problems can this code cause, esepecially with regard to SOLID principles?

namespace MyTest
{
    abstract class Base
    {
        public void DoSomething()
        {
            var param = Prepare();
            DoItReally(param);
        }

        private string Prepare()
        {
            return "Hallo Welt";
        }

        protected abstract void DoItReally(string param);
    }

    class DerivedOne : Base
    {
        protected override void DoItReally(string param)
        {
            Console.WriteLine(param);
        }
    }

    class DerivedTwo : Base
    {
        protected override void DoItReally(string param)
        {
            Console.WriteLine(param.ToUpper());
        }
    }
    
    static class Program
    {
        public static void Main(string[] args)
        {
            Base strategy = new DerivedOne();
            strategy.DoSomething();
            
            strategy = new DerivedTwo();
            strategy.DoSomething();
        }
    }
}

Replace switch case: interface vs abstract class

I have a code that has a switch statement and want to improve the design.

There's the interface and the the abstract class way.

I want to know which way is better and why ?

I have the following class :

enum MovieChargeType {regular, new_release }

class Movie {
    public MovieChargeType type;
    public double get_price(){
          switch (type){
                  case regular: //return regular price
                  case new_release : // return new_release price }
    } 

}

So I decided to improve the design using 2 ways:

1 Way - Interfaces

Interface MovieType{
    public double get_price();
}

class RegularMovie implements MovieType{
    public double get_price(){
        // return regular price
    }
}

class NewMovie implements MovieType{
    public double get_price(){
        // return new price
    }
}

class Movie{
        public MovieType type;
        public double get_price(){
              type.get_price();
        } 
    
    }

2 Way - abstract classes:

abstract class Movie {
        public MovieChargeType type;
        public abstract double get_price();
    
    }

class RegularMovie extends Movie{
        public double get_price(){
            // return regular price
        }
    }
    
    class NewMovie extends Movie{
        public double get_price(){
            // return new price
        }
    }

I want to know which one is better in such case? I've noticed that people tend to go with interfaces but can someone explain why?

Should I Put Code Block That Contains IO/Network Operations in Thread in my lib(jar)?

I have a library which consists background operations such as file IO, network, db query etc.

  • Should i put background operations inside thread block?

    OR

  • it is implementation details so A method which implements the operations acts this task.

As a developer I wonder that which one is correct way?

mardi 25 août 2020

C++ Finite difference differentiation - design

for the sake of simplicity consider the function:

double foo(const std::vector<double> &a, const std::vector<double> &b, ...) {
 /* do complex stuff */
 return ...;
}

(In reality the types of a and b are more complex objects).

we want to differentiate foo() with respect to its arguments. Therefore the first order sensitivity d foo/d a is a std::vector<double> with size equal to a.size(). Same reasoning goes for d foo/d b.

A naive implementation would go as follows:

std::vector<double> a = {1, 2, 3, 4, 5};
std::vector<double> b = {1, 2, 3};

// compute d foo/d a 
std::vector<double> computeDfDa(std::vector<double> a, std::vector<double> b, ..., double da = 1.0){
  std::vector<double> dfda = {};
  for (auto i = 0; i < a.size(); ++i) {

      // bump up
      a[i] += da;
      auto up = foo(a, b);
      a[i] -= da;

      // bump down
      a[i] -= da;
      auto down = foo(a, b);
      a[i] += da;

      auto derivative = (up - down) / 2.0 / da;
      dfda.pushback(derivative);
  }
   return dfda;
}

// compute d foo/d b 
std::vector<double> computeDfDb(std::vector<double> a, std::vector<double> b, ..., double db = 1.0){
  std::vector<double> dfdb = {};
  for (auto i = 0; i < b.size(); ++i) {
      // bump up
      b[i] += db;
      auto up = foo(a, b);
      b[i] -= db;

      // bump down
      b[i] -= db;
      auto down = foo(a, b);
      b[i] += db;

      auto derivative = (up - down) / 2.0 / db;
      dfdb.pushback(derivative);
  }
  return dfdb;
}

This works well however we have basically the same code for computeDfDa() and for computeDfDb().

Is there any design pattern that would allow to have a unique (maybe templated) function that would understand automatically which input to bump?

If the complexity and the number of inputs of foo() are much greater the naive solution would generate a lot of useless code as we'd have to write a computeDfDx() function for every input x of foo().

Android Where to start Activity in MVVM Resarlt

I supposed to use MVVM pattern with Data Repository. Data Came from Web Api call. and based on The Data, The Application Start The Web Browser With Returned URL.

  1. on user interaction The Activity calls ViewModel Which owns Data:

CheckOutActivity.java:

MaterialRippleLayout makeOrder = findViewById(R.id.btn_make_order);
    makeOrder.setOnClickListener(view ->{
        viewModel.makeOrder();
    });
  1. viewModel calls DataRepository with Appropriate Data (optionalShippingEntityIds) to call Web Api Async:

CheckOutViewModel.java

public void makeOrder(){
    cartRepository.makeOrder(optionalShippingEntityIds.getValue());
}

The Repository has been instantiated before:

public CheckOutViewModel(@NonNull Application application) {
    super(application);
    cartRepository = new CartRepository(application);
}  
  1. in DataRepository Api Call performs:

CartRepository

public void makeOrder(ArrayList<Integer> optionalShippingEntityIds){
    HashMap<String,String> map = new HashMap<String,String>();
    String  idsString=optionalShippingEntityIds.toString();
    map.put("shipment_saleitem_id",idsString);
    rest.httpRequest(RestAdapter.HttpVerb.POST,"order",map,new makeOrderHandler());
}

The CartRepository Constructor:

private RestAdapter rest;
private Context context;

public CartRepository(Context context) {
    this.context = context;
    rest = RestAdapter.getInstance(context);
    version.setValue(0);
}

4.HttpResponseHandler Handle The Web Browser open URL or Toast fail message

CartRepository.java

class makeOrderHandler extends JsonHttpResponseHandler{
    @Override
    public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
        if(statusCode == 200){
            try {
                Toast.makeText(context,"order number "+response.getInt("order_id")+"has been created",Toast.LENGTH_SHORT).show();
                String redirectUrl = response.getString("init_payment_url");
                version.setValue(version.getValue() +1);

                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(redirectUrl));
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        context.startActivity(intent);
                        ((Activity)context).finishAffinity();
                        //System.exit(0);

                        /*Intent chooserIntent = Intent.createChooser(intent, "Open With");
                        chooserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(chooserIntent);*/
                    }
                }, 2000);
            } catch (JSONException e) {
                Toast.makeText(context,"JSON parse error"+" : "+response.toString(), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
        }else{
            Log.e("server api changed ", "error in getting response using known api \n" + response.toString());
            Toast.makeText(context,"api change",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
        // called when response HTTP status is "4XX" (eg. 401, 403, 404)
        Log.e("server 500", "error in getting response using async-apache-http call"+" : "+res);
        t.printStackTrace();
        Toast.makeText(context, "خطا سرور ", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, Throwable t, JSONObject e) {
        if(statusCode == 504){
            Toast.makeText(context,"The Order hasnt been created duo to internal problem. please try again",Toast.LENGTH_SHORT).show();
        }else{
            Log.e("server api changed", "error in getting response using known api \n" + e.toString());
            t.printStackTrace();
            Toast.makeText(context,"Api is unknown",Toast.LENGTH_SHORT).show();
        }
    }
}

The Problem is after i launch The Application in some Devices, in The Line ((Activity)context).finishAffinity(); The Application Crashes because The context is an application context instance and not an activity context instance .

  • if i pass The Activity instance Through ViewModel, i had just violated The MVVM.
  • if i make an interface in The Activity and implement it. it violates The Activity Single Responsibility (Data Repository Response Handler Should Handle The startActivity)
    so i dont know how to handle this perfectly.
  • if i eliminate The ViewModel makeOrder, and Construct The Repository With The Activity Context I think its ViewModel Responsibility to Handle The Data Manipulation Job.

....

So I am Confused With The Right Solution To Handling StartActivity and Toast in Response.

if anyone could help me With The Right Design Pattern i Would Appreciate.

Which architecture designs for the front-end / Javascript? [closed]

My question: I'm a student building a simple website. I have done MVC architecture with Java and Spring Boot backend, My front-end is (HTML/CSS/Javascript). What architecture is good for structuring the frontend (mainly javascript wise)?

Because I have read that MVC suits backend but is too outdated for the front-end, and front-end should use unidirectional architecture like FLUX or REDUX (which I haven't really looked much into because I don't want to dig in to frameworks and libraries like React and Angular). I apologise in advance if I'm speaking gibberish or if my question actually makes sense.

Can Visitor Design Pattern and Observer Design Pattern be combined?

Let me say I have a simple Java program, which reads some files and displays some data.

I am confused, I think a pattern should be applied but I can't decide which one to implement.

Here is the scenario:

Whenever I choose a directory I want my program to display the directory name, all the files list and other data (like file sizes, file extensions etc.) Whenever I click a filename I want my program to display its' path, preview it if it is an image file and some other stuff.

The program would keep keep the data in a dataHolder class: File selectedDirectory, List filesInthatDirectory, File selectedFile, JSONObject fileData etc...

That program would have many GUI objects for display; textfields, panels, labels, lists.

Classic old approach would be writing all the code in a single method *press a button -> inside the actionListener *get files from the disk, *read their names and other stuff, *fill the GUI objects with data. This is kinda bad.

So I decided to use a design pattern. Then whenever I click this button and read from the disk, I would only update the dataHolder class (setSelectedDirectory, setFileData, fillCurrentFilesList.. methods like these) And these update operations would trigger classes which will do the needed GUI updates.

But I stayed between two approaches;

-With Observer pattern, I create some observers, for example when dataHolder's fileData (JSON) object is updated I would notify related textFields, then they will display the proper data.

-But with Visitor pattern, a visitor class will handle different objects, it would run different codes for different GUI classes. JList will try to display a List or some textFields will try to parse a JSONObject and display only the related String. But I do not need much different functions, I mean I only want the GUI objects to display some data, my only visitor class would be a DisplayVisitor which will expect the GUI display object's only job - display the data. If I needed doSomethingVisitor, doAnotherThingVisitor, doAmazingThingVisitor... classes that approach would be nice but I don't need another functions.

Do both approaches do the trick? I just can't get the difference for this scenario. Both of them offer a solution, Observer is more simple but does it offer handling different GUI classes like filling a JList with Arraylist or making a JLabel displaying an jpeg File?

Or Can I combine these patterns? Thanks for reading.

Which design pattern to use here?

I am building an app that consists of many applets. Applets can nest, but they have to instantiate in the context of their parent. Functionality is largely the same across contexts, but it needs to vary in key ways. Also--importantly--when an applet instantiates, it needs access to data that will vary based on both its class and its parent (which is itself an instance of another applet). This data cannot be computed at runtime and must be stored somewhere.

What design pattern should I use here, and will I be able to scale it to many different applets?

I realize this is kind of abstract, but if I try to explain specifics I think I will get sucked into the weeds.

When to use new Screens in Flutter instead of TabBarView

I am fairly new to Flutter and I try to understand when and why it would be necessary to navigate to a new screen. Most apps keep the same AppBar, Drawer & BottomNavigationBar (if any) through all the different "screens". Wouldn't it be easier to just have one single TabBarView, or only replace the Scaffold's body ?

I have a hard time to really understand the concept of why there needs to be a new Scaffold when routing. I couldn't find anything helpful in the official Flutter doc, even the Cookbook show you a Navigation example with 2 completely new screens just to show a different Text widget inside the Scaffold's body.

Also, what about the efficiency of always rebuilding the whole Scaffold ?

load config file for game, singleton or passing down the tree or anything else?

I'm trying to create simple game in C++. At one point I want to have some setting, save and load from config file. The config file should be read from the beginning, and should be accessible anywhere it needed.

  • So far I only see Singleton pattern as a solution.
  • Another way is to create an object an pass it down, but it can mess up the current code.
  • I've also search and found something called Dependency Injection.
  1. Is dependency injection useful in C++
  2. Which design patterns can be applied to the configuration settings problem?

But I don't quite understand it, you still have to create an object in main and pass it down, right? Singleton is quite simple, but some consider it antipattern, while pass it down the tree can mess up my current code. Is there any other Patterns?
I'm also curious how games load their setting.

Append data into time series flow

i have big flow of a events from many devices. I need to inserts start and end points: events flow figure. Every event, excluded start/end, contains some calculated params that also need to provided in start/end points. But devices can send start and end points only without calculated params, but i need it. I can take that params value from first event for start point and from last for end point, but the main problem that place where all events are sends is a gateway and it does`t store any information about previous events. Gateway sends events into three different store, and start/end should be inserted on a gateway layer.

Probably i need some midlleware storage, that would be accumulate events and than i can extract data for start/end points, but i think that is a bad solution.

Could you offer more better solution for that situation?

Elegant design pattern for multiple state machines working in concert? [closed]

I'm trying to think of an elegant way to model three state machines that work in concert with one another. For example, say we have these three machines like:

Machine One

A ---> B -.
^          |
|          v
D <------ C

Machine Two,

E <--> F

and Machine Three,

H --> I <--> J

and we we want to write code where Machine One can only transition to state B if Machine Two is in state E and Machine Three is in state I or J. There could be many other rules like that.

Being new to C++, I'm wondering what could be most elegant way to model this kind of behavior of multiple state machines working in concert.

Scalable elasticsearch module with spring data elasticsearch possible?

I am working on designing a scalable service(springboot) using which data will be indexed to elastic search.

Use case:

My application uses 6 databases(mySql) having same schema. Each database caters to specific region.
I have a micro service that connects to all these dbs and indexes data from specific tables to elasicsearch server(v6.8.8) in similar fashion having 6 elasticsearch indexes one for each db.
Quartz jobs are employed for this purpose and RestHighLevelClient. Also there are delta jobs running each second to look for changes using audit and indexes.

Current problem:

  1. Current design is not scalable - one service doing all the work(data loading, mapping, upsert in bulk). Because indexing is done through quarts jobs, scaling services(running multiple instances) will run the same job multiple times.
  2. No failover - Looking for a distributed elasticsearch nodes and indexing data to both nodes. How to do this efficiently.

I am considering spring data elasticsearch to index data sametime when it is going to be persisted to db.

Does it offer all features ? I use :

  • Elasticsearch right from installing template to creating/deleting indexes, aliases.
  • Blue/green deployment - index to non-active nodes and change the aliases.
  • bulk upsert, querying, aggregations..etc

Any other solutions are welcome. Thanks for your time.

Delegation Principle with Solid ISP

I'm trying to apply solid principles for upload and download docs usecase.

Here are the objects.

Question: I want to zip the file and save.

  1. I can create another interface for filesaving, but how should I pass the Document reference to filesaving interface from download method, any design pattern to be followed?

  2. I can use composition of FileSave interface and add the savetoZip() method in download(), but that violates single responsibility of download() method because it has nothing to do with transforming to zip.

  public class DocumentServiceImpl implements IDocumentService<Document> {

    private RestTemplate restTemplate;

    @Override
    public Document download() {
        return restTemplate.downloadDocument();
    }

    @Override
    public Document upload() {
        return restTemplate.uploadDocument;
    }
   }

    //ISP Principle
   public interface IDocumentService<T> extends IDocumentDownload<T>, IDocumentUpload<T>, 
     IDocumentProperty<T> {
   }

   public interface IDocumentDownload<T> {
      T download();
   }

StringBuffer follow which design pattern in java [closed]

I have tried to find the answer on google. But didn't find anything and still i have this doubt. If anyone know then please share experience here with some details.

python design pattern for hierarchical oop

i created following hierarcy for my project.

Abstract Car class which has common methods and common fields for all cars. Then i inherited model classes like BMW,Audi,Mercedes,Pegout,Ford and etc. which has only its own fields and methods.

class hierarchy for my project

lets assume i have similar hierarchy with classes for some other topics and i packaged each topic like :

\project folder  
    \Cars  
        BMW.py  
        Audi.py  
        ...
    \topic2  
        ...
    \topic3  
        ...
    \...  
    \my_project.py

in my_project.py i want to add all concrete classes and use them.But my problem is here that there are too many classes and i dont know how should i keep them.
Should i keep them as objects(composition) in a container such as list like myObjects = [Audi(),BMW(),...]
or should i go multiple inheritance to keep all classes in one like class Vehicle(BMW,Audi,...) (for that case i also dont know how to handle with common methods. i mean what happens if i call a common method from Car class ?)
or is there any better solution?

lundi 24 août 2020

Can someone please explain a GRASP Design pattern used in this code? [closed]

https://github.com/nidharaisa/DotsAndBoxes/tree/master/src/dotsandboxestry

I am having trouble understanding.

Understand the “Observer Pattern” with a real world example

I was studying the Observer Pattern as documented in wikipedia.

I am new to Software Development and got my head banging while understanding the design patterns. Please, help me understand the Observer Pattern. Could someone give a use-case example of where this is useful in the real world?

How to Compose two objects at runtime in C# only if the first object implements interfaces required by the second?

Say I have two classes. I want to compose class A into class B.

However, for this to be valid, class B must implement a specific set of interfaces required by class A.

How could I associate class A with the list of interfaces it requires class B to implement?

I want to do this so that at run time, some type of controller can decide whether or not to add one object to the other. It will only add a to b if b implements all of the interfaces required by a.

I hope this makes sense! Thanks!

What Is The Flow For Enabling Single-Sign-On With Other Organisations?

I have a React front end with a Spring Boot back end deployed on Azure.

Our company uses Active Directory as does our clients.

Our clients have said that they would like to use single-sign-on with our applications.

i.e. they click log in on our application and it takes them to their company login page

I don't have a good handle on how this flow would work and which parts are the responsibility of which parts of the application.

I'm not sure if it is something like this where it is handled mostly within the application:

  • user clicks log in
  • web app links to MS auth
  • MS auth redirects to correct client company login
  • client company AD authenticates and responds with JWT
  • web app forwards the jwt to us via a REST API call
  • back end connects to our AD and verifies (?) that it is a valid company
  • back end responds to the REST request with another JWT containing the user, company, role etc

Or if it is some configuration within AD that skips those last 3 steps.

I'm also not really sure what to store in our Active Directory.

  • Do I create a user that represents each client company?
  • Or a group of users that relate to that web app?
  • Should I store the roles for each user in our AD or should that come from their AD?
  • If the role is in their AD, do I tell the client what the role names should be or is there a way of doing some mapping between their roles and ours?

Is there a proper name for this design pattern to help me with searching for examples?

Design patterns for shape construction

I'm new to the design patterns and I need help to decide which patterns to use on my app.

The task is to write a simple console version of a drawing program, so if you insert:

C - Should create a new canvas of width w and height h

L - Should create a new line R - Should create a new rectangle Q - Should quit the program

So I have thought about using two design patterns. Abstract Factory for the commands and Decorator for the shapes. Is this the correct approach? or do you guys recommend using something else?

RXJS and typescript: Conditionally executing work with Server and Client Code



My requirement is to provide a function that uses various conditions to determine whether an object can be edited.
These conditions can be on both the server and the client side.
Some of these conditions should abort the execution of further validation and return the value.

i will try to make the process understandable with pseudo code.
Perhaps there is already a pattern for implementing such tasks.

isEditable(): Observable<boolean> {
  return serverSideCondition.pipe(
    switchMap(editable => {
      if (editable)
      {
        return clientSideCondition;
      }

      return of(false); // Should abort furhter conditions ...
    }),
    switchMap(editable => {
      if (editable)
      {
        return clientSideAskTheUser;
      }

      return of(false); // Should abort furhter conditions ...
    })
  );
}

Thanks

How to print a graph like pattern( ZIG ZAG ) in JAVA with respect to the given integers

I have attached the pic of sample input and output......If you see sample i/o you will get a clear picture

Sample i/o

Else see below....

Input: 3 2 4 3 2 5

Output:

        /\
       /  \  /\
  /\  /    \/  \
 /  \/          \
/                \
                  \

I need full code please...Thanks

Convert object from one class to another in java [closed]

I have 2 custom classes A and B. Now I have an object of A let say 'a' and have to convert it to B class.

Now I have 2 approach

  • First is I write a transform Util which has a static method for conversion.
  • The second approach is to write that logic in class A with a method convertToB()

Which one is more accurate. Please suggest.

Simplest way to switch context back and forth (dispatching)

I have two classes that perform independent computation. For the sake of simplicity here, I will represent them with functionscalc1 and calc2. At some random places in each function, I need to sleep for a while. Rather than doing calc1 and then calc2, I'd like to switch back and forth between them.

I could use threads, but it seems to me at first sight overly engineered to do so. I do not need different threads. I just need to switch from one context to another, and back where we were.

func calc1() {
...
sleep(300) // go to calc2
...
}

func calc2() {
...
sleep(200) // resume calc1
...
}

Is there a simple way to do this?

dimanche 23 août 2020

One big fat DTO vs multiple skinny DTO

I'm always struggling with naming convention and design pattern for my application, it's been very hard to keep it consistent, so I have a simple case, let's say I have a service with method called CreateOrder

public OrderDTO CreateOrder(int customerID, OrderShipDTO shipping, OrderDetailDTO products);

Here's the DTO class

    public class OrderDTO
    {
        public int ID { get; set; }
        public decimal PriceTotal { get; set; }
        public string Status { get; set; }
        public string PaymentMethod { get; set; }

        public OrderShipDTO OrderShip { get; set; }
        public ICollection<OrderDetailDTO> OrderDetails { get; set; }
    }
    public class OrderShipDTO
    {
        public string Name { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }
        public string Province { get; set; }
        public string City { get; set; }
        public string District { get; set; }
        public string SubDistrict { get; set; }
        public string ZipCode { get; set; }
    }

    public class OrderDetailDTO
    {
        public int ID { get; set; }
        public decimal Quantity { get; set; }
        public decimal Price { get; set; }
        public int ProductID { get; set; }
    }

As you can see, my method CreateOrder will return OrderDTO and accept OrderDetailDTO parameters, but the method actually only requires property OrderDetailDTO.ProductID and OrderDetailDTO.Quantity for the business logic calculation.

So, it feels not right for me (and confusing because I wasn't sure which properties need to have a value and which doesn't) to pass the entire OrderDetailDTO object even though it only needs 2 of the properties to be filled, but I still need to pass back the OrderDTO which will include ICollection<OrderDetailDTO> because I need to get the OrderDetailDTO.Price value and show it to my customer.

So I was thinking of creating another DTO like this

    public class OrderDetailDTO_2 //temp name
    {
        public decimal Quantity { get; set; }
        public int ProductID { get; set; }
    }

But I will end up with a lot of DTOs and even though I'm fine with it, what's the best practice for the DTO naming?