samedi 31 août 2019

What is the idiomatic way of handling "ephemeral" state in a database?

I know that "best practices" type of questions are frowned upon in the StackOverflow community, but I am not sure how else to word this.

My "big picture" question is this:

What is a good practice when it comes to handling "session" state in a stateless server (like one that provides a REST api)?

Quick details

Using nodeJS on backend, MongoDB for database.

Example 1: Login state

In version 1 of the admin panel, I had a simple login that asks for an email and password. If the credentials are correct, user is returned a token, otherwise an error.

In version 2, I added a two-factor authentication for users who activate it. Deciding to keep things simple, I have now two endpoints. The flow is this:

  • /admin/verifyPassword:
Receive email and password;
if(Credentials are correct) {
  if(Admin requires 2fa) {
    return {nextStep: 2fa};
  } else {
    return tokenCode;
  }
} else {
  return error;
}

  • /admin/verifyTotpToken:
Receive email and TOTP token;
Get admin with corresponding email
if(Admin has verified password) {
  return tokenCode
} else {
  return error;
}

At the verifyTotpToken step, it needs to know if the admin has already verified password. To do that I decided to attach a 'temporary' field to the Admin document called hasVerifiedPassword which gets set to true in verifyPassword step.

Not only that, but I also set a passwordVerificationExpirationDate temporary field in the verifyPassword endpoint so that they have a short window within which they must complete the whole login process.

The problem with my approach is that:

  • It bloats the admin document with ephemeral, temporary state that has nothing to do with an admin itself. In my mind, resource and session are two separate things.
  • It gives way for stale data to stay alive and attached to the admin document, which at best is a slight nuisance when looking through the admin collection in a database explorer, and at worst can lead to hard to detect bugs because the garbage data is not properly cleaned.

Example 2: 2FA activation confirmation by email

When an admin decides to activate 2fa, for security purposes, I first send them an email to confirm that it is truly them (and not someone who hijacked their session) who wanted to activate 2fa. To do that I need to pass in a hash of someway and store it in the database.

My current approach is this:

1) I generate a hash on the server side, store it in their admin document as well as an expiration date.

2) I generate a url containing the hash as a query parameter and send it in the email.

3) The admin clicks on the email

4) The frontend code picks up the hash from the query parameter and asks the server to verify it

5) The server looks up the admin document and checks for a hash match. If it does, great. Return ok and clean up the data. If not, return an error. If expired, clean up the data.

Here also, I had to use some temporary state (the two fields hash and expirationDate). It is also fragile for the same problems mentioned above.

My main point

Through these two examples I tried to illustrate the problem I am facing. Although these solutions are working "fine", I am curious about what better programmers think of my approaches and if there is a better, more idiomatic way of doing this.

Please keep in mind that the purpose of my question is not a get a specific solution to my specific problem. I am looking for advice for the more general problem of storing session data in a clever, maintainable, way that does not mix resource state and ephemeral state.

vendredi 30 août 2019

Why Proxy pattern is categorized in Structural pattern?

According to Structural Patterns, they focus on how classes and objects are composed to form larger structures.

Adapter and Decorator fit this definition. But for proxy it's just an interaction between the subject and the real object, it's not combining the anything to give a new object. Shouldn't it be categorized as behavioral Pattern?

I have read different Post and also related StackOverflow Question like Why is proxy pattern Structural Pattern and why is State Pattern behavioral pattern? and Why decorator is a structural and not behavioral design pattern?

But none answer the Question.

Which is best tag Div or Table?

Which is the best tag Div or Table?

Which is the best tag Div or Table for design and also which is best in responsive? I want to make design for the mail template.

Node.js - Avoiding multiple calls to the database

I'm building a REST API using Node.js (express). The project structure is divided into three parts(which is said to be a common architecture for a REST API).

  • Database Layer (code related to database config & querying functions) e.g. `db.fetchUser()`
  • Services (code related to app logic) e.g. `authSerivce.authUser()` & `authService.genAuthToken()`
  • Controllers (code related to a specific route) - Service functions are used here.

authService.authUser() service function calls db.fetchUser(username) which returns
username and password from the database. Then it authenticates the user and returns the authentication result. After that I call authService.genAuthToken(username) to generate an
authentication token and send it to the user. So for user login, I will have to do:

const authResult = authService.authUser(username, password);
if(authResult.failed) return;
const token = authService.genAuthToken(username);

The authService.genAuthToken(username) will have to call db.fetchUser() again (to access name & user role) to generate the proper authentication token.
So I will have "two" database calls because of the project architecture.

How can this issue be solved?

I thought of passing the connection instance to the service functions along with other parameters but that seems wrong too.
The design gets more complex and scattered if I use transactions.

Thanks

Oracle Table design question: configuration table, default values, primary keys

need to design a table in Oracle, these are my columns:

  1. COUNTRY
  2. PRODUCT
  3. PARAM1
  4. PARAM2
  5. PARAM3

My first thought was that I would like the combination of Country and Product to be a PK. But then, I also want a catch-all/Default for anything that doesn't fall into the records for Country + Product. Example:

  • Product A and Country US: have param values as follow 1,1,1
  • Country France for all products: have param values 2,2,2: should I have a record for every possible product? Is it possible to have a record for France and all products?
  • Any other Country & Product combination has params 3,3,3: what's the best way to achieve this without creating a record for every single country and product. Countries are probably not going to change a lot, but I could get new products all the time and I don't want to be updating this table every time this happens

Looks like I should let Product and Country be nullable and not a PK, but I wonder if I'm missing any other options.

Any thoughts would be greatly appreciated.

Cheers!

Class Architecture: Circular Dependency of Inner and Outer Class in Python

My Design

Verbal Description

I have a class Model, of course with some methods on it. Besides that I have a class ModelList whose childclass represents a List of instances of q child class of Model. Amongst other things, the use of ModelList child classes is to provide bulk operations which differ from just delegating the operation to each of the elements of the ModelList. So, the purpose of the ModelList child classes is to "vectorize" methods of the corresponding Model class.

I also use the ModelList in some places where I want to allow either a childclass of Model or ModelList allowed as parameter passed to a function.

ModelList is knowing (and checking) the type that will be accepted for any of its elements. To make the ModelList childclass know its corresponding Model child class, I define this as a class variable element_type on the ModelList child class.

Each ModelList child class is closely coupled to a Model childclass: One ModelList class belongs to one Model class. That's why I put the ModelList child class as an inner classes to their respective Model class. An here comes my problem: Because ModelList needs to know Model and Model needs to know ModelList and both during initialisation of each class, I have a circular dependency between my classes.

Minimum Example

I reduced my code to a Minimum Example to make my design easier understandable:

class Model(ABC):
    pass

class ModelList(list):
    @classmethod
    def __init__(self, elements=None):
        elements = list() if not elements else elements

        for value in elements:
            self._check_type(value)

        list.__init__(self, elements)

    def _check_type(self, val):
        if not isinstance(val, self.__class__.element_type):
            raise TypeError(
            f"{self.__class__} accepts only instances of {self.__class__.element_type} as elements. `{val}` is not!") 

The following leads to the Error free variable 'SomeModel' referenced before assignment in enclosing scope:

class SomeModel(Model):
    class List(ModelList):
        element_type = SomeModel  # this causes the Error

I do not want to decouple

I know I can get rid of the circular dependency by just decoupling the two classes. But I do want both the Model class know its corresponding ModelList class and also I want the ModelList class to know its Model class. Each Model class ought to have one and only one List attached to it.

Is monkey patching appropriate?

I know I can circumvent the dependency by "monkeypatching" my Model child class like this:

class SomeModel(Model):
    pass

class SomeModelList(ModelList):
        element_type = SomeModel

SomeModel.List = SomeModelList

For me it feels like this is a sign of a design flaw. I cannot say why but it feels "wrong".

Questions

  1. Is monkeypatching appropriate here? Or is it indicating a deeper conceptual problem of my design?
  2. Which other solutions are there?
  3. How can I redesign to get rid of this circular dependencny?
  4. Is it possible to evaluate the element_type at some point later when the respective Model childclass is defined?

How can i outsource functions that use state and do setState

I have a class which has many functions, i wish to outsource these functions and put each group of function inside a file of their own and then use them by importing and calling them.
Usually this is very simple, you simply put the function bodies inside another file and then export them, but in my case i use this.state and this.setState, is it still possible to outsource these function? if not, is there a better practice?
Thank you.

jeudi 29 août 2019

Is it an anti-pattern and violate solid principles in this scenario?

I'm new to design patterns, below is my code that let a consumer add journal and save the journal to disk, or upload it to cloud, could you have a check to see if the design is anti-pattern and is there any violations of solid principles

public class Program
{
  static void Main(string[] args)
  {
    Consumer client = new Consumer(new DiskManager("C:\\journal.txt"));
    // consumer add text to Journal
    client.AddJournal("sometext");
    client.SaveJournal();
  }
}

public class Journal
{
  private readonly List<string> entries = new List<string>();

  public void AddEntry(string text)
  {
    entries.Add(text);
  }

  public void RemoveEntry(int index)
  {
    entries.RemoveAt(index);
  }
}

public interface IPersistenceManager
{
  void Save(Journal journal);
}

public class DiskManager : IPersistenceManager
{
  private string filePath;

  public DiskManager(string filePath)
  {
    this.filePath = filePath;
  }

  public void Save(Journal journal)
  {
    //XXX.XXX.Save(filePath);
  }
}

