samedi 30 juin 2018

How to properly link new SimulatedEncoders class to an IMotor interface

Full Code: https://github.com/Team-2502/ezAuton

package com.team2502.ezauton.actuators;

/**
 * A motor. Takes in an input and runs the motor.
 */
public interface IMotor
{
}

package com.team2502.ezauton.actuators;

/**
 * A motor which can be run at a certain velocity
 */
public interface IVelocityMotor extends IMotor
{
    void runVelocity(double velocity);
}

package com.team2502.ezauton.actuators;

/**
 * A motor which can be run at a certain voltage
 */
public interface IVoltageMotor extends IMotor
{
    void runVoltage(double voltage);
}

package com.team2502.ezauton.localization.sensors;

/**
 * A sensor which can record revolutions/s and revolutions as a distance
 */
public interface IEncoder extends ITachometer
{
    /**
     * @return revolutions
     */
    double getPosition();
}

package com.team2502.ezauton.localization.sensors;

/**
 * A sensor which can measure revolutions / s
 */
public interface ITachometer extends ISensor
{
    /**
     * @return revolutions / s
     */
    double getVelocity();
}

  • right now all IMotor subclasses (implementations of interfaces IVelocityMotor, IVoltageMotor) are basically maps of (input -> action) (they are effectively interfaces which act as setters for a motor).
  • As I am further decoupling logic, I am making a group of SimulationEncoders ⊆ IEncoder which can be useful for...
    • simulations
    • fake encoders (i.e. if someone is using voltage drive without encoders but still wants to be able to estimate position)
  • The problem is how to link the group of implemented SimulationEncoders to IMotor implementations.
    • I could possibly have SimulatedEncoder1(ITachometer) and SimulatedEncoder2(IVoltmeter) for IVelocityMotor and IVoltageMotor, respectively. SimulatedEncoders would implement an interface Updateable and be called every x seconds to read ITachometer and IVoltometer inputs. The problem with this is it is clunky and the SimulatedEncoders might work better knowing every time a method of IMotor is called instead of periodically checking the last call.
    • I could use the Observer pattern to add SimulationEncoders which listen to setVelocity(...), setVoltage(...)
    • I could try to couple these into one class which acts as a wrapper and forwards velocity/voltage to a SimulatedEncoder and an IVelocityMotor/IVoltageMotor... the problem with this is I don't see any easy way to link specific types of SimulatedEncoders to their respective type of motor.

Any help resolving this dilemma would be greatly appreciated.

Factory of union type without type casting

abstract class Passenger {
    passengerKey: string;
}

class PassengerAdult extends Passenger {
    adultField: string;
}

class PassengerInfant extends Passenger {
    infantField: string;
}

class PassengerFactory {
    static createPassenger(isInfant: boolean): PassengerAdult | PassengerInfant {
        if (isInfant) {
            return new PassengerInfant();
        }

        return new PassengerAdult();
    }
}

const passengerInfant: PassengerInfant = PassengerFactory.createPassenger(true); 

I get an error that

Type 'PassengerAdult | PassengerInfant' is not assignable to type 'PassengerInfant'. Type 'PassengerAdult' is not assignable to type 'PassengerInfant'. Property 'infantField' is missing in type 'PassengerAdult'.

Can I in some way force typescript to understand what he's returning inside createPassenger method? I know that in the call line I'd cast the result like

const passengerInfant: PassengerInfant = <PassengerInfant>PassengengerFactory...

but i'd like to avoid that.

When apply observer pattern an error occured

I have the following code:

class ISubscriber;
class News {
public:
    float getVersion() { return this->version; }
    void setVersion(float state) { this->version= state; this->notifyAllSubscribers(); }
    void attach(ISubscriber *observer) { this->subscribers.push_back(observer); }
    void notifyAllSubscribers() {
        for (vector<ISubscriber*>::iterator it = subscribers.begin(); it != subscribers.end(); it++){
            (*(*it)).update();
        }
    }
private:
    vector<ISubscriber*> subscribers;
    float version;
};

class ISubscriber {
public:
    News *news;
    virtual void update() = 0;
};

class Subscriber1 : public ISubscriber {
public:
    Subscriber1(News *news) { this->news = news; this->news->attach(this); }
    void update() override { cout << "Subscriber1: A new version of the newspaper has been launched (v" << this->news->getVersion() << ")" << endl; }

};

class Subscriber2 : public ISubscriber {
public:
    Subscriber2(News *news) { this->news = news; this->news->attach(this); }
    void update() override { cout << "Subscriber2: A new version of the newspaper has been launched (v" << this->news->getVersion() << ")" << endl; }

};


int main(int argc, char *argv[]) {
    News newspaper;
    newspaper.setVersion(2.1f);

    Subscriber1 sb1(&newspaper);
    Subscriber2 sb2(&newspaper);
    return 0;
}

But a strange errors happened:

The first error points to this code (*(*it)).update(); in news class. Why that errors happened, what's the reason?

What pattern to check on an SQL query for possible injection?

I want to detect possible SQL injection atack by checking the SQL query. I am using PDO and prepared statement, so hopefully I am not in the danger of getting attacked by someone. However, what I want to detect is the possibility of input/resulting query string that may become a dangerous query. For example, my app--properly--will never generate "1=1" query, so I may check the generated query string for that, and flag the user/IP producing that query. Same thing with "drop table", but maybe I can check only by looping the input array; or maybe I should just check to the generated query all over again. I am using MySQL, but pattern for other drivers are also appreciated.

I have read RegEx to Detect SQL Injection and some of the comments are heading in this direction. To my help, I'm developing for users that rarely use English as input, so a simple /drop/ match on the query may be enough to log the user/query for further inspection. Some of the pattern I found while researching SQL injection are:

  • semicolon in the middle of sentence -- although this may be common
  • double dash/pound sign for commenting the rest of the query
  • using quote in the beginning & ending of value
  • using hex (my target users have small to low chance for inputting 0x in their form)
  • declare/exec/drop/1=1 (my app should not generate these values)
  • html tag (low probability coming from intended user/use case)
  • etc.

All of the above are easier to detect by looping the input values before the query string is generated because they haven't been escaped. But how much did I miss? (a lot, I guess) Any other obscure pattern I should check? What about checking the generated query? Any pattern that may emerge?

tl;dr: What pattern to match an SQL query (MySQL) to check for possible injection? I am using PDO, so the check is for logging/alert purposes.

Java NullPointerException occurred at the same of the construction

Sorry if this question has been answered already. I am written a java program, where I am trying to use the factory pattern to encapsulate SQL statement queries. For this, I create a SQL interface which I use to declare a variable on another abstract class (no instantiation). Instantiation of SQL query variable is done in the constructor of the concrete class. For example :

public abstract class ProductList {
    private  Connection connection;
    private DataBaseDAO dbInstance; //DataBaseDAO uses singleton
    protected  ResultSet results;
    private  Statement statement;
    protected  SqlQuery sqlquerry; //abstract product


    public ProductList(){
        dbInstance = DataBaseDAO.getInstance();
        if(dbInstance.open()) {
            try{
                connection = dbInstance.getConnection();
                statement = connection.createStatement();
                statement.execute(sqlquerry.createTable()); //To be defined

            }catch(Throwable t) {
                t.printStackTrace();
            } finally {
                try{
                    statement.close();
                } catch (SQLException e)  {
                    e.printStackTrace();
                }
            }
        }
    }
}

Implementing the ProductList concrete class, with a concrete instance of SQL query

public class GenericProductList extends ProductList {
    public GenericProductList() {
       this.sqlquery = new StandardProductSqlQuery(); //instantiating 
    }
}

I create an instance of the GenericProductList, as for example:

public class Main {
    public static void  main(String[] args){
        ProductList generic = new GenericProductList();
    }
}

The problem is whenever I run the program I get the following java.lang.NullPointerException which can be traced to the following line:

 statement.execute(sqlquerry.createTable());

 public GenericProductList() 

 ProductList generic = new GenericProductList();

NullPointerException screenshot

What did I do wrong? Thanks for looking and answering!

vendredi 29 juin 2018

In the State Pattern as outlined in the Gang of Four textbook can the ConcreteState objects make changes to the context in which they reside?

This is a quote that I might be misinterpreting from this section of the book Design Patterns, Elements of Reusable Object-Oriented Programming.

• A context may pass itself as an argument to the State object handling the request. This lets the State object access the context if necessary.

If the ConcreteState is passed the context from a Request(this); is that State allowed to make changes to the context itself?

In the example I'm working on the Context is a WindowsForm in C#, with states such as FormStart and FormStop. I would like to make changes so that when the state is changed some of the buttons in the form are disabled/greyed out. As far as I know the constructor of the ConcreteState could be passed the context as an argument and then the state could make changes to the context.

Let me know what you think. I'm still a beginning programmer working on making GUI apps that are functional and reusable from a code perspective before working on tweaking the UI and making the front end pretty.

Best way to refactor this class

We have this legacy system that has many DataAccess classes for adding/removing/retrieving data from many bussines entities from the SQL Server.

Thing is all have the singleton pattern applied for the DB connection. So for each DataAccess class there's a static DB (GetInstance like) method that returns the connection (it keeps one connection per DataAccess instance). This started giving us headaches because the connection is shared and we seem to have multithreading issues, etc.

public class SomeDataAccess {

private static Database dBConnection;

private static Database DB
       {
            get
            {
                if (dBConnection== null)
                {
                    dBConnection= DatabaseFactory.CreateDatabase();
                }
                return dBConnection;
            }
        }

public method_1() {
  ... 

   DB.ExecuteScalar("mystoredprocedure", param1, param2,...param_n);

  ...
}

.
.
.

public method_k() {
  ... 

   DB.ExecuteReader(...)

  ...
}

}

Anyway, we would like to refactor this code into the use of "Using" for keeping the connections and closing them automatically, if possible, or some other good practice for C# in this case.

Is it a good pattern to use !! notation to listen for ReactJS changes?

