mardi 30 avril 2019

How do I prevent adding an object in multiple vectors?

There are some objects that are Drawable and some that are Movable.
All drawable objects are movable.
I store all the drawable objects in a vector called drawables and movable objects in a vector called movables.
I also have vectors ships and bullets which contain objects of type Ship and Bullet respectively. Ship and Bullet both are Movable

The thing is, that each time I create a Ship I have to add it in all the vectors i.e.

drawables.push_back(ship);
movables.push_back(ship);
ships.push_back(ship);

I have created seperate drawables and movables vectors since I have a draw() function which calls the draw() method of all objects in the drawables vector. Similarly, I have a move() function which calls the move() method of all objects in the movables vector.

My question is, how do I change the structure to prevent adding the same thing in different vectors. I also need to remove objects from all the vectors once it's purpose is done.
For example, once the bullet hits someone or moves out of the screen, then I'll have to remove it from the vectors drawables, movables and bullets after searching it in all three vectors.
It seems like I'm not using the correct approach for storing these objects. Please suggest an alternative.

This seems more like a software engineering question than a coding question. Please migrate the question to other forum if necessary.

Thank you.

how do i create a dict of class objects, persist them on disk and access them later?

Basically i'm trying to design an Command-line ATM with User as my class. Later i want to load this objects from disk and perform following operations on it.

  • signup
  • authentication
  • pay
  • rewards
  • balance check
  • pin change
  • last n statement print
  • report a complaint

now my main concern is how this can be done dynamically, in-memory and store the final result in disk as pickle or something

Should I use inheritance if i want to reduce boiler plate codes in this scenario?

I have a Pojo class that is corresponding to a table in the database. The class Report.java has several fields:

class Report {
   public Date createDate;
   public String creator;
   public String description;
   public String id;
}

From the first requirement, I need to return the Report object using the id to search for it in the database. The response should only contains those 4 fields. But now they want to have another REST endpoint such that with the id, I need to return extra information in the response such as Date validUntil; I am thinking to use inheritance for this such as:

class ExtendedReport extends Report {
  public Date validUntil;
}

I am not sure is this the best way to reduce boiler plate or I should do another way ?

Thank you.

How to show selective UI features?

I have a UI that needs to either show icons on a timeline view or not based on user profile. How can I show for some users and not for others? For example : the Sports Admin team needs to see the scores of all teams over time in the view (showing all years visually) but the players (when they login to the same web app) only see the timeline view with their team's performance over the years (not other details for a particular year). How can I achieve this? I am using Angular JS and javascript

I have looked into role based SSO login and show selectively and also cookies. My goal is faster performance - meaning the page needs to load fast.

How to avoid ping pong method call in MVP?

In my Android app, I have a Fragment in MVP pattern. Lets assume we have:

  • CalculationFragment (the view)
  • CalculationPresenter (the presenter)
  • CalculationNetwork (the model)

I need a multi-step calculation or REST call:

  1. In CalculationFragment's onViewCreated() I call val sessionId = presenter.firstCall() as String to retrieve a sessionToken for further process.
  2. Then the presenter retrieves the sessionToken via REST. So far so cool. Then I need the next call in chain, what consumes the retrieved sessionToken and a NfcAdapter.getDefaultAdapter(activity).

val jsonObject = secondCall(sessionId, nfcAdapter) .

Since I am in the presenter, I do neither have the activity nor the NfcAdapter here (and I honestly do not want to). I have two options here:

  1. In my presenter I go back to my Fragment with the sessionToken view?.onFirstCallResult(sessionToken) and call from the CalculationFragment's onFirstCallResult() immediately presenter.secondCall(sessionToken, NfcAdapter.getDefaultAdapter(activity)).
  2. I hand over the activity/NfcAdapter for the second call in the first call already and store it in the presenter. I would not need to pingpong between view and presenter a lot. Furtheron, I could remain in the presenter for all my calls?

What would be an elegant solution / pattern here?

lundi 29 avril 2019

How to adapt the Chain of Responsibility pattern to pass state

I'm looking for a design that satisfies the following requirements:
1. There is a single, publicly-visible object that has the following interface:

class Whatever
{
    Whatever& GetIntstance();

    void UpdateData1(POD d1); // POD: Plain old datatype
    void UpdateData2(POD d2);
    // ...
    void UpdateDataN(POD dN);

    bool Question1();
    bool Question2();
    // ...
    bool QuestionM();
}

Where void UpdateDataX(POD dX) (1 <= X <= N) sets some internal state. Where bool QuestionY() (1 <= Y <= M) asks a yes/no question and is computed from internal state.
2. The Whatever instance may not know how to answer all Questions. In the case that it does not know how to answer a question, it needs to delegate the responsibility.
3. Different questions may have different delegates.
4. A delegate may have a delegate.
5. When delegating a question, an object needs to let a delegate have read-access to its state and the state of anything that delegated to it.
6. A delegate may take a long time to answer a question (don't ask why), so its answer may be cached. This means that the delegate needs to be notified if state, on which it is dependent, changes. This also means that delegates need to be notified on a call to UpdateDataX.

Assume that the tree structure (DAG structure, or whatever structure) of delegates is fixed after it is constructed.

React TypeScript - State should never be exported?

I have a React App that gets asynchronously its info with the method getInitialInfo. The MessageView is the uppermost component, so, the Data should live in its state, even if it will not change. In a perfect world, the IMessageInfo would be passed through props.

We need to export the type IMessageInfo because there is code that depends on this interface.


OPTION 1 - (Flat solution with no private State)

import * as React from 'react';
import Message from './Message';

// IMessageInfo needs to be exported because there is code that depends on it
export interface IMessageInfo {
    message: string;
    icon: string;
}

export interface IMessageViewProps {
    getInitialInfo(): Promise<IMessageInfo>;
}

// MessagesView is the upper most Component 
class MessageView extends React.Component<IMessageViewProps, IMessageInfo> {
    constructor(props) {
        super(props);
        this.state = {
            message: '',
            icon: ''
        };
        this.getInitialInfo();
    }

    private async getInitialInfo(): void{
        let info = await this.props.getInitialInfo();
        this.setState(info);
    }

    render(): JSX.Element {
        // Message is reusable component that receives the info through `props`
        return <Message {...this.state} />);
    }
}

From the React's design perspective the State must be private to the component. I agree with that. But here, all the state info is Public. what can throw this concept way. (If the DATA is always managed in a presenter for example, why should it be private in this case?)


OPTION 2 - (Flat solution, having a private replicated interface for State)

Talking with some colleagues, they argue that we should always keep the state private. I immediately thought about creating a IMessageViewState that would be exactly the same as IMessageInfo. This way, it gets conceptually right but we would get a maintenance issue (IMessageInfo and IMessageViewState to update whenever some of its members change).


OPTION 3 - (Compose IMessageInfo into IMessageViewState. Has a private state)

So, my colleagues suggested to define IMessageViewState as:

interface IMessageViewState {
    messageInfo: IMessageInfo;
}

This way we are favoring composition (they say). But I don't see any advantage to have composition here. Do you see any? For example, if any member of the IMessageInfo changes (message or icon), we would need to pass all the object messageInfo to the this.setState(...), instead of only updating the icon for example. Basically, it would be a more error-prone implementation.


OPTION 4 - (Extend IMessageInfo. Has a private state)

I also thought about having IMessageViewState extending IMessageInfo. It seems the best solution to accomplish a state that is not exported. But my colleagues said that it's not a good solution because we are giving priority inheritance over composition.

I think that inheritance doesn't bring any throwback in here.


CONCLUSION

In my opinion, the Option 1 is the one that best fits the problem. Since all members of the State are public, I think there's no need to have a private State. The Option 1 keeps the code cleaner.

Although, if I were to choose a solution with a private State, the Option 4 would fit better.

QUESTION: What solution would be more correct?

What is the best way to create a simple global event system in C#?

I'm looking to create a quick event system in C# but I'm not sure the best way to approach it. Here's how I would like it to work:

Messenger

This is where I'd like all events to be stored. The class would look something like this:

public static class Messenger
{
    // This event would have a few params, like GameState, Ammo, and Lives, or something
    public static GameStateMessage OnGameStateChanged;

    // This event could be generic, with no args
    public static Message OnGameStarted;
}

Subscribers

I'd like anything to be able to subscribe to these messages by doing something like this:

// Handler, which will be passed to the event
private void OnGameStartedHandler(GameState gameState, int ammo, int lives)
{
    // Do something
}


// Event would be subscribed to like this:
Messenger.OnGameStarted += OnGameStartedHandler;

// or this:
Messenger.OnGameStarted.Subscribe(OnGameStartedHandler);

Dispatchers

Finally, I'd like anything to be able to dispatch any of these events like so:

Messenger.OnGameStarted(gameState, ammoCount, livesCount);

// or

Messenger.OnGameStarted.Invoke(gameState, ammoCount, livesCount);

Is there any way to do something like this easily and cleanly? I'd like for it to be very fast to create new events (without having to create new classes or any boilerplate code)

Basically The Messenger class would act as a central hub for specific events, something that can easily be referenced and managed from a single location.

How can I write a general method that does not involve method logic in the name to accommodate various algorithms in Java?

I am designing an interface between a Java application and a device that accepts command sequences (a series of bytes) over a secure shell channel.

For the purpose of simplicity, there are fields

  1. fieldAlpha
  2. fieldBeta ...
  3. fieldn

that I can get and set on this device.

The command sequence is created out of a StringBuilder object, which consists of a

  • prefix
  • payload (if setter)
  • suffix

After writing about 20 of these, I figured there MUST be a more maintainable way to handle this.

public String getFieldAlpha() {
    StringBuilder sb = new StringBuilder();
    sb.append((char) 0x1B).append("ABC").append("DEF").append((char) 0x0D);
    byte[] command = sb.toString().getBytes();
    String response = (sendMessage(command));
    return response;
}