public class CloudManager : IPersistenceManager
{
  private string url;

  public CloudManager(string url)
  {
    this.url = url;
  }

  public void Save(Journal journal)
  {
    //XXX.XXX.Save(url);
  }
}


public class Consumer
{
  private Journal _journal = new Journal();
  private IPersistenceManager _manager;

  public void AddJournal(string note)
  {
    _journal.AddEntry(note);
  }

  public Consumer(IPersistenceManager manager)
  {
    _manager = manager;
  }
  public void SaveJournal()
  {
    _manager.Save(_journal);
  }
}

and I have a question well:

Q1-How can I modify the code so the client can also have an option to save the journal to both disk and cloud?

How single responsibility principle avoid code smell in this scenario?

I'm new to Design Patterns, I know the purpose of single responsibility principle, but not 100% sure how it can avoid lots of tiny changes. Below is my example:

//very crude implementation
public class Journal
{
    private readonly List<string> entries = new List<string>();
    private static int count = 0;

    public void AddEntry(string text)
    {
       entries.Add($"{++count}: {text}");
    }

    public void RemoveEntry(int index)
    {
       entries.RemoveAt(index);
       count--;
    }

    public void SaveToDisk(string filename)
    {
       File.WriteAllText(filename, ToString());
    }
}

I know the SaveToDisk method should not be included in the class, it should be a dedicated class, like PersistenceManager to handle the file saving.

But why can't I keep the SaveToDisk() method in Journal class? if there is any new requirements such as Save the Journal to cloud, then I just add a new method SaveToCloud(), and any dependent client classes can use SaveToCloud(), the only modification I need to make is adding SaveToCloud() in Journal class, which is totally fine?

Problem with design of existing code (initialization of actions to perform)

I have architectural problem with existing code and am looking for a clean-code solution. I cannot show real code, but will show analogy.

Let's suppose that we have a car repair workshop. There are orders which can contain one or any number of actions (from known set) to perform. When worker is free, he execute operations according to current order.

But there's one main limitation: for some reasons Worker must have method PerformRepair( ) (this interface cannot be modified) and all operations should be executed on its call.

Now I have class RepairConfiguration, representing order with boolean values for all possible actions (bool ShouldChangeTyres, bool ShouldChangeEngineOil, bool ShouldRepairBrakes etc.). Worker is initialized with this RepairConfiguration. And when he PerformRepair( ), he checks each boolean and perform action if it's needed.

It look like this:

//cannot be modified
public interface IWorker
{
    void PerformRepair( );
}

//worker implementation and all below CAN be modified
public class Worker : IWorker
{
    RepairConfiguration _repairConfiguration;
    AssignRepairConfiguration( RepairConfiguration config ) { _repairConfiguration = config; }
    PerformRepair( )
    {
        if( _repairConfiguration.ShouldChangeEngineOil )
            ChangeOil( );
        if( _repairConfiguration.ShouldRepairBrakes )
            RepairBrakes( );
        if( _repairConfiguration.ShouldChangeRim || _repairConfiguration.ShouldChangeTyres )
            TakeOffWheels( ); //some preparatory - common for a few actions
        if( _repairConfiguration.ShouldChangeTyres )
            ChangeTyres( );
        if( _repairConfiguration.ShouldChangeRim )
            ChangeRim( );
    //...... other conditions checking and actions
    }
      //implementation of all actions
}

public class RepairConfiguration
{
    bool ShouldChangeTyres;
    bool ShouldChangeEngineOil;
    bool ShouldRepairBrakes;
    bool ShouldChangeRim;
    //...... other bool conditions
}

As you can see, Worker implementation don't look good. There are a lot of IFs. And even if one action should be executed all conditions are checked. It also doesn't follow open/closed principle - when there is new possible action I need modify RepairConfiguration and Worker implementations. I wanted to ask you: how would you implement that? Are there any design patterns which could be helpful?

How can i intercept a component to check for permission

I have lots of static forms which i show the user when he clicks on the main menu and goes to a specific route, what i want to do now is to check when going to a route if that component has permission to be visited, i can do this by doing a simple post to server but i am confused and i don't know where should be the place to do this check or post.
Here are some of the solutions i thought of:
1- Writing a Higher order component and wrapping each static component with it
2- creating a base class and making each static form to inherit it while doing this check in the parent class
3- Or maybe using the routes as a solution since i am using the react-router ?
I will appreciate any help or tips. Thanks.

What's the benefit of using a template method in the wikipedia example for Factory Method pattern?

The Wikipedia article about factory method pattern

contains this example:

/* Almost same as Factory, just an additional exposure to do something with the created method */
public abstract class ProductAbstractFactory
{
    protected abstract IProduct MakeProduct();

    public IProduct GetObject() // Implementation of Factory Method.
    {
        return this.MakeProduct();
    }
}

public class PhoneConcreteFactory : ProductAbstractFactory
{
    protected override IProduct MakeProduct()
    {
        IProduct product = new Phone();
        //Do something with the object after you get the object. 
        product.SetPrice(20.30);
        return product;
    }
}

where the template method pattern is used too (GetObject calls abstract MakeProduct). In this (specific) case, I wouldn't to it that way, because the template method doesn't contain any "surrounding" code and making GetObject abstract with overrides in derived classes would be sufficient.

Do I oversee something here? Or I'm right with the assumption, that this example is not as simple as possible as it could be for the demonstration?

How to add views inside the edittext in android?

I need to add two views in an edit text like in the screenshot

    <EditText android:id="@+id/id_search_EditText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:singleLine="true"
        android:paddingRight="40dp"
        android:hint="Enter your feelings and connect" />

    <Cardview 
        android:id="@+id/id_search_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/id_search_EditText"
        android:layout_alignBottom="@+id/id_search_EditText"
        android:layout_alignRight="@+id/id_search_EditText"
        android:background="@drawable/ic_shared"/>

</RelativeLayout>

This is what I tried...

Which companies do use backend for frontend(BFF) to solve which problem they faced specifically?

I am new to BFF pattern. I did my research and understood well.

  1. I would like to know what are the famous companies did incorporate BFF in their application architecture and what problem they solved with it? ex: Netflix, but I'm not sure which problem exactly they solved using BFF. BFF will give many benefits. So it can be used to solve many problems, that's why I want to be sure about the problem they solved with it. I expect at least you discuss about 3 companies.

  2. Can GraphQL completely replace BFF?

Inheritance: Unable to access method from base class

I am implementing CQRS pattern. To use CQRS pattern in my project I wrote three commands, they are

public class DogCommand : PetCommand
{
    public DogCommand(){}
    public override string Name{get; set;}
}

public class CatCommand : PetCommand
{
    public CatCommand(){}
    public override string Name{get; set;}
}

public abstract class PetCommand : ICommand
{
    public PetCommand(){}
    public virtual string Name{get; set;}
}

public interface ICommand
{
   //Bussiness logic
 }

Here I have interface called ICommand. PetCommand is base class which is implementing this interface. Derived class DogCommand and CatCommand are inheriting PetCommand.

I also wrote base command handler, as below

public abstract class BaseCommandHandler<T> : CommandHandler<T> where T : ICommand
{
    protected BaseCommandHandler(string type, string name): base(type, name)
    {

    }
}
public abstract class CommandHandler<T> : ICommandHandler<T> where T : ICommand
{
   protected CommandHandler(string type, string name)
   {
    //Business logic
   }

   protected void LogWrite(string msg)
   {
      //Writing log 
   }
}


public interface ICommandHandler<in T> where T : ICommand
{
    void Run(T command));
}

All functions present in BaseCommandHandler, I will use in each derived command handler

Now problem is in derived class command handler

public class PetCommandHandler : BaseCommandHandler<DogCommand>, ICommandHandler<CatCommand> 
{

    public void Run(DogCommand dCommand)
    {
        this.LogWrite(dCommand)      
    }

    public void Run(CatCommand cCommand)
    {
       **//Want to access this.LogWrite() with cCommand. How can I do that?**          
    }
}

Here I am unable to access this.LogWrite() function for cCommand, because PetCommandHandler is inheriting first BaseCommandHandler and then implementing ICommandHandle.

How to access this.LogWrite() function for cCommand?

Here is compile time error:

cannot convert from ‘Command.DogCommand’ to ‘Command.CatCommand’

How to print the following pattern

I would like to know how would one print this pattern out. Preferrably in C++ This program takes in only the number of rows as input and then prints the output as shown in the Example.

Input : 3
Output :
 1*2*3
 7*8*9
 4*5*6

Input : 4
Output :
 1*2*3*4
 9*10*11*12
 13*14*15*16
 5*6*7*8

Access factory which return baseClass* , from the baseClass Function itself

I have a scenario where I need to call a factory which returns baseClass * from a function of baseClass itself

I have a function() which is common for all the child class. So I decided to define that function in base class, and the derived class then can inherit from it. Now in that function we need to call a factory which returns the BaseClass*.

class BaseClass{
public:
virtual bool someFunc(){
  baseClass *var = Factory::GetObject(1);
  // do some processing on var
}
};

class ChildClass1: public BaseClass{
 ... some other functions
};

class Factory{  //factory
  public:
    static BaseClass * GetObject(int iter){
     if(iter==1){
      return ChildClass1;
     }
     else if(iter==2){
      return ChildClass1;
     }
     ....
    }
};

Understanding what would be the best design. Thanks in advance :)

mercredi 28 août 2019

Javascript: When passing data from socket communication server to client