I've been adopting ReactJS + Redux in my projects for a couple of years. I often end up in asynchronous situations where I need my component to wait for the state to be updated to render. Normally the simple logic !this.props.isFetching ? <Component /> : "Loading..." is enough.

However there are cases where I need to check for the state of an array that is embedded in the state object. In these cases, most of my components end up looking like this:

  renderPostAuthor = () => {
    if (!!this.props.postDetails.author) {
      return this.props.postDetails.author[0].name;
    } else {
      return (
        <div>
          <StyledTitle variant="subheading" gutterBottom color="primary">
            Loading...
          </StyledTitle>
        </div>
      );
    }
  };

Is this use of the !! notation a good pattern / practice in ReactJS?

Dao and polymorphism

Say I have a hierarchy of vehicles:

public interface Vehicle { ... }
public class Car implements Vehicle { ... }
public class Bike implements Vehicle { ... }
public class Motorcycle implements Vehicle { ... }

Each concrete vehicle type has its own *Dao, because they must be partially persisted on different tables.

Say I'm working over a List<Vehicle>, what's the better approach to avoid instanceof or switches for selecting the correct *Dao implementation?
I'm not in a DI context.

PHP model with too many constructor arguments

In my current project I am implementing an Model-View-Presenter pattern. Most of my classes that represent domain objects have too many constructor arguments. Take this for example (NOTE: This is just a made-up class, just assume that models need too many arguments):

class Person {
    private $id;
    private $first_name;
    private $middle_name;
    private $last_name;
    private $birthdate;

    private $schoolName;
    private $schoolYearLevel;

    ... more properties

    public function __constructor($id, $first_name, $middle_name, $last_name, .. etc){
        ... some code to set the properties
    }
}

Suppose this class has many independent values needed for construction (7+ values), what good design can I use? The values are fetched rows from a database.

How to architecture an application that uses information from a third party API service?

I am looking for guidelines on how to architect my solution that utilizes most of its information from a third party service. Most of my applications are developed on N-layered architecture and deployed on multiple tiers. I know this may have many opinions but I just need a brief overview I can elect as the best solution before I begin develop.

Ideally, I will have the following structure in my solution:

--UI > User Interface --BO > Business Objects/ Dtos --API > Local API to feed to many user interfaces, i.e. Web/Mobile --BLL > Business Logic Layer for any application specific rules --DAL > Data Access Layer Entities and Repositories to perform CRUD ops against my DB --3rd API > To retrieve information and display within my application

I am not sure as in how to construct objects from this 3rd party source, should I marry the requests in my DAL layer or UI layer, what are the best principles and practises for working in this model, and am sure theres a lot of us developing applications that depend on other services. I would like to develop a clean, separation of concerns between layers, so that its easy to swap out the 3rd party service in case if it goes 'white elephant'. If you have a blog or examples I can look at please? Or if you would like me to elaborate more

ToList() doesn't apply dynamically generated where clauses Asp.Net Core

ToList() doesn't apply dynamically generated where clauses Asp.Net Core I am building pipeline for filtering. so i have method where i retrieve iqueryable from dbcontext, it looks like the following:

 public IEnumerable<Event> Filter(EventFilterModel filterModel)
    {
        _filterManager = new EventsSelectionPipeline();
        _filterManager.Register(new EventTypeFilter(filterModel.EventTypes, _unitOfWork));

        var events = _unitOfWork.DbContext.Events;
        var filteredEvents = _filterManager.Process(events);

        return filteredEvents.ToList();
    }

Process method:

public override IQueryable<Event> Process(IQueryable<Event> input)
    {
        foreach(var filter in _filters)
        {
            filter.Execute(input);
        }

        return input;
    }

EventTypeFilter :

public class EventTypeFilter : IFilter<IQueryable<Event>>
{
    private readonly IEnumerable<EnumEventType> _eventTypes;
    private readonly IUnitOfWork<ApplicationContext> _unitOfWork;

    public EventTypeFilter(IEnumerable<EnumEventType> eventTypes, IUnitOfWork<ApplicationContext> uow)
    {
        _eventTypes = eventTypes;
        _unitOfWork = uow;
    }

    public IQueryable<Event> Execute(IQueryable<Event> input)
    {
        if (_eventTypes.Any())
        {
            BinaryExpression condition = null;
            var expr = new List<Expression<Func<Event, bool>>>();
            var parameter = Expression.Parameter(typeof(Event), "ev");

            foreach(var eventType in _eventTypes)
            {
                var property = Expression.Property(parameter, "EventType");
                var propType = ((PropertyInfo)property.Member).PropertyType;
                var converter = TypeDescriptor.GetConverter(propType);

                var propertyValue = eventType;
                var constant = Expression.Constant(propertyValue);
                var valueExpression = Expression.Convert(constant, propType);
                var dynExpr = Expression.Equal(property, valueExpression);

                condition = condition == null ? dynExpr : Expression.Or(condition, dynExpr);
            }

            if(condition != null)
            {
                var predicate = Expression.Lambda<Func<Event, bool>>(condition, parameter);

                input = input.Where(predicate);
            }
        }

        return input;
    }
}

In IQueryable<Event> Process(IQueryable<Event> input) method Execute return iqueryable with correct number of elements (with applying filtering), but when i apply toList to iqueryable it just returns me initial set of data without filtering.

jeudi 28 juin 2018

Factory pattern with class as key

Need to know if there is any problem with this code. Have used Class as key for ComputerFactory. The advantage is that you don't need to make any changes in factory class when you add a new computer subclass. Further, with the help of generics, I am able to enforce only the valid keys for Computer factory.

public abstract class Computer {

protected String name;

@Override
public String toString(){
    return "Computer type: "+name;
}

}

public class Pc extends Computer {

public Pc() {
    this.name = "PC";
}

}

public class Server extends Computer {

public Server() {
    this.name = "Server";
}

}