public String setFieldAlpha(String alpha) {
    StringBuilder sb = new StringBuilder();
    sb.append((char) 0x1B).append("ABC*").append(alpha).append("DEF").append((char) 0x0D);
    byte[] command = sb.toString().getBytes();
    String response = (sendMessage(command));
    return response;
}

public String getFieldBeta() {
    StringBuilder sb = new StringBuilder();
    sb.append((char) 0x1B).append("OPQ").append("RST").append((char) 0x0D);
    byte[] command = sb.toString().getBytes();
    String response = (sendMessage(command));
    return response;
}

public String setFieldBeta(String beta) {
    StringBuilder sb = new StringBuilder();
    sb.append((char) 0x1B).append("OPQ*").append(beta).append("RST").append((char) 0x0D);
    byte[] command = sb.toString().getBytes();
    String response = (sendMessage(command));
    return response;
}

// ... and so forth

I suspect a better design for an API would be two methods that select functions based on parameters. I am hung up on the fact that the command sequence changes depending on the field.

  1. getField()
  2. setField(Method FieldName, String value)

Or is there an even better way I am not thinking about? I looked possibly using Enum Objects to set the prefix and suffix of field command sequences.

How to handle many different input binary message types

I have a device that I am communicating with by sending and receiving a particular binary packet structure. The device has a somewhat well defined API, but there are over 100 possible message types that it can return. What is a good design to use to handle the processing of these different message types?

Here is an example in pseudocode, I am ignoring framing, and checksum bytes to make it clearer.

// I receive this message, where 0x00 indicates the device status,
//and each other byte is a particular error or status
message = [0x00, 0x01, 0x01, 0x04]
// The next message I receive, where 0x10 indicates system time, 
// and the rest of the fields are the integer clock seconds of the device.
message = [0x10, 0x00, 0x32, 0xFF, 0x8E]
// 100 other message types....

As you can see, each message I receive needs to be processed slightly different, has different meanings. I originally was going to use a gigantic switch statement case 0x00: process_errors() case 0x10: process_time() but I was curious if there a better design that I could use to increase flexibility of adding new message types, better useability, etc.

ReactJs: Container & Component structure usecase e-commerce

I Have make a e-commerce app with reactjs and i want refactor the structure of components because many redudant component so can make reusable component. I have read some components design structure like container concept but I still bit confused. there is a homepage like this. I draw it. [1]:https://ibb.co/WGHvCcH "homepage image"

Structure :
--Homepage
----Navbar
------Cart
----Product

Description :
1. Homepage contain navbar and product
2. navbar contain cart and others .., the cart is a icon with badge how much item type in cart ex : shampoo 1, pen 3 will produce 2, and if the cart's icon is clicked will show a tooltip contain a list of product in cart
3. product is list of products contain number of stock and other information of product

Goal :
product stock and item in cart have dependencies each other, I want to make a cart badge and product stok are reactivity (no refresh).

I have design 2 structure component, first is without redux and second with redux.

1. Without redux
[2]:https://ibb.co/nfPVzm1 "without redux"
Structure :
--Homepage (container have state product=[] and cart=[] and methods)
----navbar(component)
------cart(component)
----product(component)

2. With redux
[3]:https://ibb.co/vJKRtDb "with redux"
Structure :
Redux( product=[] and cart=[], actions)
--homepage (component)
----navbar(component)
------ContainerCart(container connect to redux)
--------cart(component)
----ContainerProduct(container connect to redux)
------product(component)

What i mean about component and container :
container : have state,methods and logic
component : just receive props state, method and just for displaying purpose

how is common patern in reactjs according to that case? is my design acceptable and suitable with container concept?

Thanx for any suggestion and explanation

is my code good example for work envionment?

My code works fine, my question is, is my code good example for the work environment? Thank you!

(function() {
  function makeQuestion() {
    var num1 = Math.floor(Math.random() * 11);
    var num2 = Math.floor(Math.random() * 11);
    var result = num1 * num2;

    function askQuestion() {
      var answer = prompt(num1 + " * " + num2 + " = ").toLowerCase();
      if (answer !== 'exit') {
        if (answer == result) {
          alert("correct");
          makequestion();
        } else {
          alert("wrong");
          makequestion();
        }
      }
    }
    askQuestion();
  }
  makeQuestion();
})();

Avoid code duplication when writing selenium tests for Firefox and Chrome

If you write tests for Selenium to check e.g. both Firefox and Chrome, the tests look very much alike, except for the setUp, see e.g. https://gist.github.com/devinmancuso/54904c005f8d237f6fec, which has identical functions test_search_in_python_chrome and test_search_in_python_firefox. There are patterns to avoid code duplication in selenium, e.g. the Page Object Pattern.

Is there a way to avoid this huge code duplication?

The way to design structure of classes

I have very simple structure of classes. Class B and C inheriting from A. The functionality is similar in the case of some functions and properties. Class B and C has different processing of the data but the classes have the same output (the function creating the output is inside the A class). Example of the structure: enter image description here

Now I need to extend the functionality. I need to add the option for a little differences in processing and the outputting of the data (class X). This option is managed by configuration file so I want keep the old way of the downloading, processing and outputting the data, e.g.:

  1. option 1 - download the data without threads using the old way processing and output
  2. option 2 - download the data without threads using the new way processing and output
  3. option 3 - download the data with threads using the old way processing and output
  4. option 4 - download the data without threads using the new way processing and output

I am not sure how to implement combination of the new processing and outputting the data. I need combination of Class B and X (BX) and Class C and X (CX). I think about these options:

  1. The easiest way but the worst - duplicating some functions in the class B and class A.
  2. Keep the classes A and B and add the combination of BX and AX classes.
  3. Rewrite the classes A and B only for downloading the data. Then add classes for processing the data and then add classes for outputting the data. All classes will sharing the objects. Looks like the best option but with the most work to do.

Is there any better option (e.g. design pattern or something like this) how to extend the classes with the cleanest way?

dimanche 28 avril 2019

Is Repository pattern a design pattern?

Is Repository pattern a design pattern ? In the list of design pattern by Gang of four its not there. If its a design pattern then under which category of patterns i.e., creational, stuctural or behavioural does it come. If not then why. Please clear my confusion?

Confused about the appropriate design pattern to be used here

I am implementing a class that can download a file from various sources such as ftp, http etc. I started with the following interface

class IInternetFileDownloader
{
public:
    IInternetFileDownloader() = default;

    virtual void Download(const std::string& urlToDownloadFrom) = 0;

};

I then implemented the classes that will perform the actual download from the appropriate endpoint. So I have a HttpFileDownloader.h as follows

#include "IInternetFileDownloader.h"
class HttpFileDownloader : public IInternetFileDownloader
{
public:
    HttpFileDownloader() = default;

    virtual void Download(const std::string& urlToDownloadFrom)
    {
        // download implementation
    }

};

So I have a FtpFileDownloader .h as follows

#include "IInternetFileDownloader.h"
class FtpFileDownloader : public IInternetFileDownloader
{
public:
    FtpFileDownloader() = default;

    virtual void Download(const std::string& urlToDownloadFrom)
    {
        // download implementation
    }

};

I can invoke the appropriate class as below

#include "IInternetFileDownloader.h"
#include "HttpFileDownloader.h"

int main()
{
    std::string downloadFromUrl = "http://www.example.org/xyz.zip";
    IInternetFileDownloader* download = new HttpFileDownloader();
    download->Download(downloadFromUrl);
}

However, I don't want to instantiate specific HttpFileDownloader or FtpFileDownloader here. In my mind, there should be another class that can just take the url and depending upon the protocol, it can construct the appropriate class. This way the client code (main.cpp) does not need to worry about the instantiation of the appropriate class. I read about the factory and builder design patterns and a little confused about which one will be best to use in this scenario?

Huge structured data classes

Good evening,

I am writing an application, which has to handle a relatively big set of structured data. My current approach is to write classes for different abstract components of the data structure and have it all connected via member instances, similar like this:

class A {
  class B {
    class D {
      /* definition of class D */
      public:
        int some_menthod();
    };

    public:
      D d;

    /* definition of class B */
  };
  class C {
    /* definition of class C */
  };
public:
  B b;
  C c;

};

Now my question is, if this is considered bad design, if there are too many nested layers. Also, would you just access some_method by traversing the class hierarchy like this:

A a;
a.b.d.some_method();

or would you write "cover functions" in class A, that access methods in the lower levels? With these cover functions, you would have to touch less code, if some of the structure changes, but on the other hand, those cover functions do not really belong to class A.

What is your opinion on this matter?

C# Implement Observable Pattaern

I`m trying to implement observable pattern using C#. In my sample code I have two kind of soldiers archer two classes: Archer and Swordsman they implement Soldier interface. Soldier interface has has four methods:

  • Attack() - command the soldier to attack the enemy
  • Died() - this method doesn`t matter in that example
  • Kill() - command our soldier to kill the enemy
  • BattleCry() - celebration of ALL my soldiers after emeny is killed

and one property bool IsEnemyKilled - when Kill() method is called IsEnemyKilled becomes true.

And here is what I want to do: I know that to implement Observer Pattern I need Provider and Observers. When one of soldiers e.g. archer - kills an enemy archer.Kill();. IsEnemyKilled become true (this is my provider) and all my other soldiers (my observers) e.g. swordsman and another archer must be notified that IsEnemyKilled is true and they must call BattleCry().