I'm currently creating a crawler. I'm crawling, writing a file locally as a stream, reloading the file, and uploading it to s3. I am using socket communication with socket.io to create and use the UI. I want to send a data object from the server to the client after it is uploaded to s3. But this process is not solved, so ask.

Below is the code. The file is divided into three.

// models/**.js

(...)
await uploadFile(filename)

Here is the part that crawls, saves the file as a stream, and then calls s3.js.

// s3.js

(...)
const uploadFile = async filename => {
    await fs.readFile(join(__dirname, output, filename), (err, data) => {
        s3Upload(filename, data)
    })
}

const s3Upload = async (filename, data) => {
    await s3.upload({
        Bucket: 'work543-express-crawler',
        Key: filename,
        Body: data,
        ContentEncoding: 'utf-8',
        ACL: 'public-read-write'
    }, (err, data) => data ) // <-- this line
}

I need to send data to socket.emit() in the callback of s3.upload() but I am not sure how to do it.

// socketIo.js

(...)
const socketServer = app => {
    const socketio = require('socket.io')(app)
    socketio.on('connection', socket => {
        socket.on('append', async data => {
            queue(data)
        })
        socket.emit(someEventName, theData) // <-- this line is pseudo code
    })
}

I am thinking below how to do data in socket.emit():

  1. It seems that data, the callback argument of s3.upload(), should be exported.
  2. Or some event should occur that connects socket.emit() and s3.upload().

I would like to know if you are thinking in this direction. If yes, please give me a guide on how to fix it.

Thank you.

ps. If you can't figure it out with just the code above, please comment.

Is NOT using base implementation on a subclass considered 'Refused Bequest'?

I understand that overriding a method and leaving the implementation blank is a refused bequest, but how about when you override a method and don't use the base implementation? Is this considered refused bequest as well?

Example:

public class Car
{
    virtual void Drive()
    {
        // Some kind of drive logic
    }
}

public class Hummer : Car
{
    override void Drive()
    {
        // base.Drive(); - Base drive implementation refused!
        // Some other kind of driving logic
    }
}

Is the following what should be considered acceptable?

public class Hummer : Car
{
    override void Drive()
    {
        // base.Jump(); 
        // Some ADDITIONAL drive logic
    }
}

Can i use class instead of interface in composite design pattern?

I'm writing a program that's going to visualize compound products with input materials which can also be compound products.

Interface: [Product]

Compound item: [CompoundProduct : Product]

Leaf: [Material : Product]

I'm going to visualize the products and materials in TreeView using TreeViewItems, thus i want both the Material and CompoundProduct to include a TreeViewItem object. For this, i want my Product interface to contain a variable, which it can't since it's only an interface.

Is there any reason why i can only find composite design pattern examples with interface implementations? Does it look ugly to use the pattern with class instead of interface?

how can i implement singleton pattern on this project, to get the data base connection?

I have this example of Singleton pattern implementation :

public class Singleton {
    //singleInstance
    private static Singleton unicaInstancia = new Singleton();

    //nadie puede crear mi clase con el constructor en privado/
    private Singleton(){
        System.out.println("no one can create my class"
                + " with the builder/constructor in private");
    }
    //punto de acceso global
    //global access point
    public static Singleton getInstance(){
        return unicaInstancia;
    }



}
 //clase de prueba/ TestClass
class test{
    public static void main(String[] args){
        Singleton sgtn1 = Singleton.getInstance();
        Singleton sgtn2 = Singleton.getInstance();
        print("s1", sgtn1);
        print("s2", sgtn2);
    }

    static void print(String name, Singleton object){
        System.out.println(String.format("Object : %s, Hashcode: %d",name,object.hashCode()));
    }
}

this is my project structure :

enter image description here

this is the class I want to get single instance:

public class UConnection {

    private static Connection con = null;


   public static Connection getConnection(){
        try{
            if(con == null){
                Runtime.getRuntime().addShutdownHook(new MiShDwnHook());
                ResourceBundle rb = ResourceBundle.getBundle("backEnd.jdbc");
                String driver = rb.getString("driver");
                String url = rb.getString("url");
                String pwd = rb.getString("pwd");
                String usr = rb.getString("usr");

                Class.forName(driver);
                con = DriverManager.getConnection(url, usr, pwd);
            }
            return con;
        }catch(Exception ex){
            ex.printStackTrace();
            throw new RuntimeException("Error al crear la conexion", ex);
        }
    }
}

class MiShDwnHook extends Thread {

    public MiShDwnHook() {
    }

    @Override
    public void run(){
        try{
            Connection con = UConnection.getConnection();
            con.close();
        }catch(Exception ex){
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }
}

then my question is how can I do to get a single instance of my connection to the database in the backEnd package and as I can check it, I would like to know if someone can answer this question, previously I thought of coding everything in the builder but that doesn't look good to me, that's the only way to implement the singleton and make it work ? , I need help please, thank you

Amazon Interview Question - OO Design - LLD

Given you have different types of Phones - WinPhone, AndroidPhone, iPhone, TouchscreenPhone, and KeyPhone. Add behavior to implement NoSim() which will put the phone in NONUSABLE state. Also add TouchScreenDamaged() behavior which will put the phone in NONUSABLE state. Help me design the object model and explain the object relationships.

Came up with this object relationship. Suggestions would be appreciated enter image description here

how do I keep segregated location data into one place

I have regions and every region has 5 locations. currently we have an application which is pushing and pulling data on the logged in user branch on which user has permission. Every location is maintaining its own database where application is centralized.

My requirement is that a query module can retrieve information from any location within region so i dont understand how to do that. should I consolidate the transactions from all locations into one database or what. Need guidance from design perspective.

What is the correct way of structuring this block of repetitive code?

In my job my colleague and I spend a lot of time automating SAP processes through the SAP GUI. This involves a lot of repetitive code with almost no difference between the lines. This code is impossible or pointless to unit test, and I believe that it should not be in the code itself but in a separate XML/other storage file.

One issue that my colleague raised was that storing this as XML would make it a bit tedious to work with this code. He prefers that we keep these interactions inside the code and that moving it outside would introduce unnecessary complexity. I can understand his point but it just doesn't look right to me.

'basic example 
 Public Sub TCODE()
        setText("TXT1","00000")
        press("BTN1")
        setText("TXT2","99999")
        setText("TXT3","Desc")
        setText("TXT4","B")
        setText("TXT5","A")
        press("BTN2")
        press("BTN3")
        press("BTN4")
        .....more of the same....
End Sub

I would like somehow to take these repetitive actions out of the code and into a separate file. This would allow the code to keep the logical functionality, and the all these routine instructions would be stored separately. This would separate issues with the code from issues with instructions list.

Are there any better solutions to this problem than these two? If someone could help identify pros and cons of each approach and/or suggest improvements I would appreciate that a lot. Both of us are junior software developers and haven't dealt with issues like these previously.

mardi 27 août 2019

Add a layer of mapping on a child class

I am trying to write a class that works as a type of map. The children of this class have layers of mapping on top of basic functionality. Something like the below:

public interface MyMap<K, V> {
  public V get(K key);
}

public interface Client<K, V> {
  public V fetch(K key);
}

public class ComplexKey<T> {

  private T _key;

  public ComplexKey(T key) {
    _key = key;
  }

  T getKey() {
    return _key;
  }
}

public class BasicMyMap<K, V> implements MyMap<K, V> {

  private final Client<K, V> _client;

  public BasicMyMap(Client<K, V> client) {
    _client = client;
  }
  @Override
  public V get(K key) {
    return _client.fetch(key);
  }
}

/**
 *
 * @param <MK> mapped key
 * @param <K> key
 * @param <V> value
 */
public class ComplexKeyMyMap<MK extends ComplexKey, K, V> implements BasicMyMap<MK, V> {

  private Function<K, MK> _mapper;

  public ComplexKeyMyMap(Client<MK, V> client, Function<K, MK> mapper) {
    super(client);
    _mapper = mapper;
  }

  public V get(K rawKey) {
    return super.get(_mapper.apply(rawKey));
  }
}

public static void main(String[] args) {
  BasicMyMap<String, String> basicMyMap = new BasicMyMap<>(key -> "success");
  assert "success".equals(basicMyMap.get("testing"));

  ComplexKeyMyMap<ComplexKey, String, String> complexKeyMyMap = new ComplexKeyMyMap<>(key -> "success", (Function<Object, ComplexKey>) ComplexKey::new);
  assert "success".equals(complexKeyMyMap.get("testing"));
}

In addition to the key mapping, I would like to add a layer for mapping the value that is returned as well.

So question is:

  1. What is the common approach to this problem? I have encountered this pattern multiple times and have not found a great solution.
  2. How can I achieve this such that the users of these classes can just rely on the MyMap interface definition.

Thanks for the help.

Regex patterns in find module (Ansible)

Basically I'm trying to get a return of filenames (directories, actually) in a server. I only want those files with 3 (and only 3) characters.

I even tried to use the 'exclude' parameter ( excludes: '\S{4,}' ), to make sure it would work. It didn't.

Here's a sample of the code:

  - find:
      paths: /workdir
      file_type: directory
      use_regex: yes
      patterns: '\S{3}'
    register: oea

  - debug:
      msg: ""
    with_items: ""

I expect all files with 3 and only 3 characters, but the actual output is every directory under /workdir.

Am I using the regex pattern the wrong way?

Order of execution in Command pattern

I have a fairly basic implementation of a command pattern, along these lines:

    interface IProcessor
    {
        bool CanProcess(string input);
        void Process(string input);
    }

    class ProcessorA : IProcessor
    {
        public bool CanProcess(string input)
        {
            return true;
        }

        public void Process(string input)
        {
            // do things
        }
    }
// and other implementations, ProcessorB, ..C, etc.

Processors will get injected with DI and I'll have a loop that finds a valid processor and executes it, something along these lines:

foreach (var processor in processors)
{
    if (processor.CanProcess("abc"))
    {
        processor.Process("abc");
    }
}

So far so good, except that one of these processors is a fall-through processor which needs to be executed when all other processors have declared that they can't process - basically I have to ensure it is executed last because it can process anything. The problem is that this is an unordered list, so I need to figure out how to make fall-through processor execute last.

I see a few ways:

  • Make a pass-through processor a special case, make it implement a specific interface and explicitly call it when all other processors were exhausted. This adds a check after the loop and an extra interface (IPassThruProcessor) for DI.
  • Add a marker property on IProcessor interface and sort processors prior to the loop:

interface IProcessor { bool CanProcess(string input); void Process(string input); bool IsPassThru { get; set; } // new prop }

var processors = processors.OrderBy(x => x.IsPassThru).ToArray(); 
// IsPassThru = true goes to the back of the queue

// loop over processors

I don't really like either of these ways, first - because it introduces special cases and special interfaces, second - because the processor knows something about itself that is an external piece of information.

Any suggestions on how to design this?

How to remove multiple if blocks using design patterns

I have following functions in my class.

  1. GetAData()
  2. GetBData()
  3. GetCData()

and following Input format:-

public class Input
{
    bool IsGetA{get;set;}
    bool IsGetB{get;set;}
    bool IsGetC{get;set;}
}

Now based on input if have to return the response. a simple solution is

var result;
if(Input.IsGetA)
{
    result+=GetAData();
}
if(Input.IsGetB)
{
    result+=GetBData();
}
if(Input.IsGetC)
{
    result+=GetCData();
}
return result;

How can i remove if conditions using design patterns.

How to write own Method which waits until one statement is true

Hello im saw that many javaclasses have some sort of waitfor (like Process.waitFor() or Future.get()) Methods inside it, and i need to write Methods like that in a Future Program but with the difference, that it should check if a Method returns true or another Method (or Methods) has completed. Is there an elegant and not deprecated solve for this issue which doesnt contain some sort of Bruteforce? (like make an loop which infinitly checks an return statement)

How to name PHP class restructuring JSON API?

I am creating the new version of website and use Models of old application using REST API.

So I have a model class which consume old JSON, convert it to array, RESTRUCTURE it to new structure, generate new structure JSON.

Which Programming Pattern (Type) is this class of? How to name it? Decorator? Proxy? Bridge? Moddler? Is there any officially accepted pattern?

lundi 26 août 2019

Is there a better way to know if the current read line is null in a read-while loop?

I would like to know if there is a functional approach in identifying no lines are left to be read in the while condition when reading from, e.g. standard input or a file.

I have tried the Option/Some/None pattern in several ways, but nothing seems to work better than the old Java null with != boolean comparison operation.

var a: String = null.asInstanceOf[String]
while( { a = scala.io.StdIn.readLine; a != null } ) {
namesMap.get( a ) match {
    case Some( value ) => println( s"$a=$value" )
    case None => println( "Not found" )
  }
}

Can you please give some advice you can have as experienced Scala programmers?

Thanks in advance.

Designing for incremental migration

We would incrementally move away from a legacy persistence infrastructure to a strategic one.
The underlying infrastructure would be abstracted in a Gateway ,which would be injected with the appropriate medium at initialization.
The application would delegate the persistence to the Gateway irrespective.
However,for the legacy medium - the application needs to do an additional houskeeping.
If we do as below - the islegacy() infests the entire app space instead.

Is there a pattern or approach recommended for such incremental migration?

Class App{

     void persistEmployeeData(){
            ...
            ...
           success = gateway.persistEmpoyee(empDTO);
           if(gateway.islegacy()){
             ...do housekeeping...
            }
     }

}

Is it bad to have a service loop?(design question)

I have a design pattern question where I have encounter a discussion with my friend.

The problem is caused by function A inside Service A which called function B inside Service B and the function B in the Service B call function B from the Service A.

Is that a bad design?or will it cause problem?is this way that we should avoid coding like this?

Implementation for object converter design pattern using generics

I'm trying to create a generic object converter, for my dto <-> entity classes. I have created an abstract class with two functions representing both conversions and then extended it in my concrete converter class.

But I would like to have a generic conversion service, where I could register all of my converters during bootup and then conveniently call a single method to handle the conversions between each other.

This is what I have come up so far:

Converter abstract class

public abstract class Converter<D, E> {

  private final Function<D, E> fromFirstToSecond;
  private final Function<E, D> fromSecondToFirst;

  public Converter(final Function<D, E> fromFirstToSecond, final Function<E, D> fromSecondToFirst) {
    this.fromFirstToSecond = fromFirstToSecond;
    this.fromSecondToFirst = fromSecondToFirst;
  }

  public final E convertFromFirstToSecond(final D first) {
    return fromFirstToSecond.apply(first);
  }

  public final D convertFromSecondToFirst(final E second) {
    return fromSecondToFirst.apply(second);
  }

}

Converter concrete class

public class MyConverter extends Converter<MyDTO, MyEntity> {

    public OrderConverter() {
        super(
            MyConverter::fromDTOToEntity,
            MyConverter::fromEntityToDTO
        );
    }

    private static MyEntity fromDTOToEntity(MyDTO dto) {
        return MyEntity.builder()
            .field1(dto.getField1())
            .field2(dto.getField2())
            .build();
    }

    private static MyDTO fromEntityToDTO(MyEntity entity) {
        return MyDTO.builder()
            .field1(entity.getField1())
            .field2(entity.getField2())
            .build();
    }

}

And I would like to achieve something like this (this is where I need HELP):

@Configuration
public class ConverterConfiguration {

  @Bean
  public ConverterService converterService() {
    ConverterService converterService = new ConverterService();
    converterService.registerConverter(new MyConverter());
    // Register any other converter...
    return converterService;
  }

}

The service would look something like this:

public class ConverterService {

  private Map<Key, Converter<?, ?>> converters = new ConcurrentReferenceHashMap<>();

  public void registerConverter(Converter<?, ?> converter) {
    this.converterCache.put(key, converter);
  }

  protected <I, O> I mapBetweenTypes(final O from, final Class<I> clazz) {
    // Based on the parameters I should be able to figure out which function to get from the map and then call (convertFromFirstToSecond or convertFromSecondToFirst)
    // return this.converters.get(key).convertFromFirstToSecond(from);
    return this.converters.get(key).convertFromSecondToFirst(from);
  }

}

Singleton Pattern , java.sql.SQLException: Access denied for user 'x'@'x' (using password: YES),Why does this happen, just the singleton pattern?

Why, when I program in java, the connection to a mysql database, managed by phpmyadmin, using the Singleton Pattern design pattern, is it impossible for me to access the records of the tables in that database, because i see the message in console : "Access was denied to user 'x'" , but when I do not use the Singleton Pattern design pattern, it is possible to access the records in the tables in the 'x' database?

 public static void main(String[] args) {
        // TODO code application logic here
        String usr = "************";
        String pwd = "**********";
        String driver = "**********";
        String url = "*************";

        Connection con = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;

        try{
            //parte >>> 1

            Class.forName(driver);
            con = DriverManager.getConnection(url, usr, pwd);
            //con = Uconnection.getConnection();
             //parte >>> 2

             String sql = "SELECT ***,***,***,*** FROM ***";
             pstm = con.prepareStatement(sql);
             rs = pstm.executeQuery();

             while(rs.next()){
                 System.out.print(rs.getInt("***")+" ");
                 System.out.print(rs.getString("***")+" ");
                 System.out.print(rs.getDate("***")+" ");
                 //System.out.print(rs.getString("***")+" ");
                 System.out.println(rs.getInt("***"));
             }
        }catch(Exception ex){
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }finally{
            //parte >>> 3
            try{
                if(rs != null)rs.close();
                if(pstm != null)pstm.close();
                if(con != null)con.close();
            }catch(Exception ex){
                ex.printStackTrace();
                throw new RuntimeException(ex);
            }

        }
    }

before Implements singleton pattern

 public static void main(String[] args) {        
        Connection con = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;

        try{
            //parte >>> 1
            con = Uconnection.getConnection();
             //parte >>> 2

             String sql = "SELECT ***,***,***,*** FROM ***";
             pstm = con.prepareStatement(sql);
             rs = pstm.executeQuery();

             while(rs.next()){
                 System.out.print(rs.getInt("***")+" ");
                 System.out.print(rs.getString("***")+" ");
                 System.out.print(rs.getDate("***")+" ");
                 //System.out.print(rs.getString("***")+" ");
                 System.out.println(rs.getInt("***"));
             }
        }catch(Exception ex){
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }finally{
            //parte >>> 3
            try{
                if(rs != null)rs.close();
                if(pstm != null)pstm.close();
                if(con != null)con.close();
            }catch(Exception ex){
                ex.printStackTrace();
                throw new RuntimeException(ex);
            }

        }
    }

after implements singleton pattern

mongodb and multiprocessing - large ram usage

I am utilizing multiprocessing for parsing files for input into databases and have come to the extremely common problem of feeding data from these several processes to connections to the database.
There are of course several different way in which to do this, a few being:

  1. Create several processes in a pool, which then feed data to one connection to the data base. This requires making a queue on the output end of the pool and making the pool wait until the queue finishes a process in order to receive another job.

  2. Create several process in a pool, which each have it's own connection to the database and operate in parallel. (i.e. let the database drivers deal with the concurrency)

  3. Same as (1), but include a pool of connections to deal with the queue

A problem with many of the options is if the data being passed around and stored is large in each process, therefore each process needs to wait for the data to be persisted on the disk via the database before retrieving the next job.

This seems like it is solved in the implementation of (1).

I have tried the following (which works), but this produces a mongodb process which accumulates enormous amounts of RAM usage.

from p_tqdm import p_imap
import gc
import pymongo
import time


def data_chunk_process(f):
    # Some processing that takes time
    time.sleep(3)
    # Some ranom data that's fairly large
    m = 100
    n = 10000
    d = [{str(k):str([v]*100) for k, v in zip(range(m), range(m))} for i in range(n)]

    conn = pymongo.MongoClient()
    cln = conn['testDB']['test_collection']
    cln.insert_many(documents=d)

    conn.close()


class Database:
    def __init__(self):
        # Perhaps we could simply use one connection?
        self.conn = pymongo.MongoClient()

    def database_insertions(self):
        files = list(range(1000))
        # Process one thousand files, with each file consisting of several thousands of documents
        for file_doc_chunk in p_imap(data_chunk_process, files):
            gc.collect()

db = Database()
db.database_insertions()

glances output:

CPU%   MEM%  VIRT  RES     PID USER          TIME+ THR  NI S  R/s W/s Command
0.3    41.9  93.6G 92.2G 32344 mongodb       30:16 32    0 S    ? ?    /usr/bin/mongod

I am worried that if this script is executed on a computer with less RAM (e.g. ~4-8 GB), the system will crash due to using all of the available RAM.

What can be done to remove this constraint?

Simple Database structure for access to records

My question is about rights for data access to certain information and the easiest way to check these rights in a simple structure. In my case, this applies to the best structure for a database with tables containing documents that can only be edited by certain users. My database structure is currently the following:

docs
{
  doc_id: uuid (primary key)
  name: varchar
  content: varchar
}

workgroup
{
  workgroup_id: uuid (primary key)
  name: varchar
}

workgroup_members
{
  workgroup_member_id: uuid (primary key)
  workgroup_id: uuid
  user_id: uuid
}

users
{
  user_id: uuid (primary key)
  name: varchar
}

For each document, there exist two possibilities:

  1. Only a single user can edit a documents
  2. A document can be 'assigned' to a workgroup, so that only members of that workgroup can edit the document

Now, what is the most simple yet effective way to embed this information in my tables?

My initial thought was to structure my docs table in the following way:

docs
{
  doc_id: uuid (primary key)
  name: varchar
  content: varchar
  workgroup_id: uuid
  user_id: uuid
}

But then, either workgroup_id or user_id is always NULL. Also, the query to check if a user with a certain ID can edit the documents is not very straightforward, and also listing all documents a user works on becomes quite complex.

I also thought of not changing the docs table, but creating a doc_access table:

doc_access
{
  doc_access_id: uuid (primary key)
  doc_id: uuid
  user_id: uuid
}

This however, would create a lot of 'duplicate' information when a document is assigned to a workgroup, because all of the workgroup members need to be given access to the document. Also, I would need to run a query every time after document creation to add this 'extra' information to the doc_access table. Checking access with this table is easier though.

Is there maybe a better/simpler way to store this relationship between users, workgroups and document access?

Design pattern to customize possible statuses of a Character in a game

I decided to an solid rpg-like game structure with Java to practice design patterns.

Basically there are different types of characters in my game, which are all considered to be "game objects", having some common features:

public abstract class Character extends GameObject {
  Status status;
  //fields, methods, etc.
}

public abstract class Monster extends Character{
  //fields, methods, etc
}

public class Hero extends Character {
  //fields, methods, etc
}

Status here is an enumeration:

public enum Status {
  NORMAL,
  BURNT,
  POISONED,
  HEALED,
  FROZEN
}

I would like to make my code flexible, easy-to-modify, and I would like to follow the SOLID principles using the necessary design patterns effectively.

Let's suppose I would like to customize my characters, allowing to create custom Character extensions allowing to have only certain status changes. For example I would create a Monster called

public class FireGolem extends Monster{...}

, which is unable to get damaged by heat (hence is unable to get burnt).

I have 2 ideas to do this:

1) create a Set for the class Character, in which I would specify what kind of status changes can a Character have

2) create different interfaces (Burnable, Freezable, ...) and implement them when necessary.

What do you think? Which is better and why? Is there any better and cleaner option at all?

Thank you in advance.

Angula 2 Reactive Forms need service injection

I'm working in a project where we have lot of complex forms, so normally I create an extended class from FormGroup, and create getters for all my properties and everthing I need.

Sometimes I need to inject any service into that form class to get some information needed for the form creation. As my forms are not injectables() I have to pass manually those service thought the constructor... but that is not nice to me... it make the creation of the form a bit odd.

So, to make it better, I normally create a FactoryForm which I make it @injectable(). That way I can simply use the factory creation methods for my form creation, as I can inject anything in my factory, and I can make transparent for anybody that some service injections are taking place. I want to keep my form creation as easy as possible.

Do you know a better way? I feel that the pattern I'm using is still to much complicate.

dimanche 25 août 2019

How to choose right design solution for application?

Currently i am creating a design for a new enterprise application. Right now we have a lot of different proprietary solution and we wanna create a new one to switch from them all.

Briefly it is a kind of data destribution system. We have a lot of clients who needs a lot of different data. What do i want: 1) Common REST API service 2) Some synchronoyu(async?) enviroment to send task and get data back. On image below you could see i think to use spring kafka request/reply template. It helps to scale my application in future. 3) Different typec of calculators for every kind of data

img

I search a lot how to do the second point the best way but didn't find any ready solutions or advices. Is it good to use kafka here? Maybe some one could give me advice about best practice in such situations. Plz, send me links for articles or something else, because it will be a big application and i wanna start to create it rightly from the beginning.

samedi 24 août 2019

How to instantiate one object to communicate with others?

This is quite a generic programming question, but if it makes any difference, I will be coding in JavaScript (nodejs).

I have 3 classes: HTTPServer, IRCBot, and Game. The Game class will change depending on which game is being played, but the other two classes will remain the same.

HTTPServer and IRCBot will always have the same functionality. The HTTPServer and IRCBot will send incoming requests/messages to the Game class, the Game class will handle the requests/messages according to whichever game it is, and then the Game class will use the HTTPServer/IRCBot class to send requests/messages back.

Basically, the communication will look as such:

HTTPServer <-> Game <-> IRCBot

How should I go about instantiating these classes as cleanly as possible? The HTTPServer just needs the instance of Game, Game needs the instances of both HTTPServer and IRCBot, and the IRCBot just needs the instance of Game.

Or is there a better way to accomplish this?

Propagate and persist changes in a tree in Spring JPA/Boot

I am struggeling with a design - persistence issue . I have a tree and all elements in this tree are subclasses of the same abstract superclass. The tree has a root object with a list of children which themselves can have children, and so on. Changes to attributes of a children would need to be propagated to all parent levels. To make it easier to illustrate, let's say we deal with products which would have multiple releases, having multiple development phases. Each of these would have a lifetime. So we would have something like

@Entity
@Access(AccessType.PROPERTY)    // JPA reading and writing attributes through their getter and setter methods
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(
        discriminatorType = DiscriminatorType.STRING,
        name = "lifetime_level",
        length=10
        )

public abstract class LifeTime implements Serializable {

    // all classes are incomplete for sake of brevity

    protected Integer version;                  // Optimistic locking support

    protected LocalDate plannedBegin;           // The calculated, potentially shifted, begin resulting from children assignments
    protected LocalDate plannedEnd;

    private LifeTime parent;

    protected List<LifeTime> children;

    @ManyToOne
    public LifeTime getParent() {
        return parent;
    }

    public void setParent(LifeTime parent) {
        this.parent = parent;
    }

    @OneToMany(mappedBy="parent")
    public List<LifeTime> getChildren() {
        return children;
    }

    private void setChildren(List<LifeTime> children) {
        this.children = FXCollections.observableList(children);
    }

    public void addChild(LifeTime child) {
        children.add(child);
    }

    public LocalDate getPlannedBegin() {        
        return plannedBegin;
    }


    public void setPlannedBegin(LocalDate aBegin) {
        this.plannedBegin = aBegin;
        adjustParentBegin(parent, this);
    }

    public LocalDate getPlannedEnd() {
        return plannedEnd;
    }


    public void setPlannedEnd(LocalDate aEnd) {
        this.plannedEnd = aEnd;
        adjustParentEnd(parent, this);
    }

    protected void adjustParentBegin(LifeTime parent, LifeTime child) {
        if(child.getPlannedBegin.isBefore(parent.getPlannedBegin)) {
            parent.setPlannedBegin(child.getPlannedBegin);
        }
    }

    protected void adjustParentEnd(LifeTime parent, LifeTime child) {
        if(child.getPlannedEnd.isAfter(parent.getPlannedEnd)) {
            parent.setPlannedEnd(child.getPlannedEnd);
        }
    }

    @Version
    public Integer getVersion() {
        return version;
    }