public class ComputerFactory {

public static Computer getComputer(Class<? extends Computer> type) {

    Computer computer = null;
    if (!Computer.class.equals(type) && Computer.class.equals(type.getSuperclass())) {
        try {
            computer = type.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    return computer;
}

}

public class Test { public static void main(String args[]) {

    Computer c = ComputerFactory.getComputer(Server.class);
    if (c != null)
        System.out.println(c.toString());
}

}

Long input pattern validation fails on Edge and IE11

I am checking a email field to include any of the accepted domain names at the end using a long list of those TLDs in the pattern attribute of the <input> field

Here is a shortened version with the middle part excluded:

pattern=".+(\.aaa|\.aarp|\.abarth|\.abb|\.abbott|\.abbvie|\.abc|\.able|\.abogado|\.abudhabi|{...}|\.zuerich|\.zw)"

The pattern is accepted just fine in Chrome and Firefox but Edge and IE11 fail to validate if the match is somewhere in the ".co*" area and later

for example "email@example.aaa" validates, whereas "email@example.com" does not

Take a look and test here: https://jsfiddle.net/qoalu/Lj0p4ys5/4/

Can design patterns (factory pattern) be referenced outside a classic OOP approach? (academic context)

Now first of all, I'm not exactly sure if this should be moved to academia, but I think it is still 'SO enough'.

Here is the situation. For my master's thesis I have implemented a web-based application using javascript/angularjs. The application in question enables the user to create different items and as such, I had to implement various toolboxes and wizards. From a high level point of view, I used factory patterns:

Angular services provide methods for controllers to receive objects, which are created by the service based on an abstract object skeleton and the parameters given by the controller.

It made sense to me back then since I was used to Java mostly. Now I am fully aware that AngularJS (Javascript) is no OOP language and lacks things like inheritance which are usually a core element of the classic design patterns. Factory is not the only example here, I also used Observer and Producer/Consumer like approaches.

Now in my written thesis I have to describe and ideally back up what I have done and why. A simple "It made sense to me" is not something I would exactly feel comfortable writing, but making a bad reference would be even worse. So the question has basically three parts:

Is it viable to reference classic design patterns in this context?

If no, are there other, similar standards for non-oop languages?

If also no, would 'I thought it was a good idea' be better than not giving any reasoning at all?

Network proxy in Android MVP

In an Android application, I use a proxy skeleton pattern to communicate with a remote server. Implementing the MVP architectural pattern, who should call the proxy methods? The Model or the Presenter?

Correct Terminology of Types of Users and the Application Modules Built for Each

I'm designing a system that will have multiple modules. It is even possible that these modules are separated into different applications. Then it came a question I had previously asked myself but I could not get the answer:

What names should I give to different types of users of the modules of a system? Is there a current default pattern?

Existing example: Uber

Uber, with its "drivers users" and "passengers users", has an application for each of these types of users. Uber states that drivers are their partners and not employees (and not customers). But what about the passengers? Are they customers of Uber or customers of the drivers? Do you understand where I want to go?

My case:

In the case of my project, my client would be a number of different professionals who would be the source of money income for the system (so they would be my clients), and they would be users of a 'apk' module built only for them. These clients have their own clients, who would use another separate 'apk' module to use the services of the professionals already mentioned. These users (clients of my clients) would not pay to use the system. In addition, there are the users who administer my clients, using a CRM module that will be made for them.

In the end, there are at least 4 types of users:

  • My customers
  • Customers of my customers
  • Employees of my customers, with more restricted access profile to work for my customers in the application
  • Managers of my customers (my collaborators which have client wallets)

So, how should you name each module and its users? knowing that there is still the open module, which can be accessed without the need for authentication...

Dirty example:

  1. Customers Module
  2. Customers Clients Module + Public Areas Module
  3. CRM Module

Is it good to implement mixin pattern using #include macro in C++

As we know, mixin is a design pattern to "insert" some behaviors to another class. For example, in Ruby, we can write code like this

module Flyable
  def fly
    puts "I'm flying";
  end
end

class Bird
  include Flyable
end

C++ does not have language level mixin support, but we can use multiple inheritance to insert code to derived class. But this solution still have it's own problems, like diamond inheritance, unable to override virtual method in interface, unable to access members from "sibling" modules etc.

Later I found I can use #include macro to insert code segment to class definition to achieve mixin:

// in Flyable.h
public:
void fly() {
    // do something ...
}
float flySpeed;

And in another file

// in Bird.h
class Bird {
#include "Flyable.h"
};

So all member variables and functions are inserted to Bird class.

This solution seems to have no obvious drawback. Codes are organized well into different files. Possible name conflicts can be avoided by carefully designed modules without overlapping functions/rules.

But still I afraid there're some problems I haven't seen yet. Is there any problems for this kind of mixin?

mercredi 27 juin 2018

what is the main design pattern java.io.InputStream,java.io.Output Stream utilize?

what is the main design pattern java.io.InputStream, java.io.Output Stream and all their subclasses (ex: java.io.FilterInputStream, java.io.BufferedOutputStream) utilize?

Template Method and Remove If Statements

So, Im studying Design Patterns, and Im studying the Template Method.

From how I understood it, It is a set of Methods (The skeleton) wrapped in a Method (Operation) on an Abstract Class (If done via heritage), where different Concrete Subclasses write their own implementation of those methods (Not all of them).

But I have a doubt, what happens if some, maybe 2 methods of the skeleton are not used by a certain concretion?, Here I have an example I made, which totally violates the SRP:

using System;

namespace TemplatePattern
{
    public abstract class Coffee
    {

        public void MakeCoffee()
        {
            HeatWater();

            PutCoffee();

            if (HaveMilk())
            {
                PutMilk();
            }

            if (HaveGratedChocolate())
            {
                PutGratedChocolate();
            }

            PutSweetener();

            ServeCoffee();
        }

        internal void HeatWater()
        {
            Console.WriteLine($"I heated the water");
        }

        internal void ServeCoffee()
        {
            Console.WriteLine($"Coffee Served");
        }

        internal void PutCoffee()
        {
            Console.WriteLine("I put 2 spoons of Coffee");
        }

        internal virtual void PutMilk() { }

        internal virtual void PutGratedChocolate() { }

        internal abstract void PutSweetener();

        public virtual bool HaveMilk()
        {
            return false;
        }

        public virtual bool HaveGratedChocolate()
        {
            return false;
        }
    }
}

Concrete class SimpleCoffeeWithMilk:

using System;
namespace TemplatePattern
{
    public class SimpleCoffeWithMilk : Coffee
    {

        public override bool HaveMilk()
        {
            return true;
        }

        internal override void PutSweetener()
        {
            Console.WriteLine($"I put 1 spoon of Sugar");
        }

        internal override void PutMilk()
        {
            Console.WriteLine($"I put 100Cc of Milk");
        }
    }
}

Another Concrete class:

using System;

namespace TemplatePattern
{
    public class CoffeeWithChocolate : Coffee
    {
        public override bool HaveGratedChocolate()
        {
            return true;
        }

        internal override void PutGratedChocolate()
        {
            Console.WriteLine("Le puse choco rayado");
        }

        internal override void PutSweetener()
        {
            Console.WriteLine($"Le puse azucar");
        }

    }
}

Main Entry Point:

using System;

namespace TemplatePattern
{
    class Program
    {
        static void Main(string[] args)
        {
            SimpleCoffeWithMilk coffeWithMilk = new SimpleCoffeWithMilk();
            CoffeeWithChocolate coffeeWithChocolate = new CoffeeWithChocolate();

            coffeWithMilk.MakeCoffee();

            Console.WriteLine("\n\n");

            coffeeWithChocolate.MakeCoffee();

            Console.ReadLine();

        }
    }
}

The idea is to get rid of those If's Statements, is there any way of doing this with the template method, where some of the methods execute depending of the concrete class?

I was thinking in creating interfaces like ICoffeeWithMilk with PutMilk() method on it and implement that interface on my SimpleCoffeeWithMilk concrete class, but watching the UMLs, the Template Method for what I saw does not rely on Interfaces.

Advantages and disadvantages of using one of Singleton or Dependency Injection over the other

I know the simple differences between them, but when it come to the scenario where I want to share an object instance in the app, I can done this by using DI or Singleton.

when this question come to my mind I became confused, since I can use both, I think that one of them must be better than the other in cases like multi-threading or memory management or code maintainability ...

can someone tell me what is the advantages and disadvantages of using one of them over the other in the above scenario and what is the correct choose ??

mardi 26 juin 2018

Unity Gamespark Errorhandling

In my project we use Unity with Gamesparks and want to handle in a efficient way our errors which are sent from Gamesparks to Unity. We have foreach Response an own Class which parse the right error from Gamesparks and save them in a class like this: public class GetMiniGameTutorialResponse { public enum ErrorCodes { TIMEOUT, INVALID_MINI_GAME_ID }

    public bool hasErrors;
    private ErrorCodes _error;
    public ErrorCodes error {
        set {
            hasErrors = true;
            _error = value;
        }
        get { return _error; }
    }

    public string tutorial;
    public string control;
}

Next is that we handle these errors in a script of our scene in Unity and handle them with a switch case like this:

    private void getMiniGameTutorialResponseErrorHandler(GetMiniGameTutorialResponse.ErrorCodes error)
    {
        switch (error)
        {
            case GetMiniGameTutorialResponse.ErrorCodes.TIMEOUT:
                showConnectionError();
                break;
            case GetMiniGameTutorialResponse.ErrorCodes.INVALID_MINI_GAME_ID:
                Debug.LogWarning("UNKNOWN STATE ERROR");
                break;
            default:
                Debug.LogError("UNKNOWN ERROR");
                break;
        }
    }

We need to do this in every script where we want to use the GetMiniGameTutorialResponse class.

My question now is if everyone of you want to help me to refactor this so that my code styling will be better :D

Fit a repeated pattern in Matlab

I have the following time series that i want to model. enter image description here

The graph shows several 'events' that have a repeated pattern (i consider event the data points between the straight lines). I can fit each part (the parts between the straight lines) separately with a 3rd or 4th level polynomial but what i want is to create a continuous model to fit several plots like this one automatically.All events should have the same shape (the reason why they do not look exactly the same is because of some noise added). Does anyone know how to create a model for this whole plot if i know the shape of one of those events? I am using Matlab for the analysis but Python would work too.

design patterns to realize a shell unix command

Can someone please tell me which design pattern can be used to realize a command like:

ls -l * | cut -f1, 2 | sort

It would be really great if I get a sample code. I am seeking help in Java language.

C#. Force type parameter in generic interface to be the type of the class implementing that interface

Suppose I have the following interface:

interface IFoo<T>{}

I want to know if I can force that any class implementing this interface must provide its own class name as type parameter. Consider IEquatable<T> interface, it is perfectly legal to do:

class Moo:IEquatable<string>{ /*...*/}

Although it does not make any sense right? Suppose now I modify IFoo in the following way:

interface IFoo<T>
{
     void CopyObject(T obj);
}

I do not want to be possible to do the following:

class Foo:IFoo<Boo>{
     public void CopyObject(Boo object){}
}

So far I have tried:

interface IFoo<T> where T: IFoo<T>
{
    void CopyObject(T obj);
}

And it kind of works:

class Foo:IFoo<Boo> { /*implementation*/ } //does not compile!

class Boo { }

But:

class Foo:IFoo<Boo> { /*implementation*/ } //it now copiles =(

class Boo:IFoo<Boo> { /*implementation*/ }

The other way I thinked of was an abstract base class and just crash with a pretty runtime exception if things are not the way I want:

abstract class FooBase<T>
{
    protected FooBase()
    {
        if (typeof(T) != GetType())
        {
            throw new InvalidOperationException();
        }
    }

    protected abstract void CopyObject(T obj);
}

Now this base class works but then I have problems with existing types that are already inheriting from another type...

Is there any other workaround or design pattern that may help here?

Simplify an extensible "Perform Operation X on Data Y" framework

tl;dr: My goal is to conditionally provide implementations for abstract virtual methods in an intermediate workhorse template class (depending on template parameters), but to leave them abstract otherwise so that classes derived from the template are reminded by the compiler to implement them if necessary.

I am working on an extensible framework to perform "operations" on "data". One main goal is to allow XML configs to determine program flow, and allow users to extend both allowed data types and operations at a later date, without having to modify framework code.

If either one (operations or data types) is kept fixed architecturally, there are good patterns to deal with the problem. If allowed operations are known ahead of time, use abstract virtual functions in your data types (new data have to implement all required functionality to be usable). If data types are known ahead of time, use the Visitor pattern (where the operation has to define virtual calls for all data types).

Now if both are meant to be extensible, I could not find a well-established solution.

My solution is to declare them independently from one another and then register "operation X for data type Y" via an operation factory. That way, users can add new data types, or implement additional or alternative operations and they can be produced and configured using the same XML framework.

If you create a matrix of (all data types) x (all operations), you end up with a lot of classes. Hence, they should be as minimal as possible, and eliminate trivial boilerplate code as far as possible, and this is where I could use some inspiration and help.

There are many operations that will often be trivial, but might not be in specific cases, such as Clone() and some more (omitted here for "brevity"). My goal is to conditionally provide implementations for abstract virtual methods if appropriate, but to leave them abstract otherwise.

Here is a (fairly) minimal compilable example of the situation:

//Base class for all operations on all data types. Will be inherited from. A lot. Base class does not define any concrete operation interface, nor does it necessarily know any concrete data types it might be performed on.

class cOperation
{
public:
  virtual ~cOperation() {}

  virtual std::unique_ptr<cOperation> Clone() const = 0;
  virtual bool Serialize() const = 0;
  //... more virtual calls that can be either trivial or quite involved ...

protected:
  cOperation(const std::string& strOperationID, const std::string& strOperatesOnType)
    : m_strOperationID()
    , m_strOperatesOnType(strOperatesOnType)
  {
    //empty
  }

private:
  std::string m_strOperationID;
  std::string m_strOperatesOnType;
};

//Base class for all data types. Will be inherited from. A lot. Does not know any operations that might be performed on it.
struct cDataTypeBase 
{
  virtual ~cDataTypeBase() {}
};

Now, I'll define an example data type.

//Some concrete data type. Still does not know any operations that might be performed on it.
struct cDataTypeA : public cDataTypeBase
{
  static const std::string& GetDataName()
  {
    static const std::string strMyName = "cDataTypeA";
    return strMyName;
  }
};

And here is an example operation. It defines a concrete operation interface, but does not know the data types it might be performed on.

//Some concrete operation. Does not know all data types it might be expected to work on.
class cConcreteOperationX : public cOperation
{
public:
  virtual bool doSomeConcreteOperationX(const cDataTypeBase& dataBase) = 0;

protected:
  cConcreteOperationX(const std::string& strOperatesOnType)
    : cOperation("concreteOperationX", strOperatesOnType)
  { 
    //empty
  }
};

The following template is meant to be the boilerplate workhorse. It implements as much trivial and repetitive code as possible and is provided alongside the concrete operation base class - concrete data types are still unknown, but are meant to be provided as template parameters.

//ConcreteOperationTemplate: absorb as much common/trivial code as possible, so concrete derived classes can have minimal code for easy addition of more supported data types
template <typename ConcreteDataType, typename DerivedOperationType, bool bHasTrivialCloneAndSerialize = false>
class cConcreteOperationXTemplate : public cConcreteOperationX
{
public:
  //Can perform datatype cast here:
  virtual bool doSomeConcreteOperationX(const cDataTypeBase& dataBase) override
  {
    const ConcreteDataType* pCastData = dynamic_cast<const ConcreteDataType*>(&dataBase);
    if (pCastData == nullptr)
    {
      return false;
    }
    return doSomeConcreteOperationXOnCastData(*pCastData);
  }

protected:
  cConcreteOperationXTemplate()
    : cConcreteOperationX(ConcreteDataType::GetDataName()) //requires ConcreteDataType to have a static method returning something appropriate
  {
    //empty
  }

private:
  //Clone can be implemented here via CRTP
  virtual std::unique_ptr<cOperation> Clone() const override
  {
    return std::unique_ptr<cOperation>(new DerivedOperationType(*static_cast<const DerivedOperationType*>(this)));
  }

  //TODO: Some Magic here to enable trivial serializations, but leave non-trivials abstract
  //Problem with current code is that virtual bool Serialize() override will also be overwritten for bHasTrivialCloneAndSerialize == false
  virtual bool Serialize() const override
  {
    return true;
  }

  virtual bool doSomeConcreteOperationXOnCastData(const ConcreteDataType& castData) = 0;
};

Here are two implementations of the example operation on the example data type. One of them will be registered as the default operation, to be used if the user does not declare anything else in the config, and the other is a potentially much more involved non-default operation that might take many additional parameters into account (these would then have to be serialized in order to be correctly re-instantiated on the next program run). These operations need to know both the operation and the data type they relate to, but could potentially be implemented at a much later time, or in a different software component where the specific combination of operation and data type are required.

//Implementation of operation X on type A. Needs to know both of these, but can be implemented if and when required.
class cConcreteOperationXOnTypeADefault : public cConcreteOperationXTemplate<cDataTypeA, cConcreteOperationXOnTypeADefault, true>
{
  virtual bool doSomeConcreteOperationXOnCastData(const cDataTypeA& castData) override
  {
    //...do stuff...
    return true;
  }
};

//Different implementation of operation X on type A.
class cConcreteOperationXOnTypeASpecialSauce : public cConcreteOperationXTemplate<cDataTypeA, cConcreteOperationXOnTypeASpecialSauce/*, false*/>
{
  virtual bool doSomeConcreteOperationXOnCastData(const cDataTypeA& castData) override
  {
    //...do stuff...
    return true;
  }

  //Problem: Compiler does not remind me that cConcreteOperationXOnTypeASpecialSauce might need to implement this method
  //virtual bool Serialize() override {}
};

int main(int argc, char* argv[])
{
  std::map<std::string, std::map<std::string, std::unique_ptr<cOperation>>> mapOpIDAndDataTypeToOperation;
  //...fill map, e.g. via XML config / factory method...

  const cOperation& requestedOperation = *mapOpIDAndDataTypeToOperation.at("concreteOperationX").at("cDataTypeA");
  //...do stuff...

  return 0;
}

Singleton Implementation using Function

I read about multiple approaches of creating a singleton function in this SO question.

I came up with another approach

def my_singleton():

    if not my_singleton.instance:
        class MyClass:
            pass

        my_singleton.instance = MyClass()

    return my_singleton.instance

What is wrong with this approach compared to other approaches mentioned in previous SO question? Is there any implication related to memory/GC/thread safety/lifecycle of instance. I am asking this because other approaches looks quite complicated for a beginner (metaclass, decorators, baseclass, decorators returning class)

Refactoring suggestions?

I need some advice on how to refactor the code below. I have multiple configurations classes they are all different, but as you can see in the example code below there is a recurring pattern happening.

I was wondering what would be the best approach to simplify the View code?

 class IConfiguration
{
   public:

    virtual bool Save(const std::string& Output) = 0;       
    virtual bool OutText(const std::string& BaseFileName) = 0;    
}

class MockConfiguration
{
   MOCK_METHOD1(Save,bool(const std::string& Output));
   MOCK_METHOD1(OutText, bool(const std::string& BaseFileName));
}   

void View::SaveConfiguration1(std::string path)
{
    m_Configuration1->Save(path);
    m_Configuration1->OutText(wxFileName::StripExtension(path).ToStdString())
    //Enable Reset Menu 
    wxMenuItem* item2 = GetMenuBar()->FindItem(wxID_RESET);
    if (item2 != NULL) item2->Enable(true);
}

void View::SaveConfiguration2(std::string path)
{       
    m_Configuration2->Save(path);                                             
    m_Configuration2->OutText(wxFileName::StripExtension(path).ToStdString());

    //Enable Reset Menu 
    wxMenuItem* item2 = GetMenuBar()->FindItem(wxID_RESET);
    if (item2 != NULL) item2->Enable(true);
}

void View::SaveConfiguration3(std::string path)
{
    m_Configuration3->Save(path);
    m_Configuration3->OutText(wxFileName::StripExtension(path).ToStdString());

    //Enable Reset Menu 
    wxMenuItem* item2 = GetMenuBar()->FindItem(wxID_RESET);
    if (item2 != NULL) item2->Enable(true);
}

Search pattern $_POST

I'm searching best solution for situation like this:

I have $_POST request with many params.

In controller i have action like this:

class SearchController extends Controller
{
    /**
     * @Route("/search", name="search")
     */
    public function searchAction(SalonFacade $salonFacade, Request $request){
        $wanted = $salonFacade::convertRequestToWantedSalon($request);
        if($wanted->isValid()) {
            $salons = $salonFacade->findSalonsBy($wanted);
            dump($salons);
        }else{
            dump($wanted->getValidErrors());
        }
        return $this->render('test.html.twig',
            array()
        );
    }
}

As u can guess i convert $_POST request to object called WantedSalon

class SalonFacade
{
    private $entityManager;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    public function findSalonsBy(WantedSalon $wanted)
    {
        return $this->entityManager
            ->getRepository(Salon::class)
            ->findNearestSalons($wanted);
    }
    public static function convertRequestToWantedSalon(Request $request): WantedSalon
    {
        $post = $request->request;
        $wanted = new WantedSalon();

        $paramsKeyToSet = array('lat', 'lon', 'maxDistance', 'serviceCategories', 'datetime', 'name', 'minRating', 'maxRating');
        foreach ($paramsKeyToSet as $wantedKey) {
            $wanted->__set($wantedKey, $post->get($wantedKey));
        }
        return $wanted;
    }
}

But now i see that is not good solution because if i want to add new parameter to form which coming to controller by $_POST i need to change code in THREE places:

  1. add new field in WantedSalon object declaration
  2. add new parameter in SalonFacade::convertRequestToWantedSalon()
  3. i need to consider new field in declaration of SalonRepository->findNearestSalons()

Could you advice any better solution? Best regards

lundi 25 juin 2018

Angular - @Input and @Output vs. Injectable Service

I'm asking myself where are the differences between @Input/@Output in parent-/childcomponents and using services which is only once instatiated with dependency Injection@Injectable(). Or are there any differences besides Input/Output can only be used in parent-/child-comp.

Following Example for better visualization:

With @Input:

<parent-comp>
   <child-comp [inputFromParent]="valueFromParent"></child-comp>
</parent-comp>

ChildComponent:

@Component({
  selector: 'child-comp',
  template: ...
})
export class ChildComponent {
  @Input() public inputFromParent: string;
}

With dependency Injection

@Injectable()
export class Service {
   private value: string;

public get value(): string {
   return value;
}

public set value(input): void {
   value = input;
}

}

Now we can set the value in the parent comp. and get the value in the child comp with dependancy injection. ChildComponent:

@Component({
  selector: 'child-comp',
  template: ...
})
export class ChildComponent {
  private value: string;
  constructor(private service: Service) {
  this.value = this.service.getValue;
}

}

Even though the first approach looks simpler, I recognized using 3-4 properties carriyng through parent-/child comp. with @Input/@Output makes the tamplete very confusing and clunky.

Typing in databases using empty field

My question is about databases pattern (in my case mongo)

is it a good pattern to type, using an empty field ?

for example I have a text object:

  • id: id
  • text: string
  • commentId: id

if comment is empty than it's not a comment it's a answer

But I think this one is better:

  • id: id
  • text: string
  • commentId: id
  • type : ['comment', 'answer']

I my opinion, this is a pattern because it only use commentId for what it is, a storage for id and not a typing variable.

What is your opinion ?

How to design a switcher for parameters in Scala?

Let's say I have an object which has a method foo that accpets OptionTypeV1.

Object Util {
def foo(option: OptionTypeV1)
}

Now, I have a new OptionTypeV2 along with existing OptionTypeV1, and I want to use them with Util.

I want to design a switcher that can switch the version of OptionType.

Object Util {

val optionV2 : Boolean = false

val OptionTypeVersion = optionV2 match {
    case true => OptionTypeV2
    case _ => OptionTypeV1
}

def foo(option: OptionTypeVersion)
}

Is this a good idea? Is there a better way to do it? Any reference?

What design pattern to use parent and child class with child method?

I have faced this problem many times when I want to build a parent-child relationship class.
I have a base AuthenticateRequest class. In my case, I have 2 child requests but they have own logic to GetContent().
It doesn't not really fall into Composite Pattern nor Liskov Substitution as the base method is unique and called.
Which design pattern should I use?

public class AuthenticateRequest
{
    public string Url { get; set; }

    public string ContentType { get; set; }

    public string Method { get; set; }

    public virtual HttpContent GetContent()
    {
        return new StringContent("");
    }
} 

public class SoapAuthenticateRequest : AuthenticateRequest
{
    public string SoapMethodName { get; set; }

    public string SoapAction { get; set; }

    public string KeyForUserNameParameter { get; set; }

    public string ValueForUserNameParameter { get; set; }

    public string KeyForPasswordParameter { get; set; }

    public string ValueForPasswordParameter { get; set; }

    public override HttpContent GetContent()
    {
        var methodName = this.SoapMethodName;
        var keyUsername = this.KeyForUserNameParameter;
        var keyPwd = this.KeyForPasswordParameter;
        var valueUsername = this.ValueForUserNameParameter;
        var valuePwd = this.ValueForPasswordParameter;
        var soapAction = this.SoapAction ?? @"http://tempuri.org/"; 

        var soap = $@"<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""><soap:Body><{methodName} xmlns=""{soapAction}""><{keyUsername}>{valueUsername}</{keyUsername}><{keyPwd}>{valuePwd}</{keyPwd}></{methodName}></soap:Body></soap:Envelope>";

        return new StringContent(soap, Encoding.UTF8, ContentTypes.XmlSoap);
    }
}

public class JsonAuthenticateRequest : AuthenticateRequest
{
    public string SoapMethodName { get; set; }

    public string SoapAction { get; set; }

    public Dictionary<string, string> ParameterKeyValues { get; set; }

    public override HttpContent GetContent()
    {
        var json = JsonConvert.SerializeObject(ParameterKeyValues);
        return new StringContent(json, Encoding.UTF8, ContentTypes.Json);
    }
}

public async Task<AuthenticateResponse> Authenicate(AuthenticateRequest request)
{
    var requestMsg = new HttpRequestMessage
    {
        RequestUri = new Uri(request.Url),
        Method = new HttpMethod(request.Method.ToString()),
        Content = request.GetContent(),
    };

    var responseMsg = await _httpClient.SendAsync(requestMsg).ConfigureAwait(false);
    var responseContent = await responseMsg.Content.ReadAsStringAsync().ConfigureAwait(false);

    return new AuthenticateResponse
    {
        Message = responseContent,
        IsSuccess = Regex.Match(responseContent, (string)request.RegexForValidUser).Success
    };
}

How can i design this?

Say I have different types of operations which i need to perfom. I have an abstract class 'BaseOperation' which has all the information common to all operations. Now i need to categorize these operations based on an attribute and then further categorize every operation in each category based on some other attribute as shown in figure below. The goal is to log the operation type and subtype to prioritize investigation in case of any failures. enter image description here

The way i thought i would do this is: I can have two enums corresponding to type and subtype in 'BaseOperation'. I can define a additional layer of abstract classes deriving the base which set the type of the operation and have operations derive the class of their type. The subtype for each operation can be set foreach operation individually.

I am not sure if this will be the best thing to do and if there is any design pattern i can follow for this scenario (i couldn't find any yet). Also i need this design to be extendable, say i want another attribute to be added for each operation (which i can easily do above by adding another enum in base and setting it again for each operation).

Overriding construct

Lets say I have this code:

abstract class AbstractCar {
    private $car;

    public function __construct(CarInterface $car)
    {
        $this->car = $car;
    }
}

class LamboCar extends AbstractCar {
    public function __construct(LamboCarInterface $car)
    {
        parent::__construct($car);
    }
}

Question is: is overriding construct method only to change $car type from CarInterface to LamboCarInterface (LamboCarInterface extends CarInterface) bad practice? Let's say AbstractCar do call some methods from CarInterface, and LamboCar call some methods from LamboCarInterface

dimanche 24 juin 2018

DTO, Data Layer and types to return

At my job we use Entity Framework for data access. I am creating a Data Access Layer, a Business Access Layer and a few different types of projects to access the BLL (webAPI for client applications to interface with, multiple MVC websites and a few different desktop WinForm applications).

I added the DTOs to a separate project named "DTO". The goal of this project within this solution is to have a DLL with all the definitions for the classes and interfaces that will be past back and forth. That way this one project can be created as a git submodule within other solutions and updated for all the UI projects to use collectively. I will not be working on all the UIs as we bring more developers into the project and we will probably need to have multiple VS solutions.

My thought was to have the Data Access Layer pass back and take in DTOs instead of entity objects. This would decouple the process completely.

If we ever wanted to replace the DAL with something else as long it followed the interfaces defined in the DTO project we should be fine. I also think it would make testing easier as I can replace the DAL with a project to generate the DTOs with something like Seed.net. BTW replacement is a real possibility given our environment.

Is adding this layer of complexity bad or against design standards? Is there something I am missing?

Aggregate root referencing a collection of entities

Following up on my previous post, I re-designed my model to make it more DDD oriented. I was probably missing a level of abstraction and I was also misusing domain services.

In my invitation system admins can only invite:

  • users that are not already invited
  • users that are not already in the system (=already a member)

This flow involves two entities Invitation and User.

In the new design, I want to implement two new aggregates:

InvitationDirectory which contain a list of invitations made by a specific "client" (should be a collection of 0-10 items max).

Adding or deleting an invitation would be made through this aggregate.

ProfileDirectory will list all profiles associated to an email address.

The code should look like this:

public class InvitiationList : IAggregateRoot
{
    private IList<Invitation> _invitations;

    public void Add(Invitation invitation, ProfileDirectory directory, User creator)
    {
        // Check + business logic + could also create the invitation here
        _invitations.Add(invitation); 
    }

    public void Delete(InvitationId id)
    {
        _invitations.Remove(...)
    }
}

Currently my aggregate root is keeping a reference to a list of entities. Is this a good practice?

Thx

GRASP Indirection vs Mediator Pattern

What is the difference between GRASP Indirection and Mediator Pattern? I've tried googling but did not find the information.

samedi 23 juin 2018

Seach for pattern in dataframes

I have got a huge csv file which contains data about a bicycle being driven. So I got a time column in seconds and a Speed column. I would like to check for specific pattern in the data, in order to conclude what happend on the road.

For example driving torwards a traffic light:

I got this so far:

import pandas as pd

df = pd.read_csv('.csv', usecols = ['time', 'speed']) 
df['accelerating'] = df['speed'].diff() > 0

And I want something like this:

  df_traffic_light = df.loc[df['speed'] < 15 & accelerating == False #driving torwards the traffic light; 
    & df.loc[df['speed']< 1 #getting really slow or Standing still;
    & df.loc[df['speed']  > 5 & accelerating == True #for light switched to green and starting again 

Expected Output:

         time     speed  acceleration
0   5.000         14.0          false
1   7.056         12.0          false
2   10.097         8.0          false
3   12.131         1.0          false
4   14.165         0.0          false
5   16.201         0.0          false
6   18.236         2.0          true 
7   20.267         4.0          true

I tried it with dataframe.rolling but didnt work out quite well. Any ideas how I solve this?

How to print a multiple characters given variable number times?

Suppose if I want to print ".|." for (2k+1) times. Below is my snippet of code. How to do that? It is throwing a syntax error.

for k in range(0,n/2):
        print('.|.' * (2k+1))

Design Business House Game with design and proper class and interface implementation

Please find link of problem statement below

https://www.c-sharpcorner.com/forums/design-business-house-game

i have tried strategy pattern but interviewer was not satisfied. he was telling its not following open close principles

Where to put data validation in ADR pattren?

Where to put data validations in Action–domain–responder architectural pattern? What I am trying to do for now is something like this:

|- app/  
   |- Console/  
      |- Commands/  
   |- Events/  
   |- Exceptions/  
   |- Http/  
      |- Middleware/  
   |Blog
      |- Actions/  \\Sned data to a Service then recive data to be handled by a Responder
      |- Domain/  
          |- Models/  
          |- Services/  
      |- Responders/   
   |- Jobs/  
   |- Listeners/  
   |- Providers/  
|- database/  
   |- factories/  
   |- migrations/  
   |- seeders  
|- config/  
|- routes/  
|- resources/  
   |- assets/  
   |- lang/  
   |- views/

For validation I want to use FormRequest to handle that. Should I put it inside Actions?

vendredi 22 juin 2018

regex for symbol or nothing

I have a string where I need to parse the values such that it some times exist between[''] and sometimes not.

Eg:

Input
    1. blah .... REASON: ['elm H1MM_rr'], blah ....
    2. blah .... REASON: elm H1MM_rr, blah .... 
    3. blah .... REASON: elm H1MM_rr. 
    4. blah .... REASON: ['elm H1MM_rr']. 

The elm H1MM_rr is just an example here. It could be any string after REASON:

I tried REASON: ([^,. ]+)")but this still not working for ['']

Output I am looking for = elm H1MM_rr

Can some one suggest me a regex(java pattern) which can work for both strings ?

Some errors appeared during apply a practical example to Builder design pattern

I have written a code which applies the "Builder" design pattern but some errors appeared:

The code:

class Builder {
public:
    int m_suger;
    int m_cup;
    string m_flavour;

    Builder* sugar(int sugar) {
        this->m_suger = sugar;
        return this;
    }
    Builder* cup(int cup) {
        this->m_cup = cup;
        return this;
    }
    Builder* flavour(string flavour) {
        this->m_flavour = flavour;
        return this;
    }
    Tea* build() {
        return new Tea(this);
    }
};

class Tea {
public:
    int m_suger;
    int m_cup;
    string m_flavour;

    Tea(Builder* b) {
        m_suger = b->m_suger;
        m_cup = b->m_cup;
        m_flavour = b->m_flavour;
        cout << "Hot " << b->m_cup << " cup of tea is comming!, with " << b->m_flavour << endl;
    }
};

int main(int argc, char *argv[]) {
    Tea* mintTea = new Builder()->cup(2)->sugar(3)->flavour("mint")->build();
    return 0;
}

DDD How to design services/aggregate roots involving related entities

I'm building an invitation system in which admins can only invite

  • users that are not already invited
  • users that are not already in the system (=already a member)

This flow involves two entities Invitation and User.

  • Deleting a user should not delete invitations he has sent
  • Updating the user's FirstName should not update all his invitations

This seems to indicate that Invitations and User should be added to two separated aggregates.

Then the only way to implement the logic described above is to use a domain service like IInvitationService. Am I right?

This interface could come with two methods:

public interface IInvitationService
{
    Task<Result> Create(Invitation invitation, CancellationToken token);
    Task<Result> Delete(Invitation invitation, CancellationToken token);
}

Finally, if I go for the service approach, I will have two possible "ways" to create invitations.

IInvitationRepository.Create() 
IInvitationService.Create()

Don't you think it is confusing?

Quickly determine subclass based on abstract class

I have a C++ base class CAbstrInstruction and a large number of direct subclasses:

class CAbstrInstruction { /* ... */ };

class CSleepInstruction: public CAbstrInstruction { /* ... */ };
class CSetInstruction: public CAbstrInstruction { /* ... */ };
class CIfInstruction: public CAbstrInstruction { /* ... */ };
class CWhileInstruction: public CAbstrInstruction { /* ... */ };
// ...

There is also a CScriptWorker that exposes a public method execute:

class CScriptWorker
{
    public:
        void execute (const CAbstrInstruction *pI);

    private:
        void doSleep (const CSleepInstruction *pI);
        void doSet (const CSetInstruction *pI);
        void doIf (const CIfInstruction *pI);
        void doWhile (const CWhileInstruction *pI);
        // ...
};

The implementation of the execute method currently looks like this:

void CScriptWorker::execute (const CAbstrInstruction *pI)
{
    const CSleepInstruction *pSleep =
        dynamic_cast<const CSleepInstruction *>(pI);

    if (pSleep != NULL)
    {
        doSleep (*pSleep);
        return;
    }

    const CSetInstruction *pSet =
        dynamic_cast<const CSetInstruction *>(pI);

    if (pSet != NULL)
    {
        doSet (*pSet);
        return;
    }

    const CIfInstruction *pIf =
        dynamic_cast<const CIfInstruction *>(pI);

    if (pIf != NULL)
    {
        doIf (*pIf);
        return;
    }

    const CWhileInstruction *pWhile =
        dynamic_cast<const CWhileInstruction *>(pI);

    if (pWhile != NULL)
    {
        doWhile (*pWhile);
        return;
    }

    /* ... */
}

This is very clumsy and takes O(log(n)) to invoke the correct private method. Is there any design pattern or language construct that simplifies this?

(Clarification: I could move the private execute methods do... into the instruction classes. The execute method would simply become:

    void execute (const CAbstrInstruction *pI) { pI->execute(); }

However, that's not what I want, since the instruction classes are supposed to be just the descriptions of the instructions while the implementation of the execute methods should be in the CScriptWorker.)

design pattern for iteration php

What would be the best way to implement a design pattern in OOP where you take an associative array and perform several changes to each iteration.

I was thinking it would be Iterator class and then injecting functionality?

Here is a simplified class showing the problem:

class Contacts {

    private $contacts = [
        [
            "name" => "Peter Parker",
            "email" => "peterparker@mail.com",
        ],
        [
            "name" => "Clark Kent",
            "email" => "clarkkent@mail.com",
        ],
        [
            "name" => "Harry Potter",
            "email" => "harrypotter@mail.com",
        ]
   ];

   function changeEmailDomain( {
        foreach($this->contacts as $key => $contact){
            str replace mail.com etc...
        }
    }

    function removeSurname(){
        foreach($this->contacts as $key => $contact){
            explode name field etc...
        }
    }

   function sortByName() {
        foreach etc...
   }
}

jeudi 21 juin 2018

Is deep copy necessary on passing an ArrayList to a copy constructor?

I'm trying to figure out the best way to implement the code I'm working on.

I have two options of how to pass the data to my constructor.

First way

private String ISBN;
private String title;
private ArrayList <Person>authors = new ArrayList<>();
private ArrayList <BookCategory>subjectCategories = new ArrayList<>();

/**
 * First constructor
 * @param isbn String
 * @param title String
 * @param authors ArrayList <Person>
 * @param categories ArrayList <BookCategory>
 * Calls the checkISBN method
 */
public Book (String isbn, String title,
        ArrayList <Person>authors, ArrayList <BookCategory>categories) {

    //call the checkISBN method
    boolean check = checkISBN(isbn);
    if (check ==true) {
        this.ISBN= isbn;
    }
    else {
        throw new IllegalArgumentException("Invalid ISBN");
    }
    this.title = title;
    for(int index =0; index<authors.size(); index++) {
        this.authors.add(authors.get(index));
    }
}

Second way

        private String ISBN;
        private String title;
        private ArrayList <Person>authors = new ArrayList<>();
        private ArrayList <BookCategory>subjectCategories = new ArrayList<>();

/**
 * First constructor
 * @param isbn String
 * @param title String
 * @param authors ArrayList <Person>
 * @param categories ArrayList <BookCategory>
 * Calls the checkISBN method
 */
public Book (String isbn, String title,
        ArrayList <Person>authors, ArrayList <BookCategory>categories) {

    //call the checkISBN method
    boolean check = checkISBN(isbn);
    if (check ==true) {
        this.ISBN= isbn;
    }
    else {
        throw new IllegalArgumentException("Invalid ISBN");
    }
    this.title = title;
    this.authors = authors;

Does it make a difference?

I'm not sure because it seems like it would be unnecessary to declare the Book with a copy of the Authors arraylist instead of the original arraylist.

What is the correct way to do this, and why?

How to design different structures with common parts using inheritance

I've searched a lot about this problem without finding any appreciable result (maybe because i don't have a clear idea of what to ask), then here we are... I have to design two structures derived from two different JSON which they have common parts:

{
  "data": 
    {
      "success": true,
      "updated_ids": [0],
      "not_updated_ids": [0]
    }
}

{
  "data": 
    {
      "success": true,
      "branch_ids":["0"]
    }
}

My idea is to create something like this:

class Response
{
    Data data { get; set; }
}

class Data
{
    bool success { get; set; }
}

class UserResponse : Data
{
    List<int> updatedIds { get; set; }
    List<int> notUpdatedIds { get; set; }
}

class BranchResponse : Data
{
    List<string> branchIds { get; set; }
}

Now my question is: How can i instantiate my two different classes? If I do new Response() i don't get the UserReponse or BranchResponse part and if i do new UserResponse() i don't get the Response part.

Basically i would like to instantiate a variable for each structure, populate it with all the values and then Serialize to create the Json.

Thanks in advance!

How to get data for user pemissions

I have been developing Case management system.I have roles 'Manager','Operator','Technical Member' and Case-categories.So Manager can see all cases,Operator can see cases which he created and Technical Member can see cases which he can access, so when I create Technical Member I check some case-categories which Technical Member can see.Is there any pattern for it that get data for user.I have developed as I check If User.IsOperator Then.... But I think it's not good resolution.

php cloning objects - one cloned object then contains not a cloned object. howto solve it?

I have a class which holds some objects. An important class needs also the holder of objects but when clonig the holder inside the important class is still the initial holder when constructed.

My question:

how can i make sure that the injected holder object in DD::_list gets updated with the new clones?.

I think there are several ways but i dont see a way how to get it automatically. Or how would you do it?

Btw: ALL is a context object, DD kind of backend controller. This situation came up with unittest when i tried to change the context and it fails obviously ALL inside DD is jailed.

<?php

abstract class abst {
    protected $_input;
    public function __construct() { $this->_input['i am'] = 'master'; }
    public function __clone() { $this->_input['i am'] = 'clone'; }
}

class AA extends abst {}
class BB extends abst {}
class CC extends abst {}
class DD extends abst {
    private $_all;
    public function __construct( ALL $obj, $params=array() )
    {
        $this->_all = $obj;
        parent::__construct();
    }

    public function getAll()
    {
        return $this->_all;
    }
}

class ALL extends abst 
{
    public function __construct()
    {
        $this->_list = array();
        parent::__construct();
    }

    public function __clone()
    {
        foreach ( $this->_list as $name => $obj ) {
            $this->_list[$name] = clone $obj;
        }
    }

    public function setObject( $object )
    {
        $this->_list[ get_class( $object ) ] = $object;
    }

    public function getObject( $name )
    {
        return $this->_list[ $name ];
    }

}
$all =  new ALL();
$all->setObject( new AA() );
$all->setObject( new BB() );
$all->setObject( new DD( $all ) );
$all->setObject( new CC() ); // late checkin

$dd = $all->getObject('DD');
// does dd->_all know about CC ?
$cc = $dd->getAll()->getObject('CC'); // yes, in this case
print_r($cc);
// print_r($all);

// what about clone? does dd knows changes of cc after a clone?
// No, it knows cc but it is the initial object, 
//changing c has no effect for DD
$cloneAll = clone $all; 

print_r($cloneAll);

mercredi 20 juin 2018

Consuming API with Spring Boot - desing pattern

I want to implement REST Api which will use another REST Api as data source. What design pattern to use? Normally I would use controller/service/DAO, but I am not sure if it fits in this example.

How to deal with 401s in React application?

I am creating a react SPA application and I am using tokens that are refreshed on every request to any authenticated route.

On 401/Unauthrorized for any of these AJAX requests, I prompt the user with a popup/modal that requests the user to login so that they don't have to lose the state of their current page.

I could redirect them to the login page and then back but they would lose any current state unless I persisted it somehow, but that seems like unnecessary complexity.

The problem is that after the initial failed AJAX request, more AJAX requests could occur. So if I just redo the initial failed AJAX request then it will not be correct. I'm thinking that I could save all the failed request promises and then re-resolve them after the user has re-authenticated.

Is the proper high level approach?

Sorting the String Array based on given pattern in Java

My input string array is like below:

String[] arr = {"2T1BURHE1JCO24154C", "2TABURHE1JC024154C", "JTDKARFP5H3055472C", "2T2BURHE1JCO24154C", "JTDKARFP1H3056246C"};

The output array should be as below:

           {"JTDKARFP1H3056246C", 
           "JTDKARFP5H3055472C", 
           "2TABURHE1JC024154C", 
           "2T1BURHE1JCO24154C", 
           "2T2BURHE1JCO24154C"}

Here the priority is given in the below pattern:

[ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789]

When I use the Arrays.sort(arr) in Java it sorts the array in dictionary pattern and gives the below output:

[2T1BURHE1JCO24154C, 2T2BURHE1JCO24154C, 2TABURHE1JC024154C, JTDKARFP1H3056246C, JTDKARFP5H3055472C]

How could I achieve this in Java.

Thanks.

Factory for client requests based on request identifier

In my program i'm getting requests from client via java socket. Each request have unique command identifier which corresponds to specified command on application side.

Now i have a class with very large switch in it, which creates instances of command classes depending on received command id. This class receives ByteBuffer with request data from client, and ClientConnection object(a class which represents connection between client and server). It reads ByteBuffer first two bytes, and gets corresponding command(instance of class that extends ClientRequest class) It looks like so:

public static ClientRequest handle(ByteBuffer data, ClientConnection client) {
    int id = data.getShort();  //here we getting command id
    switch (id) {
        case 1:
            return new CM_ACCOUNT_LOGIN(data, client, id);
        case 2:
            return new CM_ENTER_GAME(data, client, id);
        //...... a lot of other commands here
        case 1000:
            return new CM_EXIT_GAME(data, client, id);

    }
    //if command unknown - logging it
    logUnknownRequest(client, id);
    return null;
}

I don't like so large switch construction. My question is - is there some ways to refactor this code to make it more elegant? Maybe use some pattern?

Also, in future i want to try to use dependency injection(Guice) in my program, could it be used for instantinating ClientRequest instances depending on received id?

Thanks in advance!

How to use a Abstract Factory Pattern with bounded typed parameter?

I am trying to use Abstract Factory Pattern with the bounded typed parameter with an example as follows:

CageAbstractFactory.java

public interface CageAbstractFactory {
    public Cage<?> createCage();
}

CageFactory.java

public class CageFactory {
    public static Cage<?> getCage(CageAbstractFactory factory) {
        return factory.createCage();
    }
}

XxxCageFactory.java (Xxx = Lion, Rat, etc)

public class XxxCageFactory implements CageAbstractFactory {
    @Override
    public Cage<Xxx> createCage() {
        return new XxxCage();
    }
}

Cage.java

public abstract class Cage<T extends Animal> { 
    protected Set<T> cage = new HashSet<T>();
    public abstract void add(T animal);
    public void showAnimals() {
        System.out.println(cage);
    }
}

XxxCage.java (Xxx = Lion, Rat, etc)

public class XxxCage extends Cage<Xxx> {
    @Override
    public void add(Xxx r) {
        cage.add(r);
    }
}

Animal.java

public class Animal {
    public String toString() {
        return getClass().getSimpleName();
    }   

}

class Rat extends Animal {}
class Lion extends Animal {}

AFP.java (Main class)

public class AFP {

    public static void main(String[] args) {
        Cage<?> rc = CageFactory.getCage(new RatCageFactory());
        Cage<?> lc = CageFactory.getCage(new LionCageFactory());
        rc.add(new Rat());
        rc.showAnimals();
        lc.add(new Lion());
    }

}

At lines rc.add(new Rat()) OR rc.add(new Lion()) the below error appears:

The method add(capture#3-of ?) in the type Cage<capture#3-of ?> is not applicable for the arguments (Rat)

It seems there is a type conversion error from Cage<?> to Cage<Rat>/Cage<Lion>

But the problem is the CageFactory.getCage(CageAbstractFactory factory) is returning Cage<?> which is only decided at runtime by the choice of the CageAbstractFactory class that is passed as argument (i.e. LionCageFactory OR RatCageFactory)

Is it normal to share one table's data with many other tables without directly using foreign key

enter image description here

In relational database design, based on the ER modeling, there should be relationship between two relational tables. However, currently I have met a special design case shown in the picture above:

There is a shared table called shared_table(on the bottom of the picture), where the values in column text_value can be used by many other tables such as those presented on the upper side of the picture, say table1, table2, table3. The relationship is on base of the field table_name, on base of the value from which the text_value can be mapped to the tables on the upper side of the picture.

I am surprised about the design above, as there is actually no direct primary key and foreign key relationship between the shared_table and other tables. Moreover, the mapping of the table has to be computed programmatically, and thus it will be difficult to use the object-relational mapping framework.

Question: is this design an anti-pattern? shall we really need such design?

Delete a text in a row of a column if it doesn't start with date in R

I have an output from R with three columns. I'm trying to identify if the content of the cell in one column (sc2) starts with date, if not I'd like to delete the string in that column.

R Output

I'm still a learner, tried using a function to find date pattern and replace it with " "

del <- function(x, del){

   for (i in 1:nrow(fstat))
{
   datepat <- "([0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9])"

   datedetect <-str_detect(sc3,datepat) 

  if (fstat$sc3[i]== FALSE)
 {
   fstat$sc3 <- " "
 }
 }

 }

The code I tried maynot be perfect,but as I said, I'm a new learner.

Any help is appreciated.

Design Entry Gates with token counter and Complaint Counter

  1. There are two entry gates (Entry1 and Entry2) and one token counter (T1 and T2) for each gate.

  2. Customer needs to collect token from any of the token counter.

  3. Unique token should be generated concurrently. For example, if counter T1 generates token number 4 and at the same time, another token is being generated from counter T2, it should be 5. There should not be any inconsistency.

  4. There are two Complaint Counter (C1 and C2) and both of them have their individual display screen (D1 and D2 respectively)

  5. Display screen can display at most three numbers at a time. Same token number should not be displayed in both the screen.

  6. Customers with remaining tokens need to wait in Waiting area.

  7. Once Complaint will be resolved for any token, Display screen will remove that number and add new token number from waiting queue.

Problem Image

Can anyone suggest how to design the above problem.

Should Entities in Clean Architecture know of persistence mechanisms?

In the book 'Clean Architecture' (Robert C. Martin) p. 191, he states that "Entity is pure business logic and nothing else". I am unsure of how literal I should interpret this statement with respect to the entites knowledge of a persistence mechanism.

I am assuming the entity objects are stateful - that they manipulate the business data that they represent. If so, the persistence-layer must be informed of changes to that data, so it can persist those changes. Therefore; are the entities allowed to hold a reference to a persistence-interface (or a unit-of-work-interface, if a more elaborate design)?

I am inclined to think that an entity-object holding such a reference (and calling it from within the entity) would be something else than 'pure business rules'. But I have a feeling it does not count as long as the entities hold reference to an interface?

And if the entities should NOT hold reference to persistence-mechanisms, are there any other good patterns for persisting changes to business data?

Design pattern for a sequence of related operations

I have a use case where I need to process a request as follows

1) Authenticate the Request 2) Authorize the Request 3) Validate the message (Reads the database for the existing record and validates it) 4) Perform some asynchronous operations 5) Update the records in the database and notify the customer

The problem is I need to read the same record we read in step 3 in step 4 and step 5 Since this looked like a workflow I thought I can use the COR design pattern. However I do not want to read the database record again in step 4 and 5 and want to pass this from step 3 to step 4 and 5.

What is an elegant design pattern I can use for this workflow. Can you help me with giving some class/interface structure for this?

Multiple validation under single input type

I am working on a project. I have used [a-zA-Z]+ for only alphabetic input. I want to restrict a user to start with only (BS- or MSC-) and then input anything Below is the input type:

 <input type="text" class="form-control" placeholder="Enter Degree Name Example BS-IT" name="degree" required pattern="[a-zA-Z]+" title="Example BS-IT">

mardi 19 juin 2018

Decorator enhancing method internally called

I want to write a decorator that is able to modify a function called by the concrete component, the following code sample illustrates my problem:

In [2]: class Animal:
   ...:     def sound(self):
   ...:         raise NotImplementedError
   ...:         
   ...:     def speak(self):
   ...:         print(self.sound())
   ...:         

In [3]: class Dog(Animal):    
   ...:     def sound(self):
   ...:         return 'woof!'
   ...:     

In [4]: class Bigfy:
   ...:     def __init__(self, animal):
   ...:         self.animal = animal
   ...:         
   ...:     def sound(self):
   ...:         return self.animal.sound().upper()
   ...:     
   ...:     def speak(self):
   ...:         return self.animal.speak()
   ...:     

In [5]: dog = Dog()
   ...: dog.speak()
   ...: 
woof!

In [6]: big_dog = Bigfy(Dog())
   ...: big_dog.sound()
   ...: 
Out[6]: 'WOOF!'

In [7]: big_dog.speak()
woof! # I want 'WOOF!' here

The method that I want to enhance functionality is sound, but this method is not directly called by the client and is instead internally called by speak so all the wraps on sound take no effect.

Is it possibly to achieve what I want using the decorator design pattern? If not what design pattern I should take a look?

Additional info: I tried swapping the wrapped class sound reference to the wrapper sound method, that worked but I found it was a very bad solution.

Code Smells: Long parameter list vs data clumps

While I am reading a refactoring tutorials, a two code smells confused me, long parameter list smell, and data clumps smell, however what come in my mind is in data clumps the params are somehow related together, meanwhile in long parameter list, the params are unrelated.

Also to solve the above two smells we use slimier techniques which is parameter object, preserve whole object or extracting a class.

My question, do I understand the two smells correctly?

Thank you.

Design patterns in ASP.NET

I am looking for advise, where in development based on ASP.NET MVC/WEB API we can apply or using a design patterns? For example, when we work with controllers we are using a factory method by default.

Factory pattern, Avoid same switch case for different interface

I have a Model which Implements 3 different interfaces

public class CustomerRateSettingModel :  IBaseFactory, IHandleSearch, IHandleSearchAggregate

I am very new with implementing design patterns and trying to implement Factory pattern to create instances. But I am unable to find a proper way to avoid the identical Switch statements while writing Factory

  public static IHandleSearch GetClassInstanceForSearch(string className)
    {
        switch (className.ToLower())
        {
            case "customerratesettingmodel":
                return new CustomerRateSettingModel();

            default: return null;
        }
    }

    private static IBaseFactory ManufactureModel(string className)
    {
        switch (className.ToLower())
        {
            case "customerratesettingmodel":
                return new CustomerRateSettingModel();

            default: return null;
        }
    }

Is there is any right way to handle scenarios like that?

EditText with Specific Pattern

I am trying to code an EditText field to have a specific pattern. The pattern is:

P20_ _ / _ _ / _ _ _ _

What I would like is that when the user starts to type the characters take place of the underscores but the forward slashes remain.

I am a beginner but this seems to be quite challenging.

Here is what I have tried so far which gives me the P20 at the start but the characters does not take place of the underscores:

editPemacNo.setText("P20__/__/____");
    Selection.setSelection(editPemacNo.getText(), editPemacNo.getText().length());


    editPemacNo.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(!s.toString().contains("P20")){
                editPemacNo.setText("P20__/__/____");
                Selection.setSelection(editPemacNo.getText(), editPemacNo.getText().length());

            }

        }
    });

Can anyone help me?

Express.js Designing Error Handling

I'm stuck on how to design error handling in an Express.js application. What are the best design practices to handle errors in Express?

To my understanding, I can handle errors in 2 different ways:

First way would be to use an error middleware and, when an error is thrown in a route, propagate the error to that error middleware. This means that we have to insert the logic of the error handler in the middleware itself (note, the middleware here was purposely kept simple).

app.post('/someapi', (req, res, next) => {
    if(req.params.id == undefined) {
       let err = new Error('ID is not defined');
       return next(err);
    }
    // do something otherwise
});    
app.use((err, req, res, next)=>{
    // some error logic
    res.status(err.status || 500).send(err);
});

Another option is to deal with the errors on the spot, when the error happens. This means that the logic must be in the route itself

app.post('/someapi', (req, res, next) => {
    if(req.params.id == undefined) {
        let err = new Error('ID is not defined');
        // possibly add some logic
        return res.status(ErrorCode).send(err.message);
    }
    // do something otherwise
});

What is the best approach, and what are the best design practices for this?

Thank you

lundi 18 juin 2018

Destroying created objects from factory (dangling pointer issue)

Suppose I have a factory class with a creation method that creates objects and also has a shutdown option that invalidates all the created objects (so they cannot be used anymore).

something like that (C#):

public class MyFactory {
    public MyObject CreateObject() { ... }
    public void DestroyAllObjects() { ... }
}

The clients of this code create objects, cache the reference and use it. Objects can be either manually destroyed or will be destroyed by calling 'DestroyAllObjects' in the factory class.

The problem here is a 'dangling pointer' issue. How can I notify the client code that the cached object was invalidated and shouldn't be used anymore? I was thinking of either using callbacks (con: complicates client code) or check on each call that the object is still valid (con: complicates MyObject code + code dup).

I understand that in an ideal world the objects will destroy themselves, but the system has a requirement for a centralized shutdown method.

Would love to hear your thoughts if someone encountered a similar issue in the past.

What are disadvantages of using a Bridge pattern?

I could not find anything on the Internet and would appreciate your answers.

Thank you

Which of the method is more correct to call object's algorithm to execute conversion?

I have a strategy pattern with factories inside. I don't know how much architecture should be visible outside. Which of the method is more correct?

1.

converterStrategyContext.getStrategy(ProductConverterStrategy.class).convert(product, ShowProductDto.class)

2.

converterStrategyContext.getStrategy(ProductConverterStrategy.class).getFactory(ShowProductDtoFactory.class).convert(product)

3.

converterStrategyContext.convert(product, ShowProductDto.class)

Specifying fewer arguments means more operations inside methods and forces to store relational structures of strategies, factories and dto to which the object is to be converted

calling the class based on the value of parameter

I have the below interface

public Map<String, List<SSTU>> exceute(Map<String, String> SSTUInputparams) throws BuisnessRuleException;

and I have the below two implemetation classes of it

the very first class

public class firstClass implements SSTUbusinessRule
{

public Map<String, List<SSTU>> exceute(Map<String, String> SSTUInputparams) throws BuisnessRuleException {
}


}

and the second class

public class secondClass implements SSTUbusinessRule
{

public Map<String, List<SSTU>> exceute(Map<String, String> SSTUInputparams) throws BuisnessRuleException {
}


}

now my above code classes is being from some other part as shown below as they pass the parameters to my classes

HashMap<String,String> hm=new HashMap<String,String>();  
  hm.put("A,"aaa");  
  hm.put(NR,"I");   // **** so the value of NR key can be I , A OR B

Map<String, List<SSTU>> aSSTUMap =  firstClass.exceute(Map<String, String> SSTUInputparams);
Map<String, List<SSTU>> CcquirerSSTUMap =   secondClass.exceute(Map<String, String> SSTUInputparams);

now what change i need to bring in them is lets say in map the value of parameter NR is of type I then execute the first class execute method and if the value of NR is of type A then execute the second class and if the value of type NR is of type B then execute both first class and second class

Now please advise how to achieve the same as i think I have to read the hashmap first inside the classes and then should I decide.

Passing context to the execute method in command design pattern

Going through the Command design pattern I understand that we need to create a Command by setting the context via constructor and then calling the execute method to perform some action on the context. Example:

public class Command implements ICommand {

    Device device;

    public Command(Device device) {
        this.device = device;
    }

    public void execute() {
        this.device.turnOn()
    }
}

I was wondering that with this approach we will be required to create a new Command object for every device object we create. Will it be ok to pass the context and some parameters to the execute method? I am looking for something like:

public class Command implements ICommand {

    public void execute(Device device) {
        this.device.turnOn();
    }

}

Are there any issues with this approach?

Entity class with over 150 fields (members) in java

I have developed an application where I am worried about design I have used. So need experts opinion.

I have defined more then 150 fields in single entity class and all fields have data type String. Will it create any performance or memory leakage issue?

Some times I observer Meta space issue during deployment . Is this something related with my entity where I have defined over 150 fields in single entity class.

Since different modules of our project have many common fields. So to avoid duplicate fields , I merged them all in single entity.

Many Thanks

dimanche 17 juin 2018

Best way to abstract an iOS App for reuse in a different deployment

I'm looking to abstract an existing app of mine, which is a social media streamer (filtered for relevant audiences). I want to abstract in such a way that the app can be reused for multiple audiences through a separate App Store deployment - e.g. App1 streams YouTube Channel 1,2,3 or Twitter feeds 1,2 and I want to build a new app (reusing most of App1) that streams YouTube Channel 4,5,6 or Twitter feeds 3,4.

I realize that this is as easy as changing the channel IDs or twitter handles, etc. However, what I want to know and learn is the best practice for such an abstraction? Moreover, abstracting the code would be easier to manage once I have multiple apps while upgrading, etc.

Some possible options that I could think of was:

  1. Creating Global Variables to store the channel names/ twitter handles
  2. Storing these variables into a info.plist or a new plist
  3. Any other?

I want to follow some best practices and also aim to improve the application performance while doing so.

Any help would be appreciated. Thanks in advance.

Pattern where implementations register themselves in a object registry

I have several classes that implement an abstract class "Product". To follow the Open-Closed-Principle I would like the implementation classes in a way that they register themselves in a ProductRegistry singleton object. When adding new "Product" classes, it should be sufficient to write them or put them in the class path without having to touch the ProductRegistry class.

Below are my first steps but it seems that the objects are lazy-initialized. Can I change that? Or should I use a init-block in every subclass? (didn't like that approach as it's easy to forget).

 abstract class Product {
    val id : Int

    constructor(id : Int) {
        println("ctor with id=$id")
        this.id = id
        ProductRegistry.register(this)
    }
    abstract fun getColor(): String
 }

object BrownProduct : Product(2) {
    override fun getColor() = "brown"
}

object ProductRegistry {
    private val registry = HashSet<Product>()

    fun register(product: Product) {
        println("Registering: $product")
        registry.add( product)
    }

    fun fromId(id: Int): Product {
        return registry.filter { it.id == id }.first()
    }
}

Test:

class TestProdFac {
    @Test
    fun test1() {
        // println(RedProduct) <- if called before, then test works
        assertEquals(RedProduct::class, ProductRegistry.fromId(1)::class)
    }
}

Spacy rule-based matcher pattern syntax questions

I am using the rule-based matcher in spacy to look for some patterns in a text. This is an example:

pattern = [{'POS':'DET'},{'DEP':'nsubj', 'OP' : '+'}, {'LEMMA':'can'},{'ORTH': 'but'},{'ORTH': 'need'},{'ORTH': 'not'}

I want to make my query more efficiënt, so what I want to do is:

  1. specify that the dependency of a certain tokens is 'nsubj' OR 'nsubjpass', so adding the option 'DEP':'nsubjpass' to {'DEP':'nsubj', 'OP' : '+'}
  2. add to my query that at a certain position 'zero or more tokens' can occur. {'OP':'*'} does not appear to work for this.

My questions thus relate to syntax and the spacy documentation offers little to no help here.

Any ideas on how I can write these queries?

Many thanks!