I`m confused how to do it. I will appreciate if anyone suggest in idea. Here is my sample code.

namespace ImplementObservable
{
    class Program
    {
        static void Main(string[] args)
        {

            var archer = new Archer();
            var swordsman = new Swordsman();
            archer.Attack();
            archer.Kill();
            Console.ReadKey();
        }
    }

    public class Archer : Soldier
    {
        bool IsEnemyKilled;
        // watch somehow prop "IsEnemyKilled" and if it changes to true call BattleCry() for all units

        public void Attack()
        {
            IsEnemyKilled = false;
            Console.WriteLine("Archer attack!");
        }

        public void Died()
        {
            IsEnemyKilled = false;
            Console.WriteLine("Archer died :(");
        }

        public void Kill()
        {
            IsEnemyKilled = true;
            Console.WriteLine("Archer killed enemy! Hurray!!");
        }

        public void BattleCry()
        {
            Console.WriteLine("Archer: Go for victory !");
        }
    }

    public class Swordsman : Soldier
    {
        bool IsEnemyKilled;
        // watch somehow prop "IsEnemyKilled" and if it changes to true call BattleCry() for all units

        public void Attack()
        {
            IsEnemyKilled = false;
            Console.WriteLine("Swordsman attack!");
        }

        public void Died()
        {
            IsEnemyKilled = false;
            Console.WriteLine("Swordsman died :(");
        }
        public void Kill()
        {
            IsEnemyKilled = true;
            Console.WriteLine("Swordsman killed enemy! Hurray!!");
        }

        public void BattleCry()
        {
            Console.WriteLine("Swordsman: Go for victory !");
        }
    }

    public interface Soldier
    {
        void Kill();

        void Attack();

        void Died();

        void BattleCry();
    }
}

MVVMC iOS App with multiple ViewModels & how they can communicate each other

He i am developing an iOS App and its base architecture is MVVMC design pattern. Using coordinators for navigation logic.

I have situation, where I have a complex UI with different components. So obviously I have to modularise my design and create multiple ViewModels for different UI sub sections or Views. All these are attached a parent view.

My question is where should I keep those ViewModel references?

I have the following options. Please help me to choose the right approach among these.

1). Have a parent view lets this parent view hold this references to those child ViewModels and pass the updates among them.

2). Have a parent ViewModel. Lets have these child ViewModels attached to this parent ViewModel and Manage the child ViewModel updates with in the ParentViewModel and pass to the view.

3). Lets the coordinator have these references to the child ViewModels and manage the updates among them with in the coordinator and pass to the view.

Or is there any other standard practice other than this? Please help me to have a clear path here.

Any suggestions with some examples will be more helpful.

How to design media streaming service like youtube?

I would like to know how a media server like youtube streams the same media, to multiple users with different config(speed, resolution etc.) where each user can seek the media from anywhere

I am looking for the answer from the appropriate data structure and design point of view. so please dont reply anything which is a particular language specific.

How to separate Business logic and metrics log?

In lots of Applications, we need to log statistics metrics, such as hist, guage and so on. This will pollute the business logic. For example:

boolean buy(int id) {
  metrics.increament(); // for qps maybe.. 
  int remain = checkRemain();
  metrics.hist(remain); // log remain amount..
  if (remain > 0)
    return true;
  else
    return false;
}

which, I hope, I can only write down the biz logic, such as:

boolean buy(int id) {
  int remain = checkRemain();
  if (remain > 0)
    return true;
  else
    return false;
}

But also I can get the metrics.

My question is: what's the best practice to separate Business logic and metrics log?

I know AOP may solve this, do I have any other choice?

Design pattern to limit access to a shared resource

Problem statement

At start up multiple machines will become online. There is a scheduler that will run on each of those machine. The scheduler will Fire every 5 minutes on each machine. There will he bunch of data to read from Cassandra. However only one machine must read those messages from Cassandra and must delete the messages after it’s done. It two or more machines read and process the data it will unnecessarily increase the load on the downstream system.

Possible solutions: Use zookeeper to implement a distributed lock. Perhaps make use of Leader election design pattern. Shared resource design pattern also work in the same way. Modified leaky bucket design pattern which can work with distributed application

Is there a design pattern which can be used to solve this problem?

How to make an atomic design system in Sketch step-by-step

I need to build an atomic design system in Sketch, but all articles in internet just about how great design systems are, and how they can improve work of designers, developers, etc. No complete manual of how to build them from scratch. Can somebody please recommend some good resource about it? I still need to improve my work with Symbols)) Thank you!

samedi 27 avril 2019

would using JavaScript classes or modular pattern be better for this project?

I am trying to create a web based music player (JS only) that is fairly complicated and would like to create it as neat as possible so I can reuse the code for similar projects.

At this point I am stock what approach would be more suitable. I can do it using modular pattern such as the below example. Or use ES6 and separate the code into few classes. I do not know which approach would be more professional and commercial for this.

(function() {
    var myModule = { 
    init: function() { // Initialising the module
    this.cacheDom();
    this.bindEvents();
    this.render();
},
catchDom: function() { // DEALS with HTML to not reapeat in the code
    this.$el = $("#plugin");
  this.$button = this.$el.find("button");
},
bindEvents: function() { // Translates the current state of the code into the HTML 
    this.$button.on('click', this.aFunction.bind(this));
},
render: function() {// UPDATING INTERFACE
  this.$ul.html("ADD DATA TO HTML");
},

aFunction: function(){
    console.log("something")
}

}

  myModule.init();
});


class class1 {
  constructor(name, location) {
    this.name = name;
    this.location = location;
  }
  start() {
    alert(this.name + 'Meetup ' + 'is started at ' + this.location);
  }
}
let obj1 = new class1('JS', 'Blr');
let obj2 = new class1('Angular', 'Noida');
obj1.start(); //JSMeetup is started at Blr
obj2.start(); //AngularMeetup is started at Noida


import class1 from './class1.js'
.
.
.
.

Again the point is to keep the plugin profession, easy to extend and reusable for similar future projects.

The answer would be the one that explains why one is better than the other.

How to design this relationship between classes?

I recently had an object/class design question. The problem was this:

"You have an University and it has employees, which can be either Student or Teacher."

They asked me to design only the relationship of the employees so I made a simple inheritance diagram

Then he asked me what happens if Student can be a Teacher, it can't inherit from Employee and Teacher. I couldn't answer so he designed a solution with a Role class.

Another solution could've been using Decorator Pattern?

Diagrams here: https://imgur.com/a/GgEQimb since I can't post images yet.

¿What dou you think of these approaches?

Thanks

Destructor patterns in software architechture

Just as Factory Pattern, Builder Pattern, etc are Creational Patterns.

Does any Destructor pattern exist?

If any... name some.

why this object still exists without it's composed class even tho it's com-positioned

i know that in composition the class composed inside, it's object should not exists outside of its class, but in the example below the Sword class is composed into the Unit class, and i can still create it's object independently without the unit class, like i did in main, how i can prevent for Sword object to exists independently?

public class Main {

public static void main(String[] args) {

    Sword sword = new Sword();

}
}

class Sword {
private int a;
}


class Unit {
private String s1;
private Sword s;

void setProperty(String s1, Sword s) {
    this.s1 = s1;
    this.s = s;
}

}

vendredi 26 avril 2019

Ownership responsibility and reusability

I had a disscusion with a collegue about approaches to these topics in our project. Im making a Progress System, in short a ProgressMonitor class and a Task class, ProgressMonitor handles an array of tasks. All pretty straight forward stuff. But when it came to the tasks ui, we had to opinions. Each task has his own UI. We agree we should have an HUD class for handling UI. The difference in opinion is, he wants the HUD to handle each specific task's UI and so the HUD class would grow quite big and the task would have near to no logic about its UI. My opinion, The HUD would only handle the logic that is the same for all things in our project that need UI's, and all specific logic is handle by the objects that need UI. Advantage of his is some ownership (objects that need to acces some ui info can easily get it from HUD) My advantages, HUD stay light clean and reusable.

What would be more correct acording to OOP?

Design Pattern Difference between Java and C#

I need to write a comparative report comparing Java and c# on Design pattern. I searched a lot but I didn't find anything. can someone help me to write some differences java vs c# on these topics of design pattern?

Implement Singleton Implement Factory Implement Adapter Implement Iterator Implement Strategy

Having trouble with inheritance in implementation of C++ factory method

Fairly new to design patterns, maybe I've missed the answered question already. I'm having trouble practicing the factory design pattern due to an inheritance issue.

This is the base class

 #ifndef FACTORY_H
 #define FACTORY_H

 #include <iostream>
 #include "truckfactory.h"

 class factory{

     public:
         std::string typeOfCar;
         factory(){}

         virtual void identifyCar(){
             std::cout << "This car is a " + typeOfCar << std::endl;
         }

         truckfactory* createTruck(){
             return new truckfactory();}
 };
 #endif

And this is the subclass of the base factory class.

 #ifndef TRUCKFACTORY_H
 #define TRUCKFACTORY_H

 #include "factory.h"
 class truckfactory : public factory{

     public:
         truckfactory(){
             std::cout <<"TruckFactory made"<<std::endl;
             typeOfCar = "truck";
         }   
 };
 #endif

Trying to implement as such

 #include "factory.h"

 int main(){

     factory carFactory;
     truckfactory* truck;
     truck = carFactory.createTruck();

     carFactory.identifyCar();
     truck->identifyCar();

     return 0;
 }

However I run into the following issues

./truckfactory.h:5:29: error: expected class name
class truckfactory : public factory
                            ^
./truckfactory.h:11:13: error: use of undeclared identifier 'typeOfCar'
            typeOfCar = "truck";
            ^
factorytest.cpp:10:12: error: no member named 'identifyCar' in 'truckfactory'
    truck->identifyCar();

I was looking around at other inheritance issues, but I couldn't find one that solves what I'm looking at.

Thanks for the help, and sorry if it's a repost

Link object to multiple object for delegation

Folder Structure :-

ProjectModules
   |-- Input
     |-- aDelegatee.js
     |-- aDelegatee.js
   |-- Module
     |-- aDelegator.js
     |-- aDelegator.js
   |-- Helper
     |-- aDelegatee.js


All the .js have an object :-

For Eg, aDelegator.js,

var stdIn = require('../Input/aDelegatee');

var helper = require('../Helper/aDelegatee');

var obj = Object.create(helper);

var obj = {
  promptForInput: { 
    this.input = this.aPropertyInInputDelegatee; // could be present in any of the two Input folder .js file// ...,
  task1: function task_one() {
    this.aPropertyInHelperDelegatee; // pass this input array, to be used in helper sub routine.
  }
}

aDelegatee.js present in Input folder:

module.exports = { 
  pulicProperty: // ...
}

aDelegatee.js present in helper.js, this file can perform its routine using its own object input array when executed independently, aDelegator.js object input array instead, when called as a subroutine of Module folder aDelegator.js

module.exports = {
  input: [],
  pulicProperty: function {
    // use this.input  
  }    
}


How I do it:

aDelegator.js

// All code same as in aDelegator.js code before this one

var obj = {
  promptForInput: stdIn.aPropertyInInputDelegatee; // here I am using name instead of this reference
  task1: function task_one() {
    this.aPropertyInHelperDelegatee;
  }
}

I am unable to use correct this reference in aDelegatee.js of helper.js.

I don't want to use stdIn.aPropertyInInputDelegatee. should be this.aPropertyInInputDelegatee instead.

Using adapter pattern when consuming 3rd party APIs and creating a domain in Laravel

In my Laravel REST API project I mainly consume 3rd party APIs. For that, I have a 'Services' folder grouped by APIs (Accommodation, Planning, Discount etc) to send correct parameters to APIs and get the raw data.

I feel that I need to use adapter pattern here, because this 3rd party outputs need to be formatted.

Let me try to give an example.

I have an EventDao interface (Data access object) and one or multiple concrete EventDao classes like EventbriteDao.

I also have an adapter for each concrete DAO. e.g: EvenbriteAdapter

I will have some business logic somewhere so I need to have an Event entity class. To pass the adapter's data to the entity, I need an EventDTO class (data transfer object)

Finally I can call the eventDao (via interface thanks to Laravel's service providers)

I pass its raw output to the adapter, then adapter's output to the entity. Then I can call one of methods of the entity class. (After that I need to convert it to a proper json data, but it is the easy part.)

I don't get where to put other CRUD logic like updateEvent, deleteEvent, getAll etc. Should I call them directly in controller or create repositories (the repository pattern)? I am confused about it.

Would it be a good approach or over-engineering? Because I have 5-6 classes/interfaces other than controller.

Another problem is calling EventbriteAdapter directly in the controller. Should I have an interface for it? In this case I will need to bind both service and adapter interfaces to its implementations in AppServiceProvider.

Here example codes for some of the files I mentioned are:

interface EventAdapter
{
    public function getId();
    public function getName();
    public function getStartDate();
    public function getLocationName();
}



class EventbriteAdapter implements EventInterface
{
    private $raw;

    public function __construct(array $raw)
    {
        $this->raw = $raw;
    }

    public function getName()
    {
        return $this->raw['name'];
    }

    public function getStartDate()
    {
        return $this->raw['start'];
    }

    public function getLocation()
    {
        return $this->raw['venue']['name'].' '.$this->raw['venue']['address'];
    }
}


// Fetch event from Eventbrite (or other third-party)
$result = fetchEventFromEventbrite();

// Wrap event in adapter
$adapter = new EventbriteAdapter($result);

How to design a service which can be exposed a file endpoint, REST endpoint and MQ endpoint?

I have a transaction processing service, which can consume transaction from MQ, File or web service.

  • MQ - output goes back to MQ
  • File - output wrtites into filesystem
  • Web service - sends back realtime response

Again request/response can be in any format - csv,json or xml Request can be a list containing multiple transactions.

What is the best way to design for such requirement ?

Object instance as a member of a list --> Is this "pythonic"? Is this lege artis?

I like to have your opinion or a suggestion to this code:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


# Defines the class (Element) that will be used in the Container
class Element:
    def __init__(self, address):
        # The address is the identifier for this element
        self._address = int(address)

    def theaddress(self):
        # Getter for the address
        return self._address

    def __eq__(self, other):
        # This function will be called if we like to check if this instanse is already a
        # member of the container instance
        print("A __eq__ called: %r == %r ?" % (self, other))
        return self._address == other._address


# Defines the class (Container) which holds n instances of Element class
class Container:
    def __init__(self):
        # Basically it is a list
        self._listcontainers = list()

    # If we like to append a new element instance, we have to check if new one is already available
    # with the same address. So we like to never had the same address twice or more times!
    def appendcontainer(self, possibleElement: Element = Element(1)):
        # Calls the __eq__ element of the Element class to check if this one (with exactly this address) is already present
        if possibleElement in self._listcontainers:
            # If the possibleElement is in the container list
            print('Address %i of this element %s is already existing.' % (possibleElement.theaddress(), possibleElement))
            return False
        else:
            # If possobleElement is new append it to the containerlist
            self._listcontainers.append(possibleElement)
            print('Added element: %s with address: %i' % (possibleElement, possibleElement.theaddress()))
            return True

    # Returns the available elements in the containers
    def lengthcontainers(self):
        return len(self._listcontainers)


def main():
    # List of containers
    myContainer = Container()

    # New element with address 1
    newElement1 = Element(1)
    myContainer.appendcontainer(newElement1)

    # New element with address 2
    newElement2 = Element(2)
    myContainer.appendcontainer(newElement2)

    # New element with address xyz
    newElement3 = Element(2) # You can play with the addresses...
    myContainer.appendcontainer(newElement3)

    print('Available elements: %i' % myContainer.lengthcontainers())


if __name__ == "__main__":
    main()


Now:

  • I have a class Element which represents an abstraction of some data. It will contain some logic by itself as private methods too...
  • I have a class (Container in this example) which holds n element instances.
  • I need to prevent the appending of an element with the same properties. In this example - the same address.

Questions:

  • I like to know if this is state of the art for doing the identification of an element?
  • Maybe is there a better way for doing this in Python 3?
  • Especially the __eq__ function is very interesting for me. Because, _address should be a private variable and I get a warning at other._address --> "Access to protected member _address of a class...". Do I have to consider something here?

Any opinion or suggestion will be very helpful for me. Actually I'm doing only prototyping, but it should be the basic for an real project which holds some data in this case.

When a programmer should use Interface over Abstract class and vice versa

There are may Java interview question and answer for difference between Java Interface and Abstract class. My question is In which scenario a programmer need to use Interface over Abstract class and vice versa. a simple layman example will help

How View Holder uses Singleton Design Pattern in Android?

I know View Holder itself a design in android to not call findViewByID many times but I was reading articles regarding all the design used in android SDK code. At many places, this says View holder uses singleton design. Can Anyone help how view holder is using singleton design?

regex pattern for serial-number input

Someone can help me pls I have a serial-number input and I need the expression regex to validate this input [ex: 11-22-33333] number of character max=11, I added this pattern but it doesn't work

"pattern": "^[0-9]{2}*-?[0-9]{2}*-?[0-9]{5}$",

Is it a good idea to storage validations in DAO?

I have web application. The structure: controller which take an entity and DAO which save the entity and making some other actions. Is this a good idea to check stateless validations (size of name for example) in controller and sate validations (duplicate email in db for example) in DAO. Is there good practices for that? Can you advise some resources or book to get it?

jeudi 25 avril 2019

Good design approach for reading value from a database and publish as JSON

What could be a good design approach / pattern for following problem statement (in Java) - "I would like to read data from a relational database (as of now using hibernate) and publish that to a web socket client (both should part of one component). The web socket client will ask for the data when he needs it. Already published data should not be published"

How to apply template method pattern in Python data science process while not knowing exactly the number of repeating steps

I like to apply the template method pattern for a data science project while I need to select or identify target subjects from a large pool of original subjects. I will create tags based on different characteristics of these subjects, i.e., age, sex, disease status, etc.

I prefer this code to be reused for future projects of similar nature. But all projects are somewhat different and the criteria of selecting subjects to be in the final filtered pool are different from one another. How do I structure the subject_selection_steps in such a way that it is flexible and customizable based on project needs. Currently, I only included three tags in my code, but I may need more or less in different projects.

import sys
from abc import ABC, abstractmethod
import pandas as pd
import datetime
import ctypes
import numpy as np
import random
import pysnooper
import var_creator.var_creator as vc
import feature_tagger.feature_tagger as ft
import data_descriptor.data_descriptor as dd
import data_transformer.data_transformer as dt
import helper_functions.helper_functions as hf
import sec1_data_preparation as data_prep
import sec2_prepped_data_import as prepped_data_import

class SubjectGrouping(ABC):
    def __init__(self):
        pass

    def subject_selection_steps(self):
        self._pandas_output_setting()
        self.run_data_preparation()
        self.import_processed_main_data()
        self.inject_test_data()
        self.create_all_subject_list()
        self.CREATE_TAG1()
        self.FILTER_SUBJECT_BY_TAG1()
        self.CREATE_TAG2()
        self.FILTER_SUBJECT_BY_TAG2()
        self.CREATE_TAG3()
        self.FILTER_SUBJECT_BY_TAG3()
        self.finalize_data()        

    def _pandas_output_setting(self):
        '''Set pandas output display setting'''
        pd.set_option('display.max_rows', 500)
        pd.set_option('display.max_columns', 500)
        pd.set_option('display.width', 180)

    @abstractmethod
    def run_data_preparation(self):
        '''Run data_preparation_steps from base class'''
        pass

    @abstractmethod
    def import_processed_main_data(self):
        '''Import processed main data'''
        pass

    def inject_test_data(self):
        '''For unitest, by injecting mock cases that for sure fulfill/fail the defined subject selection criteria'''
        pass

    def create_all_subject_list(self):
        '''Gather all the unique subject ids from all datasets and create a full subject list'''
        pass

    def CREATE_TAG1(self): pass
    def FILTER_SUBJECT_BY_TAG1(self): pass
    def CREATE_TAG2(self): pass
    def FILTER_SUBJECT_BY_TAG2(self): pass
    def CREATE_TAG3(self): pass
    def FILTER_SUBJECT_BY_TAG3(self): pass

    def finalize_data(self): 
        pass

class SubjectGrouping_Project1(SubjectGrouping, data_prep.DataPreparation_Project1):
    def __init__(self):
        self.df_dad = None
        self.df_pc = None
        self.df_nacrs = None
        self.df_pin = None
        self.df_reg = None
        self.df_final_subject_group1 = None
        self.df_final_subject_group2 = None
        self.df_final_subject_group3 = None
        self.control_panel = {
            'save_file_switch': False, # WARNING: Will overwrite existing files
            'df_subsampling_switch': True,  # WARNING: Only switch to True when testing
            'df_subsampling_n': 8999,
            'random_seed': 888,
            'df_remove_dup_switch': True,
            'parse_date_switch': True,
            'result_printout_switch': True,
            'comp_loc': 'office',
            'show_df_n_switch': False, # To be implemented. Show df length before and after record removal
            'done_switch': False,
            }

    def run_data_preparation(self):
        self.data_preparation_steps()

    def import_processed_main_data(self):
        x = prepped_data_import.PreppedDataImport_Project1()
        x.data_preparation_steps()
        x.prepped_data_import_steps()
        df_dict = x.return_all_dfs()
        self.df_d, self.df_p, self.df_n, self.df_p, self.df_r = (df_dict['DF_D'], df_dict['DF_P'], 
            df_dict['DF_N'], df_dict['DF_P'], df_dict['DF_R'])
        del x

if __name__=='__main__':
    x = SubjectGrouping_Project1()
    x.subject_selection_steps()

HTML input must contain a specific string

I have a input field, which will record the response of the end-user. Say the label of it is Linkedin URL. The user who has to enter the linkedin URL could enter some other input(facebook.com/satyaram2k14), which is not invalid. So how can one check, if the url entered contains string 'linkedin.com' along with other text. Final url should be 'linkedin.com/satyaram2k14'. How can I check for this pattern at front-end.

properties table pattern vs storing all properties in json column

I'd like some feedback on having all properties a model can have in a properties table accessed via relationship (using laravel relationships) vs storing all properties/settings in the same table but in a json column.

Currently, my application has a propeties table called settings that is also polymorphic in nature so multiple models can store their properties there. This table has columns like

key (string), 
value(string), 
type (string) - tells if the value is of string, integer, boolean, json type 

so that I do not send strings to javascript frontend, but instead I can send string, integer, boolean native types for better handling of types in frontend. I do this conversion before I send the properties to the frontend using php function that cast string values to int, boolean, json or string, depending on the type.

This means if a model has 40 properties, all get stored in its own row, so creating one model leads to creating 40 rows that store all properties it may have.

Now the above approach vs approach where I just have a single json column, we can call it settings and I dump all these 40 properties there.

What do I win with json column approach? I shave off a table and I shave off an extra relationship that I need to load on this model each time I do some queries. I also shave off having to each time I get properties cast them to integer, boolean, json or string. (remember the type column above) To keep in mind these properties do not need to be searchable, I need them only for reading from them. I will never use them in queries to return posts based on these properties.

Which one is a better idea to use, I'm building a CMS btw you can see it in action here: https://www.youtube.com/watch?v=pCjZpwH88Z0

the design philosophy about why does spring framework refresh context?

when I study spring-framework's source code, I notice that there are many situations in which ConfigurableApplicationContext's refresh method is invoked.

I wonder why Spring-framework design the refresh mechanism。

How should setup code be handled in entity-component-system?

I am writing an ECS framework and also a game with it, in Python. In an ECS framework, components should contain only data. However, sometimes setup code is needed to create the data. For example, in an audio component, the data would be the volume of the the sound to play and the path to the audio file. But in the audio-playing library, there are objects to represent sounds, which have a sound.play() method, for example. My question is whether this object should be created in the component, which sort of violates the rule that entities should be pure data, or in the system. If it should best be done in a system, it would only need to be done once (and it would harm performance if the audio file needed to be created once per frame). What is the best way to do this?

Make Interfaces Easy to Use Correctly and Hard to Use Incorrectly - Example

I was reading best practices for developers and found one suggestion is,

Make Interfaces Easy to Use Correctly and Hard to Use Incorrectly

Can anyone describe with minimal sample code to understand the principle. I have tried to search on the internet but did not find any example.

class Account{
    void process(){}
}

interface IBankAccountService {

    boolean check(Account acc);
    void process(Account acc);
}

class ScbAccountService implements IBankAccountService {

    @Override
    public boolean check(Account acc) {
        return true; // check account consistency
    }

    @Override
    public void process(Account acc) {
        acc.process(); // proceed operation
    }
}

Is that above example violating the principle? I so how can I apply this principle in this example.

Exporting SqlRowSet to a file

I want to export the results of an SQL query, fired through JDBC, to a file; and then import that result, at some point later.

I'm currently doing it by querying the database through a NamedParameterJdbcTemplate of Spring which returns a SqlRowSet that I can iterate. In each iteration, I extract desired fields and dump the result into a CSV file, using PrintWriter.

final SqlRowSet rs = namedJdbcTemplate.queryForRowSet(sql,params);
while (rs.next()) {

The problem is that when I read back the file, they are all Strings and I need to cast them to their proper types, e.g Integer, String, Date etc.

while (line != null) {
    String[] csvLine = line.split(";");

    Object[] params = new Object[14]; 
    params[0] = csvLine[0];
    params[1] = csvLine[1];
    params[2] = Integer.parseInt(csvLine[2]);
    params[3] = csvLine[3];
    params[4] = csvLine[4];
    params[5] = Integer.parseInt(csvLine[5]);
    params[6] = Integer.parseInt(csvLine[6]);
    params[7] = Long.parseLong(csvLine[7]);
    params[8] = formatter.parse(csvLine[8]);
    params[9] = Integer.parseInt(csvLine[9]);
    params[10] = Double.parseDouble(csvLine[10]);
    params[11] = Double.parseDouble(csvLine[11]);
    params[12] = Double.parseDouble(csvLine[12]);
    params[13] = Double.parseDouble(csvLine[13]);

    batchParams.add(params);
    line = reader.readLine();
}

Is there a better way to export this SqlRowSet to a file in order to facilitate the import process later on; some way to store the schema for an easier insertion into the DB?

How to design a pub-sub system where there can be multiple publisher for same entity?

Consider the following situation:

  1. There is a User table with fields like name, email, contact_no etc.
  2. We have multiple products/system(with their own db) which use User information for various purpose.
  3. These systems remain in sync by pub-sub pattern eg: System 1 changes name is consumed by system 2 and make changes in system 2.
  4. For simplicity let us assume there are 3 systems:
    • S1 having UI for the user. Here user can himself change his information.
    • S2 system given to the sales person. Here user can call sales person and update their information.
    • S3 another product which uses information from S1 and S2 for various computations.

So information can be published from S1 and S2.

Suppose a user initially have name N1.

  • At time t1, user updates name from N1 to N2.
  • At time t1, sales person updates name from N1 to N3.

  • Now S1 consumes event from S3 and updates name to N3. S2 consumes event from S1 and updates name to N2.

  • In S3 name can be anything N2 OR N3 depending which event is consumed first.

This has caused a lot of data consistency among various system.

In ideal system there is only one publisher but due to requirement we had to add publishing events from Sales panel. What can be done to minimize data inconsitency?

How to manage multiple clients website having same code structure but different UI?

I want to create websites for many colleges using MVC.
Since coding structure will be common for all the client websites but the website templates will be different I need suggestions on handling this.
Do I need to create a core framework for this and use the same for other website projects? If I do so, then how do I handle the website template as these will be different.
Any opinion will be a great motivation for me to start.

mercredi 24 avril 2019

To what extent does Angular/Typescript impose the rules of SOLID?

Just how reusable are components? Do the rules of SOLID apply for medium-sized applications? In my opinion, it would seem like some rules of SOLID apply for various providers such as services, and maybe one component or two. However, for a small-medium sized application, is it supposed to reuse many, many components?

For example, say you wanted to make a ngForOf loop. Given the circumstance, would you create a component that receives this input and displays the data in its given order, and re-use this component the 2-3 times its usability is reproducible? (This is probably a bad example, not even sure if this is possible in place)

How does this connect with software programs? What are the differences between SOLID in Angular/Typescript in comparison to software?

What is the recommended way to manage application state of a PyQt desktop application?

I am developing a PyQt5 based desktop application that processes real-time information. The application includes many modules(ex. Connecting to a web socket server) implemented as different classes with each module having their own internal state (such as whether the module is running, encountered an error or not, whether socket connection successful or not etc..). The application has to expose this internal state of different modules to the user through a GUI panel. Is there any recommended design pattern to manage the internal state of these different modules at one place?

I am looking at Memento Pattern and wondering if this is the right approach. Appreciate any design thoughts on this.

Appropriate design patterns for this problem

I'm asking if anyone could help me in this problem

  • Imagine an online shopping portal which displays the products for selling on its home page.
  • These products are coming from a third-party vendor with which the portal has tied hands to sell products.
  • The third-party vendor already has an inventory system in place which can give the list of products it is selling and their number in stock; there is no interface available to online shopping portal with which the portal can call the third-party vendor’s inventor code.
  • We want to call the third-party vendor’s code which is incompatible with client (online shopping portal) code to show the products to users on the home page.
  • Also, when online shopping portal users click on “notify me when item is back in stock” for a particular item that is out of stock currently, they get notified through email.

what design patterns should I use and for what?

return statement approaches - cons and pros

Which return style in your opinion is „better”, more universal? For example, for this operation:

foo.filter(...).map(...).reduce(...)...

We have:

1st approach

const result = foo.filter(...).map(...).reduce(...);

return result;

2nd approach

return foo.filter(...).map(...).reduce(...);

If it comes to 1st approach I think it’s more readable if we have long code which result is stored in variable. But in 2nd option we don’t have extra variable, so we save memory a bit. Do you know any other cons nas pros? Which style should I use?

How to automatically register new subclasses?

I'm working on the reporting module of our web-application. There are six reports available to the client, each of them has a code. The problem is that now the module is not closed for modification with respect to potential addition of new reports, thus violating OCP.

To elucidate, I have the following set of classes:

A generic report class, which all other reports inherit:

public abstract class Report 
{
    private final String code;

    Report(String code)
    {
        this.code = code;
    }

    public String getCode() { return code; }

    public abstract byte[] generate();
}

A servlet which manages POST requests for report generation:

public class ReportServlet extends HttpServlet
{

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        Report requested = ReportRegistry.lookup(req.getParameter("report_code"));
        byte[] bytes = requested.generate();
        // attach bytes to response
    }

}

Report registry, which stores all existing reports for later access:

public class ReportRegistry
{
    private static final Map<String, Report> registry = new HashMap<>();

    static
    {
        // Violates OCP!
        registerReport( GlobalReport.getInstance() );
        registerReport( AvailablePackagesReport.getInstance() );
        registerReport( BadgeReport.getInstance() );
        registerReport( PlacementReport.getInstance() );
        registerReport( TerminalReport.getInstance() );
        registerReport( VerActReport.getInstance() );
    }

    private ReportRegistry() { }

    static void registerReport(final Report report)
    {
        registry.put(report.getCode(), report);
    }

    public static Report lookup(final String reportCode)
    {
        return registry.get(reportCode);
    }
}

However, ReportRegistry violates OCP, since we need to add an to its static block every time a new report is created.

My question is: how can I make any new subclass of Report to be registered automatically, without any explicit mentioning?

Java generic inheritance "unchecked cast"

I've implemented a simple system of payment processing using java generics. It compiles and works at runtime, but i confused by the "unchecked cast" warning.

enum PaymentType {
    CARD, SAVED_CARD
}

interface PayData {
}

class CardPayData implements PayData {
    private String cardNumber;
    private String cvc;
}

class SavedCardPayData implements PayData {
    private String cardId;
}

interface PayService<T extends PayData> {
    void pay(T payData);
}

class CardPayService implements PayService<CardPayData> {
    @Override
    public void pay(CardPayData cardPayData) {
        // i need concrete class CardPayData here
    }
}

class SavedCardPayService implements PayService<SavedCardPayData> {
    @Override
    public void pay(SavedCardPayData payData) {
        // i need concrete class SavedCardPayData here
    }
}

class PayServiceFactory {
    private CardPayService cardPayService = new CardPayService();
    private SavedCardPayService savedCardPayService = new SavedCardPayService();

    public PayService getService(PaymentType paymentType) {
        if (paymentType.equals(PaymentType.CARD))
            return cardPayService;
        else
            return savedCardPayService;
    }
}

class PaymentProcessor {
    PayServiceFactory payServiceFactory = new PayServiceFactory();

    public void serveRequest(PayData payData, PaymentType paymentType) {
//        here i have 'unchecked cast' warning
        PayService<PayData> payService = (PayService<PayData>) payServiceFactory.getService(paymentType);
        payService.pay(payData);
    }
}

Any attempts to move away from such warning lead me to compiltation errors. For example i've tried to return generic type from my factory method, and received nothing but compilation error:

// return generic
public PayService<? extends PayData> getService(PaymentType paymentType) { ... }

 public void serveRequest(PayData payData, PaymentType paymentType) {
        PayService<? extends PayData> payService =  payServiceFactory.getService(paymentType);
// error here:
// pay (capture <? extends PayData>) in PayService cannot be applied to (PayData)
        payService.pay(payData);
    }

Prototype Design Pattern

Why I need to use Prototype Design Pattern ? Instead of that I can directly assign that value right ? for example

as per Prototype Design Pattern we have to clone like below

same I can as below right ?

Different properties interpreting of some constant object in WPF

I have a data packet, that body is consist of byte array. Also I need interprete a packet fields in few variations, but the body is still constant. For example: AA-BB-CC-DD-EE-FF - constant packet's body. In first interpretation: AA-BB-CC - as a Parameter 1 and DD-EE-FF - as a Parameter 2. In second variation: AA-BB - as a Parameter 3, CC-DD - Parameter 4, and EE-FF - Parameter 5. And so on.

I see few options to realize such behavior:

  1. In single class create all of the needed properties (parameter 1...parameter 5), and in caller class check the variation flag.
  2. Create few derived classes, and each class contains only specific properties (parameters 1 and 2 in first case, parameters from 3 to 5 - in the second).

Now to show packets in WPF I use 1st option. I have ListView and it's style as GridView:

<ListView x:Name="lv" />

When I need to visualize packets in first interpretation:

lv.Style = CType(TryFindResource("packetsStyle_1"), Style)

The packetsStyle_1 contains columns "Parameter 1" and "Parameter 2".

When I need to visualize packets in other interpretation, I just change the style of ListView:

lv.Style = CType(TryFindResource("packetsStyle_2"), Style)

The packetsStyle_2 contains columns "Parameter 3", "Parameter 4" and "Parameter 5".

This kind of realization is not object-oriented, as I understand. I want to do this with the OOP (option 2) - base class of packet with common properties and inherited classes with specific properties. But what is the WPF way to refresh GUI in this case? Do I need create two objects List(of PacketVar1) and List(of PacketVar2) and change ListView item's source and style? But list of packets is huge enough, and takes a lot of memory. Or what is the right implementation?

mardi 23 avril 2019

What is the concrete difference between App Shell Skeleton, MVC and the PRPL pattern?

I am used to using a pattern for web development but I would like to develop a pwa. I saw information about App Shell Model, MVC, the PRPL pattern but I don't understand the concrete difference between them.

How to make object accessible from anywhere, without misusing static methods?

This question relates to a desktop application.

Something I'm always thinking about, is a way to be able to access an object that could be considered global, like if it is declared as static. But I always avoid this.

For example, in an application a User object (or something similar) is present very often. Imagine somewhere from the business logic a data model/repository is used, and you need the user ID to pass it as a parameter to the data layer so it can load the corresponding data for the user. Most times in web applications I see that information like a user ID is coming from a URL parameter, or HTTP post data, and is sent into a controller via its action method.

In desktop applications this is different, since all 'state' stays the same. Suppose a user object is constructed once on program startup, and of course stored now in memory somewhere. How do I access it from within another part of the application? It seems there are only two options:

  1. Using a static method on a general class that contains the user object, which returns it.
  2. Injecting the user object through the whole tree of classes that need the object.

I think both options are ugly and not optimal. Since I think it's a very common situation, what are best practises to keep a good structure?

I am developing and android app. How i will fill a spinner with basic currencies format patters?

I am developing and financial android app with 6 languages like {Engish, Hindi,Greek, Russian, French, Spanish}. I have a textView with a double value and i want to give the user the option to select from a spinner the currency format pattern of his choice. I want to format the double value of textView with the pattern from the spinner. I dont know where to start!

formatter =  NumberFormat.getNumberInstance(Locale.UK) as DecimalFormat
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 0
formatter.applyPattern("#,###,###.##")

is there a better way to invalidate the redis cache used in asp.net mvc application?

I have a asp.net mvc 5 application with entity framework 6.1.

For caching i have used redis cache in my application. that works fine for me all add update and remove items with key are working.

what i am expecting is that whenever a request comes for data it will first check cache then go towards the db if data is not found in cache and then populate cache accordingly for the subsequent requests. I have implemented Generic repository pattern with data storage and caching strategies.

The issue i am facing is this:

  • once the data is cached then how i come to know that any updates, delete or add operation is done to the data then sync those data changes with redis cache

  • how should i store data into redis database for different tables as each table may have data with same primary key values. then while fetching record from redis how do i come to know that value with key 1 is from table A, or table B.

Below i have shown the code for my repository class with injectable redis cache. what i want for methods like GetList, firstOrDefault fisrt the data is served from cache then from my db if needed

public abstract class GenericRepository<TEntity> :IBasicOperations<TEntity> 
where TEntity : class
{

    protected IDataStoreStrategy<TEntity> _dataStoreStrategy;    // Data Storage Strategy e.g, SQL SERVER
    protected ICachingStrategy _cachingStrategy;    // Caching Strategy e.g, Redis
    public GenericRepository(IDataStorageContext db, ICachingStrategy cache)
    {
        _cachingStrategy = cache;
        this._dataStoreStrategy = new BaseActions<TEntity>(db);
    }

    public void Add(TEntity entity, bool SaveChanges = true)
    {
        this._dataStoreStrategy.Add(entity, SaveChanges);
    }

    public async Task AddAsync(TEntity entity, bool SaveChanges = true)
    {
       await this._dataStoreStrategy.AddAsync(entity, SaveChanges);
    }

    public void AddRange(IEnumerable<TEntity> entities, bool SaveChanges = true)
    {
        this._dataStoreStrategy.AddRange(entities, SaveChanges);
    }

    public async Task AddRangeAsync(IEnumerable<TEntity> entities, bool SaveChanges = true)
    {
       await this._dataStoreStrategy.AddRangeAsync(entities, SaveChanges);
    }

    public TEntity FindById(object Id)
    {
       return this._dataStoreStrategy.FindById(Id);
    }

    public async Task<TEntity> FindByIdAsync(object Id)
    {
       return await _dataStoreStrategy.FindByIdAsync(Id);
    }

    public IQueryable<TEntity> FindWithCondition(Expression<Func<TEntity, bool>> filter = null, Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null, string includeProperties = "")
    {
        return this._dataStoreStrategy.FindWithCondition(filter,orderBy,includeProperties);
    }

    public TEntity First(Expression<Func<TEntity, bool>> where)
    {

        return this._dataStoreStrategy.First(where);

    }

    public Task<TEntity> FirstAsync(Expression<Func<TEntity, bool>> where)
    {
        return this._dataStoreStrategy.FirstAsync(where);
    }

    public IQueryable<TEntity> GetList()
    {
        return this._dataStoreStrategy.GetList();
    }

    //public T Last(Expression<Func<T, bool>> where)
    //{
    //    return this._dataStoreStrategy.Last(where);
    //}

    public void Remove(TEntity entity, bool SaveChanges = true)
    {
        this._dataStoreStrategy.Remove(entity, SaveChanges);
    }

    public async Task RemoveAsync(TEntity entity, bool SaveChanges = true)
    {
       await this.RemoveAsync(entity,SaveChanges);
    }

    public void RemoveRange(IEnumerable<TEntity> entities, bool SaveChanges = true)
    {
        this._dataStoreStrategy.RemoveRange(entities, SaveChanges);
    }

    public async Task RemoveRangeAsync(IEnumerable<TEntity> entities, bool SaveChanges = true)
    {
       await this._dataStoreStrategy.RemoveRangeAsync(entities, SaveChanges);
    }

    public void Save()
    {

        this._dataStoreStrategy.Save();
    }

    public async Task SaveAsync()
    {
       await this._dataStoreStrategy.SaveAsync();
    }

    public TEntity Single(Expression<Func<TEntity, bool>> where)
    {
       return this._dataStoreStrategy.Single(where);
    }

    public async Task<TEntity> SingleAsync(Expression<Func<TEntity, bool>> where)
    {
        return await this._dataStoreStrategy.SingleAsync(where);
    }

    public void Update(TEntity entity, bool SaveChanges = true)
    {
        this._dataStoreStrategy.Update(entity, SaveChanges);
    }

    public async Task UpdateAsync(TEntity entity, bool SaveChanges = true)
    {
      await  this._dataStoreStrategy.UpdateAsync(entity, SaveChanges);
    }
    internal CaliberMatrixEntities ctx { get { return _dataStoreStrategy.ctx as CaliberMatrixEntities; } }
    public virtual IQueryable<TEntity> GetAll() { return null; }
    public virtual TEntity Get(long id) { return null; }
    public virtual void Delete(long id) { }
    public virtual void Change(TEntity t, Guid by) { }
    public virtual void Add(TEntity t, Guid by) { }
    public virtual void AddRange(List<TEntity> t) { }
    public virtual void DeleteRange(List<int> t) { }
}

Why the while loop is not working in this code?

I want to print the following pattern but the while loop for length is not running. When i run the code it only prints one triangle Below the code there is expected output and actual output :

height = int(input("Enter height ? "))
length = int(input("Enter length ? "))
spaces  = height-1
spaces2 = 0
while length > 0:
    for n in range(height):
        for i in range(spaces):
            print(' ',end="")
        print('/',end="")
        for j in range(spaces2):
            print(' ',end="")
        print('\\',end="")
        for i in range(spaces):
            print(' ', end="")
        print('')
        height-=1
        spaces-=1
        spaces2+=2
    length-=1

Expected Output :

height = 5 length = 3

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




Output when the code ran :

height = 5
length = 3

    /\           
   /  \          
  /    \       
 /      \   
/        \

Which pattern is implemented by attached property in WPF?

In WPF, when we require extra behavior we generally implement attached property. Can any one tell which pattern its implemented?

Design Pattern to easily switch between local JSON and http call - Angular

I am working on implementing a design where a developer can easily switch between a local JSON file or its corresponding API.

Scenario :

  1. We have https://jsonplaceholder.typicode.com/todos/1 with corresponding json as user1.json.

  2. We have https://reqres.in/api/users/2 with user2.json

I have created a config.json which has a mapping :

[
  {
    "url":"https://jsonplaceholder.typicode.com/todos/1",
    "json" : "/assets/user1.json",
    "local": true
  },
  {
    "url": "https://reqres.in/api/users/2",
    "json" : "assets/user2.json",
    "local": false
  }
]

Now, if you toggle local property of each object, you can see that it toggles between local JSON and REST API calls.

I would really like to get some feedback on my implementation and get to know about potential problems which I might face(if any) in future with this design

Here is the implementation which I have thought about

Poker game loop , what is the appropriate approach?

I am trying to create a test environment for my algorithm(Poker AI and using Java). State transitions really boggles my mind. This is not something like "init()-update()-draw()-repeat" cycle , or i can't simplify like that.Basically my pseudo code will be something like this:

Create players deck etc etc
Load/Create AI memory from file

Loop 1)Play 100000 hand or 100 games (example)
Loop 2))Game_Loop (unless one of players gone bankrupt)
Loop 3)))Hand_Loop (unless terminal state)
      )))pre-flop(deal cards)
      )))betting state (players can fold therefore hand will be over)
      )))flop
      )))betting state (same logic applies)
      ))).....
      ))).....
      )))showdown (this is where we reach end game, whoever has better hand
         wins)
      )))for the sake of example lets say we reach 'p1_won' state 
      )))anytime you reach a terminal state update value-regret by 
         backtracking visited state-action pairs.



Thing is, i need to also implement a GUI for this. I am trying to find a way to implement all this states? So i can both render , update without a problem and get the required action with communicating with my algorithm at betting round.

States and Transitions Illustrated: https://imgur.com/a/VSd58vE

lundi 22 avril 2019

Extending (alternative to) the repository desing pattern?

I am working on a project in ASP.NET MVC. I want to create an abstraction layer between the data access layer and the business logic layer of an application. I have been working with Repository and Unit of work. To review, in this pattern a general repository and a number of specific repositories is being created. The problem I have faced in this project is that I need method of some specific repository in another repository. For example, I have a Product and Subproduct repository. I want to use Subproduct methods inside Product methods instead of rewriting LINQ Queries for Subproduct every time. Is there any way to extend the functionaltiy of repository design pattern, or I have to use another design pattern?

-Design Problem--How to externalize Map of objects

I have to get few objects of classes based on the key so i created a Map like below

 Map getObjects(){
    Map objs = HashMap<String, Object>();
    objs.put("model1", new ModelOne());
    objs.put("model2", new ModelTwo());
    objs.put("model3", new ModelThree());   
 }

But how to externalized this Map of objects i.e. is there any way to I can do this dynamically using a property file/yml ? If so how ?

Can it be achieved in a functional style using java 8? if so how can it be done.

design pattern like electricity switch?

I'm coding in c# and currently implementing an "electricity switch" like component.

General idea is there are a bunch of classes implementing a ISwitch interface, and when one is false it basically triggers an Off() action and when all are true then On().

Idea is pretty clear and I'm pretty sure there is a design pattern for such behavior / functionality, would appreciate a reference to documentation so I can educate myself and look at best practices,

cheers

Why State Design Pattern over If-else

Every where I find people saying it is better to use state design pattern over if else , I want to know how :

  1. It is an improvement to if-else in real world use case ?
  2. Does it make code more testable ?

can any one please provide an example where state pattern actually improves the case, it is difficult to make sense of why i shall take the overhead of following state pattern when i can use if-else.

Examples over the internet is not enough to show how this pattern solves the real world problem or makes code more maintainable.

Entity Framework Core use Guid as PK

Should I use Guid as PK in every table?

I'm not experienced in using EF Core or EF. Most of the time when searching for patterns I can find something like this

public class BaseEntity
{
    public Guid Id { get; private set; }
    public DateTime CreatedAt { get; private set; }
    public DateTime ModifiedAt { get; private set; }

    public EntityBase()
    {
        Id = Guid.NewGuid();
        CreatedAt = DateTime.UtcNow;
        ModifiedAt = DateTime.UtcNow;
    }
}

where Guid is used as PK and other entities extend this base class. That should be well known pattern.

But what I'm wondering is if it's good idea to use Guid instead of long or int in every table as PK and if does, should I use Guid also as Foreign Key or should?

Another question in case that above question is true is if in many-to-many relation, joining entity should extend the base entity.

Please, feel free to correct my question grammatically.

Design pattern for handling frequent logic changes in extending classes

I have a processor class - AbstractProcessor and multiple concrete classes (that extend this base class) which get called in order of the business logic.

public Abstract class AbstractProcessor {
   public void doProcess(){}
}

The logic in my concrete classes keeps on changing depending on the business requirements. This leads to a change in the corresponding test classes and seems to be a tightly coupled approach.

Is there a better way to design such classes.

Entity Framework Core Fluent API/Annotations

Which is better to use?

I don't have much experience with EF or EF Core patterns. When I'm reading articles about Entity Framework some peoples are using annotations for annotating PKs, FKs, Generated values, etc. and other people (I think more common case) are using Fluent API for same purpose.

What I'm interested in is that if there is any significant difference between this two approaches.

Main questions are:

  • Can I do more with Fluent API or vice versa?

  • Is it just question of preference or it depends on project type or size?

  • Is it good idea to combine those two approaches in some way?

  • Should I avoid using annotations?

I know there is no just one answer for those questions but I wonder what is opinion of experienced developers.

Currently i intend to use this pattern for entity configuration: source

Please, feel free to correct my question grammatically.

How to make stainless steel plaques?

If you want to make wall plaques on your own, use cardboard, wood etc. You can take any idea like creating a metal looking wall plaque or give it a finishing of bronze plaque. If you want to buy stainless steel plaques, contact us. https://arkramos.com/gallery/

how to make my jhipster entity with one field(singleton style)

I made an entity for my project that holds some system configurations, and want this entity to have only one field i'm thinking that a singleton style would be great but i don't know how i can add it exactly and where since i'm new to jhipster and spring world

i think that if i edit the file 'configuration.model.ts' ( i mean editing the constructor it might work but i'm still not sure if that's it, here is the constructor.

constructor( public id?: number, public letter?: string, )

i'm expecting to have an entity with one field where i can't add more than it and it shows a message in case of someone tried to add a new field to the entity

dimanche 21 avril 2019

How to use two-way adapter and pluggable adapters in Java?

Recently, I have read the "GOF" book. In adapter chapter, the book mentioned Pluggable adapters, I read the chapter over and over, but I can't understand it because of its example in Smalltalk. What's more, it also mentioned the two-way adapter which I have ever met several times, but no books gave me an example code. I don't know whether my understanding is right. This is my code:

public interface Hero {
    void save();
}

public interface Evil {
    void destory();
}

public class Adapter implements Hero, Evil {
    private Hero hero;
    private Evil evil;

    public Adapter(Hero hero) {
        this.hero = hero;
    }

    public Adapter(Evil evil) {
        this.evil = evil;
    }

    @Override
    public void destory() {
        hero.save();
    }

    @Override
    public void save() {
        evil.destory();
    }
}

In conclusion, what's I want to know is whether my code is right or not and how to use a Pluggable adapter in Java. Anyway, Your answer will be welcome all the time.

design pattern selection for workers

main goal is to use maximum number of design patterns :)

exist some entrypoint worker script which accept 2 params

1) "start" or "check" if working

2) worker name

#entrypoint start HelloWorld
#entrypoint check HelloWorld

script can check if worker running in different ways so for this part i could use Strategy pattern

workers can do different jobs, so for this part i could use Factory Method

what kind of pattern could be used to select which action should be used "start" or "check"

what other patterns you could imagine for such a task

What is the best strategy to commit the changes using the UnitOfWork pattern?

What is the best strategy to commit the changes using the UnitOfWork pattern? Doing it inside a try-catch? If I need to rollback , the catch is the best place to do it in that case?

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

public void Rollback() {
            _context
                .ChangeTracker
                .Entries()
                .Where(entry => entry.State != EntityState.Unchanged)
                .ToList()
                .ForEach(entry => {
                    switch (entry.State)
                    {
                        // Under the covers, changing the state of an entity from  
                        // Modified to Unchanged first sets the values of all  
                        // properties to the original values that were read from  
                        // the database when it was queried, and then marks the  
                        // entity as Unchanged. This will also reject changes to  
                        // FK relationships since the original value of the FK  
                        // will be restored. 
                        case EntityState.Modified:
                            entry.State = EntityState.Unchanged;
                            break;
                        case EntityState.Added:
                            entry.State = EntityState.Detached;
                            break;
                        // If the EntityState is the Deleted, reload the date from the database.   
                        case EntityState.Deleted:
                            entry.Reload();
                            break;
                        default: break;
                    }
                });
}

try { 
  UnitOfWorkRPOMain.Commit();
}
  catch (Exception ex) {
  UnitOfWorkRPOMain.Rollback();
  Logger.Error(baseLog + "Error - ex.Message).");
}

How to associate a popup menu item with its functionality

I'm developing a JDBC application, using Java Swing to build the GUI. Once in a window, there are some items which reply to clicking by showing a popup menu with several items. Now I'm facing a design problem, since I don't want to write redundant code or create similar classes. Therefore, I would like to have only one class for the PopUpMenu, and other for its items. My approach then is encapsulating the actions that can be performed by the menu items (maybe classes with an operation Execute() implementing an interface IPopMenuItem), but now I face the problem of linking that functionality to the one provided by the different windows (and those can be of different types), because I can't define a common interface for every one of them... How can I solve this?

Which design pattern is to use in below scenario?

I got this question in my interview- "There are two data source. First one is database system and another one is File System.Client code will only provide id whose data it needs to see and nothing else. The client logic doesn't need to know from where its getting the data for a particular id.Which design pattern should be used in this case?"

My best guess is Abstract Factory design pattern. I will use abstract class which will be inherited by database access class and file access class but I am unable to decipher how Client code will get the object of either database class or fileclass to access the file if we do not provide any other input?

Which creational pattern is suitable for the scenario?

Which creational design pattern is suitable for the given example

I am bit confused if it is Factory pattern or Builder pattern

Here is scenario: “A bank offers business accounts to contratct and permanenet employees based on the salary (amount) and designation. It is required to develop a solution in odrer to choose the value added features of an account (i.e. Gold account, Silver account) offerred to the employees. The features options that a user can choose are as follows: • Digi Vallet • Free SMS • Free Internet Banking • 10% profit on amount exceeding Rs. 500,000 • …”

Studied Patterns are: Factory, abstract factory, builder, & prototype. For me prototype is been eliminated from the options as there isn't ant cloning of object required. It says, "the bank is offering business account" so probably we should use factory. Please discuss.

samedi 20 avril 2019

How to return whole non-latin strings matching a reduplication pattern, such as AAB or ABB

I am working with strings of non-latin characters. I want to match strings with reduplication patterns, such as AAB, ABB, ABAB, etc. I tried out the following code:

import re

patternAAB = re.compile(r'\b(\w)\1\w\b')
match = patternAAB.findall(rawtext)
print(match) 

However, it reurns only the first characters of the matched string. I know this happens because of the capturing parenthesis around the first \w.

I tried to add capturing parenthesis around the whole matched block, but Pyhton gives

error: cannot refer to an open group at position 7

I also found this method,but didn't work for me:

patternAAB = re.compile(r'\b(\w)\1\w\b')
match = patternAAB.search(rawtext)
if match:
    print(match.group(1))

How could I match the pattern and return the whole matching string?

# Ex. 哈哈笑 
# string matches AAB pattern so my code returns 哈 
# but not the entire string

What is a clean comments composition on data observations design pattern?

I am working on a data analysis system that looks over a set of data then writes some basic observations on the data based on some preset rules. For example, consider columns a to e, output would have to be like column comment:

a b c d e comment
1 2 5 8 9 'observation 1, observation 3 and observation 4'

This algorithm can easily be done with tones of if statements, for example:

def get_comments(row)
 comments_bag = []
 if row[1] > 0:
   comments_bag.append('observation 1')
 if (row[1]+row[4] + 7) > 0:
   comments_bag.append('some other observation 1')
 ...
 return comments_bag

However, as in the future, more comments will have to be implemented depending on multiple variable checks, updating the code will be a pain in the neck. Therefore, I am looking for a design pattern, algorithm that can solve my problem and be easy to update in the future. Moreover, the comments will also have to follow some logical order. For now, the only solution I have is a comment to validation dictionary as so:

is_observation_1 = True if row[1]> 0 else False
is_observation_2 = True if if (row[1]+row[4] + 7) > 0 else False

comments_dict = { 'observation 1': is_observation_1
                  'observation 2': is_observation_2
                  'observation 3': is_observation_3
...
                  'some observation': is_observation_some
}

return keys where values are True from comments_dict

I was also thinking of implementing the composite pattern, however I think that might be an overkill for my problem. I was also thinking of a decision tree type of pattern.

Template design pattern - how to "share" implementations?

Working on a project so I'll try to generalize this.

Say I have an abstract class A with an abstract method method().

There are 4 subclasses of A: B, C, D, and E, but B and C have the same exact implementation of method(), and D and E have the same exact implementation of method(). How can I organize the code in such a way that minimizes duplicate code?

Is this "legal" microservices design?

Setup:

  • Within the whole system, there is a concept of a list of items for each customer and this needs to a concept understood by multiple services A, B, C.
  • Those same multiple services perform distinct type of work that operates on that list of items.
  • It's ok if B or C is operating on a version of the list of items that is not up-to-date, so long as they eventually get the latest version.

My design:

  • One service A is the source of truth for the current state of the list of items. The list is manipulated in this service.
  • When the list changes, A publishes the list and B and C, subscribers to this event, store copies of it in their own storage.
  • When B and C do their work, they use their local copy of the list.
  • B and C also have additional state specific to their domain.

My rationale:

Since B and C don't ask A for the list when they do their work, they are not dependent on A. If for some reason A goes down, the impact to the system is only that B and C don't have up-to-date information, which is acceptable, and which will be mitigated when A is fixed.

Is there anything wrong with this?

How to remove decorated object from Decorator Pattern?

How could I remove items that have been added using the decorator design pattern? For example Pizza Ordering System. I want to be able delete some items and decrease price.

public interface Pizza {
    double getPrice();
}
public class SimplePizza implements Pizza {

    @Override
    public double getPrice() {
        return 25;
    }
}
public abstract class PizzaDecorator implements Pizza {
   Pizza tempPizza;
   public PizzaDecorator(Pizza a){
       tempPizza = a;
   }
   @Override
   public double getPrice(){
       return tempPizza.getPrice();
   }
}
public class Mushroom extends PizzaDecorator {
    public Mushroom(Pizza newPizza){
        super(newPizza);
    }
    public double getPrice(){
        return tempPizza.getPrice() + 10;
    }
}

vendredi 19 avril 2019

Is this design posible with bootstrap?

I dont know how to make this design using bootstrap. Already tried using col and rows, combining them but never reached a solutionenter image description here

[Here's exactly what i want in bootstrap]

Passing data on events between classes in C++

I'm trying to write voice communicator in C++ as a school project. So far I've written two classes - one to record sound (Recorder) and one to play it (Player). At this point Recorder writes to file, which I later pass to Player. But now I would like to try to get it to work in real time. Inside Recorder there is loop that repeatedly reads 480 bytes of audio from sound card. Now each time audio data is ready I would like to send it to Player class to play it. Player just adds that data to sound card buffer, so it's as easy as calling playerObject.play(char* buffer, int bufferSize). I don't want to put one class inside another. How can I pass that data between them? Or call function of Player inside Recorder? (Later I will write Encoder and Decoder and will need to pass data between all those classes)

class Recorder {
    void play(char* audioData, int audioSize)
    {
        sendAudioToSoundCard(audioData, audioSize)
    }
};

class Player {
    void record()
    {
        const int dataSize = 480;
        char buffer[dataSize]
        while (1)
        {
            readAudioFromSoundCard(buffer, dataSize);
            sendAudioToPlay(buffer, dataSize); // how do I make this call play from Recorder? 
        }
    }
}