    private void setVersion(Integer version) {
        this.version = version;
    }

}

We would have the concrete classes Product, Release and Phase. All would extend LifeTime. As root object we have a product. The product has children representing releases of the product and each release would have several development phases. We would also have baselines, iterations that we ignore for the moment. Next, we have somewhere a service class that cares for handling the business logic:

@Service
public class LifeTimeService {

    @Autowired ProductRepository productRepository;
    @Autowired ReleaseRepository releaseRepository;
    @Autowired PhaseRepository phaseRepository;

    public Product createProduct() {
        Product product = new Product();
        release.setPlannedBegin(LocalDate.now());
        release.setPlannedEnd(LocalDate.now());

        product = productRepository.save(product);  // without will throw TransientPropertyValueException: object references an unsaved transient instance when saving release

        createRelease(product);

        return productRepository.save(product);
    }

    public Release createRelease(Product product) {
        Release release = new Release();
        product.addChild(release);
        release.setParent(product);

        release.setPlannedBegin(product.getPlannedBegin());     // initial values
        release.setPlannedEnd(product.getPlannedEnd());

        release = releaseRepository.save(release);      // without will throw TransientPropertyValueException: object references an unsaved transient instance when saving phases

        addPhases(release);     // add phases and adjust begin and end of the release

        return releaseRepository.save(release);
    }

    protected void addPhases(Release release) {

        LocalDate date = release.getPlannedBegin;

        Phase phase1 = new Phase();
        release.addChild(phase1);
        phase1.setParent(release);

        phase1.setPlannedBegin(date);
        date = date.plusMonth(3);
        phase1.setPlannedEnd(date);

        phaseRepository.save(phase1);

        phase2 = new Phase();
        release.addChild(phase2);
        phase2.setParent(release);

        phase2.setPlannedBegin(date);
        date = date.plusMonth(3);
        phase2.setPlannedEnd(date);

        phaseRepository.save(phase2);
    }

}

Let's say we have Controller class, that makes use of the Service

@Controller
public class MyController {

    @Autowired LifeTimeService service;

    protected Product product;

    public void myTest() {
        Product product = service.createProduct();  // this creates a product with an initial release and all phases
        Release release = service.createRelease(product);   // now the product has a later plannedEnd than the corresponding database row
    }
}

Obviously, I want that the createRelease method creates and returns a release. The issue is that it alters all levels of the tree: It creates phases but also changes the parent product begin and end date. I would need to save the product after I call createRelease to persist this change. This approach doesn't scale if the tree has more levels. Otherwise, if I save the product within createRelease, the product in the myTest method would have the wrong version. Or createRelease returns the saved parent - what is counter intuitive - and I have to code a method which return last created release. This is all unsatisfying.

While the above class example follows the Domain Driven Design, whereby each object is in charge of securing its integrity, I was although thinking about Anemic Domain Model and moving the two adjustment methods to the service class and make them recursive. But I don't see how it changes or fixes the above issue.

In reality my tree goes over at least 5 hierarchical levels. So whatever solution you propose, it should scale to multiple levels.

vendredi 23 août 2019

What is the best way to execute continues operations using java

I have to build one API.This api suppose to do couple operation in a sequence manner and based on this operations, it has to generate api response. For example there are 10 steps inside this api.Almost all steps are interacting with DB and some other APIs also. If any operation got failed I have to pick it from that failed step and move forward. I am planning to use schedular for this retry mechanism.This retry mechanism not part of this service.But we have build this api in a such way that it should provide information for this retry mechanism also.

I have to use this same mechanism in some other APIs also if I can create a generic tool which will help to solve this problem that will be really great

Consider above scenario and suggest me some good library or good design pattern which can solve above problem with out compromising any object oriented concepts and coding standard

NOTE:

I don't want use messaging systems like Kafka because if I use Kafka each message will go out of application. Please feel free to comment on this thought

I am using springboot,Java8,Microservice architecture

I just gone through spring state machine,Command design pattern, pipeline design patter,Apache camel,Spring Integration

Nikhil

No parameterless constructor defined for this object in ASP.NET MVC

I am getting No parameterless constructor defined for this object error while posting data. It is working fine on get. I am using service pattern in my project and using unity container for handling dependency injection. I have registered all the services in container.

Stack Trace :-

[MissingMethodException: No parameterless constructor defined for this object.] System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0 System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +122 System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +239 System.Activator.CreateInstance(Type type, Boolean nonPublic) +85 System.Activator.CreateInstance(Type type) +12 System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +197

[MissingMethodException: No parameterless constructor defined for this object. Object type 'System.Web.Mvc.SelectList'.] System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +233 System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +285 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +284 System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +17 System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +377 System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +101 System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +55 System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1210 System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +333 System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +336 System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105 System.Web.Mvc.Async.<>c__DisplayClass3_1.b__0(AsyncCallback asyncCallback, Object asyncState) +640 System.Web.Mvc.Async.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128 System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +346 System.Web.Mvc.<>c.b__152_0(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +27 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128 System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +494 System.Web.Mvc.<>c.b__151_1(AsyncCallback asyncCallback, Object callbackState, Controller controller) +16 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128 System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +403 System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16 System.Web.Mvc.<>c.b__20_0(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +54 System.Web.Mvc.Async.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30 System.Web.Mvc.Async.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +427 System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +105 System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +50 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163

As suggested in some articles i have also created the constructor for my model but no luck.

My Controller (GET)

    [HttpGet]
    public ActionResult Home()
    {
        var ct = _ctService.getctdetails();

        var viewModel = new HomeviewModel()
        {
            itemsList= GetItemsList(),
            ctDTO= ct 

        };
        return View(viewModel);
    }

POST:-

    [HttpPost]
    public ActionResult Submit(HomeviewModel values)
    {


        return RedirectToAction("Index");
    }

ViewModel:-

  public class HomeviewModel
 {
    public productDetailsDTO { get; set; }
    public CreationDTO ctDTO{ get; set; }
    public SelectList itemsList{ get; set; }
  }

Controller Constructor

 public HomeController(ICTService ctService,
        ITemsService itemService)
    {
        _ctService= ctService;
        _itemService= itemService;
    }

In My view i am just using the itemslist and setting values in DTO , fetching some data using ajax if we change the selected item and submitting form, the control is coming to the controller constructor but after that giving error,not going to the post method.

For concrete classes that implement multiple interfaces, how can clients to that class follow Dependency Inversion?

My issue is that I have a concrete implementation which implements two different interfaces. In the spirit of Dependency Inversion Principle, I would like clients to this class to only depend on an interface and not the concrete implementation. However, as this class uniquely implements these two interfaces; it seems to me that all clients will need to program to this concrete implementation.

Take the example below: I have a Restaurant class which for the most part only needs to interact with implementations of the Pizza interface. However, the CanadianPizza class also implements the Canadian interface, with the intention that every time someone serves this Pizza they must apologize, it seems like my Restaurant class would need to have some coupling with the concrete impl (see below).

Looking for ways to avoid depending on concrete implementations with classes that are a unique composition of multiple interfaces.

interface Pizza {
    void bake()
    void addToppings()
    void rollDough()
}

interface Canadian {
    void apologize()
}

class CanadianPizza implements Pizza, Canadian {
    @Override
    void bake() { ... } 
    @Override
    void apologize { ... }
}

class Restaurant {

    private final Pizza mPizza;

    constructor(Pizza pizza) {
        mPizza = pizza; 
    }

    void serveFood() {
        mPizza.rollDough()
        mPizza.addToppings()
        doSomethingWithPizza()
        // But I also need to know if my Pizza is Canadian
        if (mPizza instanceof CanadianPizza) {
            ((CanadianPizza) mPizza).apologize()
        }
    }
}

C# Interfaces & Generics working together

I have a domain object, Address that may be populated from a variety of data sources, which requires a lot of mapping code. In the interest of "Closed to Modification" I want to be able to create individual "Mappers" for each data source. I can then pass the mapper into an instance of the Address and VOILA! get an appropriate data entity back in response. And vice-versa, I also want implement a method on that Address that will allow me to map an entity into a new or to populate an existing instance of the Address.

I create my Address object ...

public class Address
{
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    public string Street3 { get; set; }
    public string Street4 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
    public string PostalCode { get; set; }
}

Now I create a couple of classes that will facilitate mapping specific data entity objects to and from this Address object.

//
// Maps to and from a Database object (DB1_ADDRESS)
//
public class DB1AddressMapper
{
    property DB1_ADDRESS _entity;

    public DB1AddressMapper()
    {

    } 

    public DB1AddressMapper(DB1_ADDRESS entity)
    {
        _entity = entity;
    }

    public DB1_ADDRESS MapModelToEntity(Address model)
    {
        DB1_ADDRESS ret = new DB1_ADDRESS();

        <... mapping logic goes here>

        return ret;
    }

    public Address MapEntityToModel()
    {
        Address ret = new Address();

        <... mapping logic goes here>

        return ret;
    }
}

//
// Maps to and from a WebService response (WS_ADDRESS)
//
public class WSAddressMapper
{
    property WS_ADDRESS _entity;

    public WSAddressMapper()
    {

    } 

    public WSAddressMapper(WS_ADDRESS entity)
    {
        _entity = entity;
    }

    public WS_ADDRESS MapModelToEntity(Address model)
    {
        WS_ADDRESS ret = new WS_ADDRESS();

        <... mapping logic goes here>

        return ret;
    }

    public Address MapEntityToModel()
    {
        Address ret = new Address();

        <... mapping logic goes here>

        return ret;
    }
}

Now that I have my mappers I create a method on Address that I can pass them into, in order to facilitate transforming the data. So you can see in the code below that I have had to overload the methods because each mapper has its own types involved. This means that every time I want to add a new data source to populate the Address object I have to re-open Address and add new overload methods. Ugghhh ... no thanks you (what happened to "closed for modification"?)

public class Address
{
    public string Street1 { get; set; }
    public string Street2 { get; set; }
    public string Street3 { get; set; }
    public string Street4 { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
    public string PostalCode { get; set; }
    //
    // Populate "this" instance of the Address object from data found in the mapper.
    // The "mapper" argument would have to have been instantiated with the entity it expects to map 
    // to the Domain object, Address
    //
    public Address MapToModel(DB1AddressMapper mapper)
    {
        return mapper.MapEntityToModel();
    }

    //
    // Map "this" instance of address to a new DB1_ADDRESS instance
    //
    public DB1_ADDRESS MapToEntity(DB1AddressMapper mapper)
    {
        return mapper.MapModelToEntity(this);
    }


    //
    // And now again for WSAddressMapper
    //
    public Address MapToModel(WSAddressMapper mapper)
    {
        return mapper.MapEntityToModel();
    }

    //
    // Map "this" instance of address to a new WS_ADDRESS instance
    //
    public WS_ADDRESS MapToEntity(WSAddressMapper mapper)
    {
        return mapper.MapModelToEntity(this);
    }

} 

This leads me to interfaces and generics ... which I have dabbled in for years but the lack of necessity for them has not forced me to deepen my understanding of them (which I believe holds me back).

Back to the problem at hand ... I only want two mapping methods in Address that will be "closed for modification". They need to accommodate any mapper for any data source I run into. The mapper encapsulates all the specific mapping logic and Address doesn't really care about the details. It just wants to "MapTo".

The pseudo-code solution looks something like this ...

public class Address 
{
    public Address MapToModel(EntityMapper mapper)
    {
        ...
    }

    public EntityAddress MapToEntity(EntityMapper mapper)
    {
        ...
    }
}

It seems that I could make an interface for the mappers so that all mappers will implement the same two methods ...

MapModelToEntity();
MapEntityToModel();

I start with that ...

public interface IEntityAddressMapper
{
    Address MapEntityToModel();
    T MapModelToEntity<T>(Address model);
}

You may be able to see where I start to run into trouble. Since the return type of the "MapModelToEntity" varies from data source to data source I don't know what to make this. I opt to make it a generic; those have worked for me in other areas. I press on by implementing it in my mappers in hopes that an answer will reveal itself.

public class DB1AddressMapper : IEntityAddressMapper
{
    Address MapEntityToModel()
    {
        Address ret = new Address();

        <... mapping logic goes here>

        return ret;
    }

    //
    // This is what I want but, does NOT satisfy interface
    //
    DB1_ADDRESS MapModelToEntity(Address model)  <!-- DOES NOT SATISFY INTERFACE
    {
        DB1_ADDRESS ret = new DB1_ADDRESS();

        <... mapping logic goes here>

        return ret;
    }
    //
    // This satisfies interface but is silly. The mapper already KNOWS the TYPE, that's the point.
    // Besides this means that the consumer will have to pass in the types, which is EXACTLY what 
    // I am trying to avoid.
    //
    T MapModelToEntity<T>(Address model)  
    {
        DB1_ADDRESS ret = new DB1_ADDRESS();

        <... mapping logic goes here>

        return ret;
    }   
}

I've tried a million different permutations so it's impractical to list them all here but suffice to say the closest I have come so far is the following ...



public interface IEntityAddressMapper<EntityType>
{

    EntityType MapModelToEntity(Address mode);

    void MapModelToEntity(Address model, ref EntityType entity);

    Address MapEntityToModel(EntityType entity);

    void MapEntityToModel(EntityType entity, ref Address model);
}



public class DB1AddressMapper : IEntityAddressMapper<DB1_ADDRESS>
{
    Address MapEntityToModel()
    {
        Address ret = new Address();

        <... mapping logic goes here>

        return ret;
    }

    T MapModelToEntity(Address model)  
    {
        DB1_ADDRESS ret = new DB1_ADDRESS();

        <... mapping logic goes here>

        return ret;
    }   
}

This seems to allow me to implement the Interface without a problem now, but I seem to have shifted the burden to the methods which now are breaking ...

public class Address 
{
    // *********************************************
    // ERROR - Using generic type 'IEntityAddressMapper<EtityType>' requires one type argument
    // *********************************************
    public Address MapToModel(EntityMapper mapper)
    {
        ...
    }

    // *********************************************
    // ERROR - Using generic type 'IEntityAddressMapper<EtityType>' requires one type argument
    // *********************************************
    public EntityAddress MapToEntity<EntityType>(EntityMapper mapper)
    {
        ...
    }
}

I'm spinning in circles and have been for years on this. I need to sort this out!! Any help would be greatly appreciated.

Thanks

Instantiating module object on module's file vs. instantiating module object on file that uses it

Are there any advantages/disadvantages to instantiate a module object on the module's file instead of instantiaing the module object on the file that uses it?

Example of Instantiating module on the module's file:

module.js

const someModule = (function() {
  const doSomething = function(id) {
    console.log("doing something");
  };

  return {
    doSomething: doSomething
  };
})();

export someModule;

main.js

import { someModule } from "./module";
someModule.doSomething();

Example of instantiating module on the file that uses it:

module.js

const someModule = function() {
  const doSomething = function(id) {
    console.log("doing something");
  };

  return {
    doSomething: doSomething
  };
};

export someModule;

main.js

import { someModule } from "./module";
someModuleInstance = new someModule();
someMosomeModuleInstance.doSomething();

The first example only has "someModule"(from the import statement) on the main file's global scope while the second example has both "someModule" and its instance on the global scope. So is the first example better?

different return type and signature in Strategy Pattern in Java

I am bit confuse to use Strategy Pattern in my below case.

I have Contact class which is below.

public class Contact {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(columnDefinition = "INTEGER(11) UNSIGNED")
    private long id;

    @Column(columnDefinition = "INTEGER(11) UNSIGNED", nullable = false)
    private long userId;

    @Column(columnDefinition = "VARCHAR(255)")
    String firstname;

    @Column(columnDefinition = "VARCHAR(255)")
    String lastname;
// other fields

I have below scenario that

  1. getContact(long user_id) which accepts user_id as parameter and return List which have same user_id from database.
  2. updateContact(Contact contact) which accepts Contact as parameter and update this contact in database.
  3. deleteContact(long contactID) which accepts ContactID as parameter and delete this contact in database.
  4. addContact(Contact contact) which accepts Contact as parameter and add this contact in database.

    Strategy Pattern with Java with above requirement. I can use Strategy Pattern in Java if method has similar input parameter and similar output parameter. But for my case I have different input parameter and different output parameter so I am confuse that how can I use Strategy Pattern. Please guide me on this case.

Keeping rating for multiple tables

Having the db design with more than two tables representing main entities e.g. book, publisher, author I want to find out what will be best approach for user-rating for a given entity.

Is it the best to create one table with no relation to the above tables but only for user table (to show user the rating of a given table record) and indicate the type of related table with varchar?

Or is it better to keep separate rating table for each of the tables.

My idea would be as below but I'm not sure is it the best way to store this kind of data.

***rating table***
ObjectType
ObjectId
UserId
RatingScore

jeudi 22 août 2019

What is difference between Monolith to Microservices? And when to use it?

I want to know what is the difference between the Monolith and Microservice design pattern and when to use those.

C++: Where to place helper/subfunctions functions?

I'm designing a class for a project I'm working on.
A member function is too big and I want to break it down into smaller functions.

I've looked into lambda functions, private functions and free functions. None of which really satisfy me enough. Lambda functions make the line too long (ex. auto check_vertical = [&](char **grid, size_t i, size_t j, size_t amount) -> bool { ), private functions are visible to other functions within the class and free functions are visible to any files which include the file.

class Foo {
    private:
        Goo goo;
    public:
        Foo(size_t size);
        ~Foo();
        size_t get_xyz(size_t size) const;
};

size_t Foo::get_xyz(size_t size) const {
    // A lot of code.
}

I currently have this setup.

class Foo {
    private:
        Goo goo;
    public:
        Foo(size_t size);
        ~Foo();
        size_t get_xyz(size_t size) const;
};

size_t Foo::get_xyz(size_t size) const {
    auto check_something = [&](char **grid, size_t i, size_t j, size_t amount) -> bool {
        ....
    };
    // More lambda functions..
}

I want to break down get_xyz function into smaller functions.
Where should I place the new functions? What's the best design principle?

How to Set Options for Function Deep in a Call Hierarchy [on hold]

I have a C++ application (C++11) and deep in the call hierarchy I have a function that I would like to be able to show output from in occasional circumstances. The question is how to tell the function whether or not to show the output. It seems like the options are:

  • Pass in some variable through the call hierarchy, or add a value to the parameter object already being passed through the hierarchy
  • Set a global variable that the function checks.
  • Read in a parameter from a file
  • If we can set it at compile time, use a #ifdef that includes the code

None of these feels right, so I'm looking for a design pattern or discussion of the right way to do this.

Design pattern for different client type

In Java, what would be a better design pattern, for designing classes when request ( HTTP ) and response can be different for different client eg. android vs TV etc.

Right now, the code is bloated with if(android) {} etc.

Would Adapter pattern be a good choice?

Upcast using reference in C++

I would like to use the "Strategy" design pattern, and have just one simple question.

We have two classes: Base as an abstract class and Derived as a concrete class.

#include <iostream>

using namespace std;

class Base {
public:
    virtual void func() = 0;

};

class Derived : public Base{
public:
    virtual void func() override
    {
        printf("hello \n"); 
    }
};

int main(){

    Base * base = new Derived();
    base->func();

    Derived derived2;
    Base & base2 = derived2;
    base2.func();

    return 0;
}

Using pointer,

Base * base = new Derived();

Using reference

Derived derived2; 
Base & base2 = derived2; 

  1. Is there any way to write in one line for reference?
  2. Which method are you guys use to implement the "strategy" design pattern, using pointer or reference?

Because of the reason above, I tend to use pointer... but I would like an answer from experts.

Visitor pattern - visiting super class before visiting class

I have a class structure containing a base class and several extending classes. There are multiple 'Actions' i want to perform on each class which depends on their type - which is why i want to use the visitor pattern. Implementing the actions on the classes itself requires some dependencies which i want to avoid pushing to the event class.

This is a simplification of my current class structure that i want to move into the visitor pattern :

class BaseEvent{

    public BaseEvent(SomeDependency d){...}
    String baseAttrA;

    public void doActionA(){
       d.doSomeAction(baseAttrA);
    }
}


class EventA extends BaseEvent{
      String eventAAttribute;
      public EventA(SomeOtherDependency d){...}    
      public void doActionA(){ 
        super.doActionA();
        d.doOtherAction(eventAAttribute);
      }    

}

I have several more classes that extends BaseEvent and several more actions.
Please note :
EventA(and following) actions requires the same action to be done on Base event .
Same action on BaseEvent/EventA/other requires a different dependency and attribute. it is a different logic that is called on the same scenario.

Optimally, i'd like to have a class for each Action (using the visitor pattern), which recieves the specific dependencies it requires for the actions and contains all the logic in one class. Something like

public class ActionAVisitor{
     public ActionAVisitor(SomeDependency d1, SomeOtherDependency d2){...}

   public void visit(BaseEvent event){
       d1.doSomeAction(event.getBaseAttribute());  
  }

  public void visit(EventA event){
      // Missing call to super.doActionA()
      d2.doDifferentAction(event.getEventAAttribute());
  }

The problem is that now there is no call to super.doActionA(), which can be solved by calling an ugly this.visit((BaseEvent)event); instead of the commented line. But this have to be added on each visit function, in all visitors.... which feels wrong.

Is there any other design pattern \ addition to the visitor pattern that will allow me to do that?

mercredi 21 août 2019

OOP Design for PET STORE

DOMAIN

Building a custom software for a pet shop owner.

  • This pet shop sells 3 kinds of pets: cats, dogs, birds.

  • The shop is open from Monday to Saturday.

  • The store has a showroom where 5 dogs, 10 cats, 15 birds are shown to the customers

  • The store has a backyard where 15 dogs, 30 cats, 30 birds can live.

  • At night, the pet store owner move all the pets from the showroom to the backyard.

  • Cats and dogs cannot be sold if they not have been implanted with a chip identifying them.

  • Every Sunday, the pet shop owner would bring all the cats and dogs that don’t have a chip implanted yet to the veterinarian. The pets should be at least 2 months old to have a chip. The cost for the chip is 200 Yen per animal.

  • The owner keep a record for each animal with its name, date of birth, unique chip identifier, date when the chip was implanted, the price of the pet and a description text for the showroom.

  • Customers can subscribe to an insurance when buying a pet. The insurance allow them to return the pet during 3 months. They would get 80% cash back (excluding the price of the insurance). The insurance cost 10,000 Yen.

  • Customers can take an option on a cat or dog. they would pay 20% of the price up-front and the pet would be given to them after the trip the veterinarian. The pet shop owner would contact the customers on Friday and ask them to come pick the pet on Monday.

USE CASES

  • The pet shop owner would like to have a weekly revenue report. The report should also show the money immobilized (money the store owner might have to return to customers) because of the insurance policies.

  • The owner would like the system to give him a list of pets that should be in the showroom. Pets that have an option on them don’t need to be shown to customers.

I have designed some classes here to implement domain. But, i can’t confirm that I did it correctly.

How can I design this situation Using OOP concept?

A suitable method to predict next binary outcome based on the patterns of past binary data

I have a series of binary data ( W and L values which are trade results of a trading platform) and I need to be able to predict the next value (Whether W or L) based on the past patterns. What would be the best method to accomplish this in Matlab o python.

I have already tried a basic pattern matching algorithm developed by my self. What I do there is get an input sequence of 5 outcomes and match it with all past data to get a probability of the 6th outcome. However the accuracy of that method is close to 30% which is not suitable for my prediction. That is a very basic method, I'm sure there must be other machine learning methods which would give more accurate results.

Basically What I need is, I have a past data sequence [ W, L, W , W , L , W ......up to 4300 points ] like this. And my system generates new data feeds like this [ W , L, L ,W ...] what I need is to predict the value of the next data, by matching the patterns of my current data feed to the past 4300 data points.

How to write a base class whose child classes depend on each other?

I'm trying to write a mathematical set class. My idea was to make an base class which is called Set. Then i wrote two child classes of the Set class. Namely the FiniteSet class and the CountableSet class (which can deal with infinite Sets). My problem is now that those child classes depend on each other and I cannot solve this. I will also appreciate completely different solutions to this problem.

//--------------------------------------------------------
//Set class
//--------------------------------------------------------
class Set
{
public:
    //some virtual functions

protected:
    //some attributes 
};

//--------------------------------------------------------
//FiniteSet class
//--------------------------------------------------------
class FiniteSet : public Set
{
public:
    //implements all virtual functions 

    //function which needs to know CountableSet:
    Set unionWith(Set* otherSet)
    {
        if(typeid(CountableSet) != typeid(*otherSet))
        {
            //the other set is finite. We can simply add all             
                        //elements from otherSet to this set.
        }
        else
        {
            //create a CountableSet and return it
        }
    }

private:
    //some attributes
}

//--------------------------------------------------------
//CountableSet class
//--------------------------------------------------------
class CountableSet : public Set
{
public:
    //implements all virtual functions 

    //function which needs to know FiniteSets
    Set intersectWith(Set* otherSet)
    {
        if(typeid(FiniteSet) == typeid(*otherSet))
        {
            //do something and return FiniteSet
        }
        else
        {
            //do something and return occasionally CountableSet
        }
    }

private:
    //some attributes
}

Angular Service Factory pattern

I am trying to deploy a new module for work and I am stuck on how to implement the design pattern for my service.

To be specific I have a generic class called 'LoggerService' which gets extended by my services for console logging and database logging. I now want to be able to export the whole module and fetch it from a proxy within the company. The publishing and fetching works, but now the problem is that when I want to instantiate either one of the concrete services, angular tells me that this service was not exported. `

@NgModule({
  declarations: [NgxCmLoggerComponent],
  imports: [NgxCmHttpModule
  ],
  exports: [NgxCmLoggerComponent],
  providers: [NgxCmDatabaseLoggerService, NgxCmConsoleLoggerService]
})
export class NgxCmLoggerModule { 
  static forRoot(config: NgxCmLoggerService): ModuleWithProviders {
    return {
      ngModule: NgxCmLoggerModule,
      providers: [
        {provide: NgxCmLoggerService, useClass: config}
      ]
    };
  }
}`

This is how my module looks like, as you can see I am providing both Services and I have the forRoot method to instantiate the service I want for the use case. `

NgxCmLoggerModule.forRoot(new NgxCmConsoleLoggerService),

` That's how I am trying to instantiate my service, in this case, the console logger. When I try this, angular signals me that the ConsoleLoggerService, which should be provided by the module, is not available. I am pretty sure I am doing something wrong with respect to the forRoot method, I just don't know what.

I am happy for any help, thank you, Chris.

Should DAO methods receive a data object as parameter or just its contents?

I am thinking about two different approaches for a DAO and I was wondering which is more correct. Let's say that we have the following class:

public class Employee {

private int id;
private String name;

//getters and setters

}

And the following two approaches for the DAO:

A)

public class EmployeeDao {

    public Employee insert(int id, String name) {
    ...
    }

B) :

public class EmployeeDao {

    public Employee insert(Employee employee) {
    ...
    }

My question is whether both approaches are correct and/or one of them is more correct than the other.

Thank you for your attention.

Java: How to neatly create a data mapper utility for 200 fields not to repeat same checks again all over?

Suppose we have scenario like following

if (!areEquals(empFraMD.getUserId(), empFraBubba.getUserId())) {
            empFraMD.setUserId(empFraBubba.getUserId());
            updated = true;
} 

if (!areEquals(empFraMD.getFirstName(), empFraBubba.getFirstName())){
            empFraMD.setFirstName(empFraBubba.getFirstName());
            updated = true;
}
 .........200 Times check for 200 different parameter. 150 Times String checks 20 times integer checks. 
 //EmpFraMD is current employees in Database and empFraBubba is employees fetched from SFTP 
    and both are objects of same class. The requirement here is just to update database 
    only in case difference

updated flag is just to set at end of code that if updated is true then setLastUpdated(now) in database.

Is there neat way to do this in Java using either design pattern or beans or some other way of transformation rather then write same chunk again and again?