mardi 31 juillet 2018

Is this Singleton + Lazy Loading?

public class UserSession
{
   private UserSession()
   {
   }

   public static UserSession Current
   {
       get
       {
           var session= (UserSession)HttpContext.Current.Session["_userSession"];
           if (session == null)
           {
               session = new UserSession();
               HttpContext.Current.Session["_userSession"] = session;
           }
           return session;
       }
   }

   public User User { get; set; }
}

//USAGE
UserSession.Current.User

I'm trying to figure out what patterns are used in this code. My understanding is that this is a

  1. Singleton Pattern (in fact there is a private constructor) and a
  2. Lazy Loading (or lazy initialization?) because the way the GET is implemented.

I'm also confused by the

  1. UserSession property which is the same type of the class and the usage itself seems weird to me.

Can someone explain what is happening here?

Is below implementation of Abstract Factory Design Pattern is correct?

#include<iostream>

using namespace std;

//Abstract Product A

class Document
{

    public:

        virtual void createDocument() = 0;

};


class Word: public Document

{

    public :


        virtual void createDocument()
        {

            cout<<"Document Word is created"<<endl;         

        }
};


class Excel : public Document
{
    public :

        virtual void createDocument()
        {
            cout<<"Document Excel is created"<<endl;            
        }
};

//Abstract Product B


class VideoFile
{

    public:

        virtual void createVideoFile() = 0;

};


class VLC : public VideoFile
{

    public :

        virtual void createVideoFile()
        {
            cout<<"VideoFile VLC is created"<<endl;         

        }
};


class AVI : public VideoFile
{

    public :

        virtual void createVideoFile()
        {

            cout<<"VideoFile AVI is created"<<endl;         

        }
};



//////////////////////////////////////////////////////////////////////


class AbstractFactory

{

    public:

        virtual Document* createDocFiles(string fileType) = 0;

        virtual VideoFile* createVideoFiles(string fileType) = 0;       

};


class ConcreteFactoryA : public AbstractFactory
{

    public:

        virtual Document* createDocFiles(string fileType)
        {

            if(fileType == "Word")
                return new Word();
            if(fileType == "Excel")
                return new Excel();
        }

        virtual VideoFile* createVideoFiles(string fileType)
        {

            if(fileType == "VLC")
                return new VLC();
            if(fileType == "AVI")
                return new AVI();
        }

};


class ConcreteFactoryB : public AbstractFactory
{

    public:

        virtual Document* createDocFiles(string fileType)
        {

            if(fileType == "Word")
                return new Word();
            if(fileType == "Excel")
                return new Excel();
        }

        virtual VideoFile* createVideoFiles(string fileType)
        {

            if(fileType == "VLC")
                return new VLC();
            if(fileType == "AVI")
                return new AVI();
        }

};



int main()
{

    AbstractFactory *ptrAbFac = new ConcreteFactoryB();

    Document *ptrDoc =  ptrAbFac->createDocFiles("Excel");

    ptrDoc->createDocument();

    VideoFile  *ptrVideoFile = ptrAbFac->createVideoFiles("VLC");

    ptrVideoFile->createVideoFile();

}

(MVC/MVVM) What is the reason behind creating a separate view model for each view?

I've heard many people state that every view should have it's own view model, but, IMHO, it creates a bit of a mess with a lot of unnecessary classes in the working tree. I know that I should avoid submitting redundant data into views, but is it that much of a sin to reuse a view model across 2 or 3 views? If so, what are the long term benefits of such tedious-looking work?

design pattern issues with extended class and interface in Java

So I have this class called as BaseUtils. This is inherited by two classes now. But, in future it will be inherited by upto 5 or 6 classes. Let's call one of the child class as SubUtils.

This SubUtils implements an interface - UtilInterface.

I have four methods in UtilInterface:

sendRequest()
prepareHeader()
getClientId()
setClientId()

I implemented two methods (getClientId and setClientId) of this in the base class - BaseUtils. And the other two I implemented in SubUtils.

I somehow feel I made a design flaw.

Am I doing it the correct way?

A trouble with design of game project

I have a trouble. I'm learning programming with in home and university about one year. Now, in summer, I studying on the free courses called "Summer school" in one friendly IT-company. I developing ascii-roguelike in Terminal using CXX lang and NCurses library for Linux. We were advised to use the Entity-Component-System design pattern. Or, at a minimum, it's good to design a good class hierarchy. And also use other patterns, such as the prototype, IOC container, State Machine, Route Machine, and so on. To date, I'm in an absolute dead end: I have a ready-made piece of the game, but everything in it is very strongly connected. I absolutely do not know where to start, the implementation of the ESC looks very complicated, today I spent a whole day reading articles and code, in the end I did nothing at all. Advise, where to start, what to do? Can I draw a diagram of entities, components and systems on paper? Or how, what? There is a poorly written piece of the game, there is a clear task, there are recommendations for patterns that are desirable to use, there are teachers who do not explain for hours, they need to be approached with good questions. Maybe someone has something to share, to help.

PS sorry for my bad language

Calling private methods from inside the constructor in Java

I have the following class:

package com.tesco.demandforecasting.group8.choprachap7;

import java.util.ArrayList;

import com.tesco.demandforecasting.group8.utils.MathOperUtils;
import com.tesco.demandforecasting.group8.utils.RegressionUtils;

import lombok.Getter;

/**
 * This class if used to find seasonality factor of each period, as explain in
 * the chapter See https://kelley.iu.edu/mabert/e730/Chopra-Chap-7.pdf for the
 * explanation
 */
@Getter
public class ChopraChap7SeasonalFactorsCalculator {

    private double[] regressionParams;

    private int sales_size;
    private int periodicity;

    private ArrayList<Integer> sales;
    private ArrayList<Double> deseasonalisedData;
    private ArrayList<Double> deseasonalisedDemandUsingRegression;
    private ArrayList<Double> seasonalityFactors;

    public ChopraChap7SeasonalFactorsCalculator() {

        this.sales = new ArrayList<>();
        this.deseasonalisedData = new ArrayList<>();
        this.deseasonalisedDemandUsingRegression = new ArrayList<>();
        this.seasonalityFactors = new ArrayList<>();

        this.sales.add(8000);
        this.sales.add(13000);
        this.sales.add(23000);
        this.sales.add(34000);
        this.sales.add(10000);
        this.sales.add(18000);
        this.sales.add(23000);
        this.sales.add(38000);
        this.sales.add(12000);
        this.sales.add(13000);
        this.sales.add(32000);
        this.sales.add(41000);

        this.sales_size = sales.size();
        this.periodicity = 4;

        calculateSeasonalityFactors();
    }


    private void calculateSeasonalityFactors() {

        .......
        .......

        this.seasonalityFactors = seasonalityFactors;
        this.deseasonalisedDemandUsingRegression = deseasonalisedDemandUsingRegression;
        this.deseasonalisedData = deseasonalisedData;

    }

}

I want to expose the class fields to external classes, using their respective getters. But, the problem is that those fields attain any value only after the ChopraChap7SeasonalFactorsCalculator() method is called. So, what I have done here is call the method as soon as an object of the class is created. Of course, this will work, but is this good design pattern?

Supposing I would not have called the method from the constructor. So, if we have the following code is some other class:

ChopraChap7SeasonalFactorsCalculator calc = new ChopraChap7SeasonalFactorsCalculator();
calc.getDeseasonalisedData();

This will return to me any empty array list. How do I ensure that the method is called before any field is accessed?

What would be the best design pattern in my case?

A better way than looping and calling functions that loop and call another functions

I have a message (string) that is composed of transactions that is composed of groups that is composed of elements.

I there a better way to parse such message than looping and calling functions that loop and call another functions that loop and call another functions because I find the following is silly:

class Parser:
  def parse_msg(self, msg):
    trans = re.findall(trans_pattern, msg)
    for t in trans:
      self.parse_trans(t)

  def parse_trans(self, trans):
    groups = re.findall(groups_pattern, trans)
    for g in groups:
      self.parse_group(g)

  def parse_group(self, group):
    elements = re.findall(element_pattern, group)
    for e in elements:
      self.parse_element(e)

  def parse_element(self, e):
    pass

Is there a better way/design-pattern that I can approach this with?

How to make scala List of Any have a mandatory attribute?

I'm new to scala and OOP in general, therefore I apologize in advance if the question is stupid, but I really don't know how to find what I'm looking for.

I have the following code

case clase MyClass(id: Int, active: Boolean)
case class MyOtherClass(name: String, active: Boolean)


private def myMethod(active: Boolean, list: List[MyClass]): List[MyClass] = {
  if(active){
      list.filter(_.active == true)
  }else{
      list.filter(_.active == false)
  }
}

Ok now, what I want to do is to make this "myMethod" take a List of "Any" instead of a specific class as long as it has an "active" attribute. How should I go about it?

For instance, the class:

 case class MyThridClass(name: String)

wouldn't work since it doesn't have an "active" attribute

Good design for a reusable class with many derived classes

I have a class that will serve as the base class for (many) other classes. The derived classes each have a slight variation in their logic around a single function, which itself will be one of a set group of external functions. I aim to have something which is efficient, clear and will result in the minimal amount of additional code per new deriving class:

Here is what I have come up with:

// ctor omitted for brevity

// CRTP
template<class DERIVED>
class Base
{
public:
    void process(batch_t &batch)
    {
        if (previous) previous->process(batch);
        pre_process(batch);
        proc.process(batch);
        post_process(batch);
    }

protected:
    // no op unless overridden
    virtual void pre_process(batch_t &batch) {}
    virtual void post_process(batch_t &batch) {}

    Processor proc;
    Base* previous;
}

  • Expose the 'process' function which follows a set pattern
  • The core logic of the function is defined by a drop in class 'Processor'
  • Allow modification of this pattern via two virtual functions, which define additional work done before/after the call to Processor::proc
  • Sometimes, this object has a handle to another which must do something else before it, for this I have a pointer 'previous'

Does this design seem good or are there some glaring holes I haven't accounted for? Or are there other common patterns used in situations like this?

GoLang - given this Worker-API, how do I create an infinite loop of Jobs?

since I wasn't able to find anything about my specific problem, I'm going to ask this for myself here.

I've got this API for workers in Go:

package workerapi
import (...)

var MaxWorkers int = 1 << 16

type Job interface {
    Run()
}

type Pool struct {
    workers  sync.WaitGroup
    jobqueue chan Job
}

func NewPool(n int) (*Pool, error) {
    if n <= 0 {
        return nil, fmt.Errorf("worker: number of workers(n=%d) is <= 0", n)
    }
    if n > MaxWorkers {
        return nil, fmt.Errorf("worker: number of workers(n=%d) is > MaxWorkers(%d)", n, MaxWorkers)
    }

    p := &Pool{jobqueue: make(chan Job)}

    p.workers.Add(n)
    for i := 1; i <= n; i++ {
        go p.worker()
    }
    return p, nil
}

func (p *Pool) worker() {
    for job := range p.jobqueue {
        job.Run()
    }

    p.workers.Done()
}

func (p *Pool) SubmitAndWait(jobs ...Job) {
    for _, job := range jobs {
        p.jobqueue <- job
    }
    close(p.jobqueue)
    p.workers.Wait()
}

My task is now to build an infinite loop of Jobs. This is, what I have so far:

package workertest

import (...)

type job struct {
    id int
    // later on, these will contain more data
}

func (j job) Run() {
    sleep := rand.Intn(100)
    fmt.Printf("job %3d: Start   (%dms)\n", j.id, sleep)
    time.Sleep(time.Duration(sleep) * time.Millisecond)
    // here some more calculation
    fmt.Printf("job %3d: Stopped (%dms)\n", j.id, sleep)
}

func Start(args []string) {
    nrJobs := len(args)
    const nrWorkers = 5

    fmt.Printf("Starting   %3d workers\n", nrWorkers)
    p, err := workerapi.NewPool(nrWorkers)
    if err != nil {
        fmt.Println(err)
    }

    fmt.Printf("Submitting %3d jobs\n", nrJobs)
    jobs := make([]workerapi.Job, nrJobs)
    for i := 0; i < nrJobs; i++ {
        jobs[i] = job{i + 1, args[i]}
    }

    fmt.Println("Submit and Wait ...")
    p.SubmitAndWait(jobs...)
    fmt.Println("Finished all jobs")
}

The code above runs every given Job once with 5 workers in total. My goal is to put a finished job into the jobqueue again. But I don't know, how to manage this. Any advice is welcome!

Best approach in making instance of a class when __init__ takes a lot of time?

I'm currently working on somekind of device handler. The idea is to use Observer design pattern.

Let's say for example you as a 'user' want to add a new device for everyone else to use and would be globally avaiable in scope of the program.

What I wanted to do is implement DeviceHandler base class which will be marked as singleton using decorator. There would be 3 publicly visible methods register, unregister and get_device_list.

Also I wanted to implement a base class Device which you as a 'user' must inherit in order that your 'device' can be registered. Using abc.ABCMeta and abc.abstractmethod I would force your class to implement 2 functions get_instance() and find_me(). find_me() returns either True or False (depending if your device is connected to the system or not), get_instance() returns obviously instance of your class.

When an instance of DeviceHandler is created, in the __init__ method daemon thread is created which is running __discover method with 1 second period. __discover basicly calls find_me() method of registered device and if method returns True then get_instance() is called XY times until valid instance of your class is obtained (one call per iteration).

What the problem is that my DeviceHandler class expects your __init__ method to be non-blocking. When I call get_instance() I either expect an instance of your class or somekind of error code that would inform me that your class is not yet instantiated and that get_instance() needs to be called XY times until I get valid instance of your class (you could implement some kind of state-machine inside your class).

I wanted to find out what is better approach in acquiring instance of your class. Should I force you to implement get_instance() method and then you would implement state-machine handling (if needed) inside that method or should i just lose that method and instantiate your class as usually YourDeviceClass() and then you would implement state-maching handling in the __init__ method?

How Phalcon design pattern works?

I am recently start working on Phalcon. It is very good framework. I am trying to understand the design pattern of this.

Suppose that i am working on Form module. There is a class named Text and i am using this as $text = new Text("field_name");, Text class in included from use Phalcon\Forms\Element\Text;. Now i checked this namespace directory and found the Text class but there are only a render function. Here it is-

namespace Phalcon\Forms\Element;

/**
 * Phalcon\Forms\Element\Text
 *
 * Component INPUT[type=text] for forms
 */
class Text extends \Phalcon\Forms\Element
{

    /**
     * Renders the element widget
     *
     * @param array $attributes
     * @return string
     */
    public function render($attributes = null) {}

}

Nothing is here for create a form element so i checked the parent class of Text but also this is inherited by an interface and its only define the all fucntions which present in its parent interface.

There are no defication for create a form elemet. Then how it's works? How it can produce the code for an form element?

I also find such things in another module also. Please explain, is this any design pattern in oops?

I also works in npm and also checked packages they also have same design pattern.

lundi 30 juillet 2018

Design Model based system for compile time

I have a system with few model classes, each one with another members, but the behavior of all models are same-

For example, all models are request input from user in this format: Hi, Please enter {MemberName} value as {MemberType}: And convert the input to MemberType.

Because this intended to be library, I want that in each model I can to access his members (or members-like) at compile time, not by myModel.get("memberName"), but rather by myModel.memberName or myModel.get(modelEnum.MemberName) or myModel.ListOfMember[0] or maybe Factory.getMember(myModel, SpecificModelMembersList[0]) etc..

I don't need to add or remove members in runtime, just create a good way to add them in compile time, and not change all the code for add member to model class.

How would you design it?

I work with C#.

Thank you and you can suggest an english fixes.

Python3 Application, how to replace bunch of nested loops to improve performance(reduce execution time)

I have an application which has a bunch of nested loops and if statements. I believe these are the necessary burden to handle dynamic and unexpectable random sequence arguments. Or maybe I don't know python that much. Most of the loops are used for string comparisons.

If anyone knows some design patterns or some alternative way to solve this, please give me some hint or links so I that I can study! Thank you

Design to dynamically apply filters on list of products

I need some of your inputs in deciding a right approach in following case.

I am currently working on a ecommerce application (An online shopping website). Here, on homepage of application, I have to display a list of products available in shop.

The end user has a facility of applying filters (include/exclude) to products list so that only the products satisfying the applied filter will be displayed.

So, my question is regarding the correct design for applying these filter in Java layer. Please note I keep all the data in-memory (hashmap) at Java layer. I just want to apply filters that are passed as an input from UI on this in-memory data store and return back the filtered results.

Can anyone please guide me, if there is any recommended way to handle this requirement? Any input is highly appreciated. Please let me know if more information is required in this context.

Aspect-Oriented Programming in 2018

I would like to know the state for Aspect-Oriented Programming in 2018.

I know that there exists an implementation of aspect-oriented programming for Java as AspectJ and Spring supports AOP but I have read somewhere that AOP seems to be more like an anti-pattern.

If there would be good blogs, talks or projects documenting the usage of AOP(preferably in Java), please let me know.

Multi layer API system architecture plan

I am currently planning on creating an application.

I want this application to run on Desktop, iOS and Android. What I have done so far is as follows:

  • SpringBoot API server which handles database fetching/posting. This server also handles the desktop webpages.
  • Flask API server which handles certain calculations to and from the Spring server.
  • The mobile apps will be made using react native.

The problem

I am going to need to handle user sessions (via a login).

Is there a single unified way of handling user sessions over all these applications?

Otherwise I am going to need 2 different SpringBoot servers. One to purely act as an unauthenticated API server to serve the main data, the other which will authenticate the user and call the other SpringBoot servers API's...

The React-native will have its own login implementation and then also call the unauthenticated SpringBoot server.

So is there a cross-platform login system that can reduce the need of having 2 Spring servers?

Thanks.

Best way to integrate pattern library in a CMS based web application?

Quick brief: Our UI designers team have used Pattern Library as a framework and designed the modules in terms of atoms, molecules etc. using mustache templates and json files as data.

We are planning to integrate the pattern library code-base to our solution (ASP.NET MVC and Sitecore CMS based) using following two options:

  1. Normal workflow: Pre-compile the pattern library code-base (mustache templates) using NPM and generate the compiled HTML templates. Further, use this generated HTML into our Razor Views and integrate the data points (JSON or Model properties).

  2. Automated workflow: Integrate pattern library code-base in our solution (by copy-paste all of the required templates). Then refer these templates path under our Razor views (similar to handlebars) and have a run-time compile mechanism where data will be provided by the MVC controller as a JSON format. I'm not sure if this approach is feasible but thinking about this only with the benefit of managing all the UI logic at one place.

Can anyone help and suggest what would be the best solution while integrating pattern library (front-end) with a web-application?

Thanks!

How do I destroy "diagonal" point-alignments?

I start with a set of n points (here n = 6) in the 2D plane: {(1, 1), (2, 4), (3, 6), (4, 3), (5, 5), (6, 2)}. By adding all x-coordinates with k = 6, I have a new set of 6 points: {(7, 1), (8, 2), (9, 6), (10, 3), (11, 5), (12, 2)}. I make the same with the new set of points and obtain: {(13, 1), (14, 2), (15, 6), (16, 3), (17, 5), (18, 2)}. I can continue until m ≤ 10 (here m = 3). In the image, one can see the structure of "diagonal" point-alignments {(12, 2), (10, 3), (8, 4)}, {(18, 2), (16, 3), (14, 4)}
I want to have only two points on each "diagonal "point-alignments.
Only movement parallel to Y-axis is possible. For example the point (1, 1) can move from 0 to 6 like this (1, 1)-->(1, 2), (1, 1)-->(1 3)...(1, 1)-->(1, 6).

How can I destroy “diagonal” point-alignments to improve the arrangement of points? I want to implement it with C++. Any help is greatly appreciated.

Scala design pattern - sealed trait with two generics, children method having same type object in arguments list

sorry if the title is not very explicative, but I don't know how to explain it. I'm a scala newbie and I'm struggling in finding a solution to my problem. Here's the snippet:

sealed trait Base[T, M] {
  var value: Option[T] = None

  def initialize(v: T): this.type = {
    value = Some(v)
    this
  }
  def combine[K <: M](other: K): M

}

class Child1 extends Base[String, Child1] {

  override def combine[K <: Child1](other: K) = {
    val c = new Child1()
    c.initialize(value.get + " - " + other.value.get)
    c
  }

}

class Child2 extends Base[Long, Child2] {
  override def combine[K <: Child2](other: K) = {
    val c = new Child2()
    c.initialize(value.get + other.value.get)
    c
  }
}


object Main extends App {
  val c1a = new Child1()
  c1a.initialize("a")
  val c1b = new Child1()
  c1b.initialize("b")

  val c21 = new Child2()
  c21.initialize(1)
  val c22 = new Child2()
  c22.initialize(2)

  val m1 = Map("child1" -> c1a, "child2" -> c21)
  val m2 = Map("child1" -> c1b, "child2" -> c22)

  m1("child1").combine(m2("child1"))
}

What I want to achieve is that each subclass of Base can be combined only with objects of the same type.

The compiler complains when calling the combine method due to a mismatch in the type of the argument. Is this a correct approach? Or the structure of the classes for my purpose is to be rewritten?

EDIT:

This should be ok as well:

sealed trait Base[T, M] {
  var value: Option[T] = None

  def initialize(v: T): this.type = {
    value = Some(v)
    this
  }
  def combine(other: M): M

}

class Child1 extends Base[String, Child1] {

  override def combine(other: Child1) = {
    val c = new Child1()
    c.initialize(value.get + " - " + other.value.get)
    c
  }

}

class Child2 extends Base[Long, Child2] {
  override def combine(other: Child2) = {
    val c = new Child2()
    c.initialize(value.get + other.value.get)
    c
  }
}

dimanche 29 juillet 2018

Update status field according to the datetime field in Yii2

I want to implement an Event Management System in Yii2.

I have a datetime property in event table that shows when the event start. I have another property in event table that shows status of event and it has three value NOT_STARTED , HOLDING and FINISHED.

I want to update status field according to datetime. Cron jobs maybe not a good suggestion because events may be very close in datetime and i can't run action in every minutes.

How should i do this?

Inheritance vs. Strategy Pattern

I'm learning about programming patterns and for our final assignment we were asked to build an "online store".

I was thinking about how to model the User which can either be Admin or Customer.

I thought about the Strategy pattern to model each individual User with their particular behaviors.

They don't share any behaviors so far, so the Admin can't addToCart and Customer can't registerNewProduct.

However, they could share behaviors / methods as the system evolves!

Furthermore, the User won't change it's type in run-time. I.e., once you log in as Customer, you can't log back in as Admin.

Even if they shared behaviors such as seeProductList, this could be achieved with good ol' inheritance, right?

Should I use Strategy, Inheritance or would you recommend another pattern?

If you need more information, please let me know! :)

Thanks in advance.

Where can I find material to understand/study, unistroke / multistroke gesture recognition ? C#

This is my first post and looking for some guidance. I wanted to to implement gesture recognition for varied shapes and symbols that would be drawn via touch on screen for a small project. I understand there are different tool kits etc out there and on asset store that will help implement this but ive gotten curious on how it actually works and cant find much online yet.

I was hoping someone with this knowledge or knowledge of where i can obtain such study material that would be in an easy-ish digestible format for me.

I currently programme in C# using unity engine and have had some experience in C++.

Thanks to anyone who can point me in the right direction whether it be books , papers or video tutorials!

What is appropriate design pattern

I have some problem on deciding wich design pattern solve my situation. My problem is as fallows: i have to build testing platform to perfome some tests on physicall devices the company i work for produces. So i have: 1) ITest interface, which is parent for all interfaces:

interface ITest
{
   string Description {get; set;}
   void Run();
}

So particular test should inherite from this interfase and implement Description property and Run method. 2) TestManager class, which holds the collection of tests to run. It also may perfome some actions on tests, say for example it has RunAll method which runs all tests it holds.

class TestManager
{
   public List<ITest> Tests {get; run;}
   void RunAll()
   {
       foreach (var t in Tests)
       {
           t.Run();  
       }
   }
}

Now suppose that some tests need some preparations before running. So i have subtype of ITest which have a preparation text for test:

interface IPreparableTest : ITest
{
   string PreparationMessage {get; set; }
}

This PreparationMessage is gonna be prompted to user in some way so that the user can perfome some actions on device we wanna test. But it is the TestManager's responsability to decide what tests need to be prepared and in what way the PreparationMessage is gonna be shown to user. The problem is that it holds the collection of ITest and therefore it have to distinguish between preparable test and ordinary test. Of course i could've written something like this:

RunAll()
{
   foreach (var test in tests)
   {
       if (test is IPreparableTest)
       {
          MessageBox.Show(((IPreparableTest)test).PreparationMessage);
       }
       test.Run();
   }
}

But i don't wanna write like this because it is not OOP style. I wanna use some pattern here, but i don't have any idea which one i should use. Also i don't wanna put the preparatation logic on test, because it's not the responsability of test, test should have only the information on how to prepare the device, but how this message is gonna be shown to user is up to TestManager. So basically i wanna learn the way to avoid the switch on type of object. I aprreciate if someone can help me on this issue! Thank you!

samedi 28 juillet 2018

How to know which design patterns are being used in my project?

Suppose I joined a new organisation and the template has already been created and they don't have any documentation regarding the project, how am I suppose to know what design patterns are being used in the project assigned to me?

How to determine the strength of class coupling?

How can I determine the strength of the coupling between two classes? Is there a way to order the couplings by their relative strength?

For example, let classes A and B be abstract and the class C be a regular class. Then are the classes A and B in the expression A extends B coupled stronger together than the classes A and C in the expression A extends C? Are the classes A and B in the expression A instantiates a child of B coupled stronger together than the classes A and C in the expression A instantiates C?

Has anyone found a way to formalize this?

C# MVC What is Dependency Injection?

C# MVC What is Dependency Injection ?

What is Inversion of Control(IoC) ?

What is Repository?

What is Design Pattern?

i need to good definition to understand, and the relationship of all with one another

any simple example contain of all

Thanks you UW

How to avoid a Circular Dependency

I have a class, let's call it A, which holds an array of a different class, called B. Each B class has a reference to the A class which holds it.

Let's assume each B is a button, and upon clicking I want to print to the number of "brothers" buttons this buttons has.

The way I do it now, is simply going to the A class via a saved reference in B and returning it's array size.

I think my design is poor since both classes, A and B, are aware of each other. What would be a better way of designing such a structure?

Thank you.

Java: reusing same Object variable to create multiple objects

First off, some pseudo code:

//case 1:
main {
    List<Foo> bar = new ArrayList;

    Foo baz = new Foo(params);
    Foo baz1 = new Foo(differentParams);
    Foo baz2... 
}

Foo {
    main.bar.add(this);
}

//case 2:
main {
    List<Foo> bar = new ArrayList;

    Foo baz = new Foo(params);
    baz = new Foo(differentParams);
    baz = new Foo..
}

Foo {
    main.bar.add(this);
}

I am wondering if case 2 is an okay design practice. Since in Foo I am storing the instance of the class in the list in main, I will never need the direct object variable baz1 during runtime, but will be iterating through the list to apply some logic to each object. So my question is, is it an alright practice to reuse the same variable to keep making new Object instances (like case 2)? Conventional practices would suggest to keep a separate variable for the objects as you make them (like case 1).

This question came up in my mind when thinking about memory and whether or not doing case 2 would save more memory compared to case 1 since you are not declaring a new variable each time.

How to apply design pattern to replace Switch condition code smell for below code

I have below implementation to find cardType.

public enum CardType{
CREDIT,DEBIT , LOYALTY;

}

class CardTypeChecker{
public String getCardTypeInString(CardType cardType) {
    return  convert(cardType)
}

protected String convert(CardType cardType) {
    switch (cardType) {
    case CREDIT:
        return CardType.CREDIT.name();
    case DEBIT:
        return CardType.DEBIT.name();
    case LOYALTY:
        return CardType.LOYALTY.name();
    default:
        throw new IllegalArgumentException("Provided CardType is NOT available.");
    }
}
}

Now i want to know how i can apply design pattern to remove this code smell of switch statement.

vendredi 27 juillet 2018

Is there a name for a design pattern that implements a workflow orchestration using messages passed through queues?

Basically, I want to implement a workflow like

        B0---C0
       /        \
 A ---B1-----C1--D----E----F
       \        /
        B2---C2

using only message queues. I'm thinking that every message will be sent to a forwarder/dispatcher that has logic like

switch message_result
   case A
        split to B0,..,BN and forward to service that processes Bis to Cis
   case Ci
        if is final Ci
            aggregate Cis into D and forward to service that processes D
        else
            add to collection of accumlated Cis
   case E
        do something with result and forward to F

Is there a name for this type of pattern?

replaceAll or regex java forward slash

I want to change the string "S/" to "S/." only whole word , I tried with Pattern.compile and Matcher.quoteReplacement. I didn't find the solution. please help me. Thanks you.

DDD Entity in orm and java

I started reading chapter 5 of E. Evans DDD and try to make head or tail of the concepts.

In context of ddd what is and what is not entity and what is value object ?

looking at Value object or entity object in my Hibernate mapping? - but it is about Hibernate, not DDD, I ask about DDD

  1. In above sample of hibernate OrderLine is Entity, but is OrderLine still a DDD entity ?
  2. And more generally, can we say that any jpa/Hibernate @Entity is DDD entity, or not ?
  3. It seems to me, that OrderLine is a good example of Jpa/Hibernate entity that is not a DDD entity, is it ?

If we for instance had used some object database we would possibly store Order togeter with it's OrderLines, wouldn't we ?

  1. In terms of relational databases could we say, that Jpa @Entity that is mapped in database as OnDeleteCascade is not a DDD Entity, but it is still a value object ?
  2. Is hibernate @Embedded always a DDD value object ? (seems yes, it has no identity)

Ok, and now other case with other doubts. Lets say that we have two different systems one in Java other in Python. One for billing other for marketing. Both of them have a Customer Entity.

  1. Do we say that BillingCustomer is the same DDD Entity as MarketingCustomer (assuming both of them represent the same Customer John Doe born 01.01.1980 wiht ssn 12-34-56)? This would imply that in java two different classes, even not having common parent (except from Object) can represent the same DDD entity. If so, how should equals be implemented in above classes ?
  2. Should java equals return true for two different java classes representing the same DDD entity ?

How to implement polymorphism in Angular in running time?

Component inheritance is quite straight forward in Angular >2, just a matter of extending the parent class:

import { ParentComponent } from './parent.component';

@Component({
  selector: 'child',
  templateUrl: './child.component.html'
})
export class ChildComponent extends ParentComponent {
}

This works pretty well for a lot of use cases.

Now, let's imagine that I have a parent class Person, and two children classes, Employee and Contractor. I don't know if a person is a contractor or an employee until I query the database.

So my question is, what is the best way to subclass Person based on a flag that is received at running time? Is there a design pattern that fits this use case?

Querying DB records based on permissions

I have a DB table, where the user should be able to query and retrieve (using my web search form) certain records inside it. When the user does the search, he should see the records that are assigned to:

1- him directly 2- his Group 3- shared with him from other users in the system

Currently, I'm doing multiple queries in the runtime to get the records according to the previous three conditions, and it's working, but I'm worried that when the application grows, doing multiple queries and combining their results is not an efficient approach...

What could be a best practice here?

C# Microservice CQRS & DDD

I 'm new to the CQRS & DDD patterns, I 'm trying to get a clear understanding in simple terms with project code, could you please help?

What are the common usecases of the visitor pattern?

I was looking for the common usecases for the Visitor pattern. I could found some examples in the internet, but they are rather basic and only explains the concept, not when this pattern may really save your time.

Do you have a real world example using such pattern ? (i.e in an existing java project in Github for example)

I don't see clearly what problem does it solve in a large scale and why a developer may use it ?

how to organize the code for an analytics solution with different algorithms?

So I´m currently creating an analytics solution that will:

  1. read the data from csv files
  2. clean, pre-process, normalize some fields
  3. apply different algorithms depending on the case (k-means, sales forecasting, etc)
  4. save results as csv files somewhere

I´m planning to have different standalone batch jobs without any dependencies among them and all of them would have the 4 steps described above. Which design pattern would you use to implement this in Python? strategy? Would you have a parent class called Analysis and use inheritance (like below)? any "more decent" solutions available?

class Analysis:
    def __init__(self, name):
        self.name = name
    def readData(self):
        print("read data")
    def cleanData(self):
        print("clean data")
    def etL(self):
        print("etl")
    def process(self):
        print("process")
    def saveResults(self):
        print("save results")

Design patter to refactor nested if else inside switch case

I have to refactor a bulky existing code. Gone through a lot of similar questions on SO and other sites, still confused. If anyone can put some light or any idea will be of great help.

There are 5 drop downs and I need to update the view based upon the slected values in drop downs. First drop down has following options:

"TOP DOWN BUDGET"
"TEMPLATE BUDGET"
"ORIGINAL BUDGET"
"REVISED BUDGET"

Second drop down has following options:

"Day"
"Week"
"Month"
"Quarter"
"Year"

Third drop down has following options:

"Details"
"Summary"

Fourth drop down has following options:

"Hours"
"Dollars"

Fifth drop down has following options:

 "StartDate"
 "EndDate"

Now code has following scenario:

public List<WorkPlanReport> XYZ(...){//opening of some method XYZ....

List<WorkPlanReport> workPlanReportList=null;
switch(first_Drop_Down_Value){

    case "TOP DOWN BUDGET":
        List<TaskDetails> timeLine=getTimeLine("firstDropDownA", second_drop_down_val, third_drop_down_val, fourth_drop_down_val);
        workPlanReportList=setWorkPlanByTimeLine(timeLine, "firstDropDownA", second_drop_down_val, third_drop_down_val, fourth_drop_down_val);
        break;
    case "TEMPLATE BUDGET":
        List<TaskDetails> timeLine=getTimeLine("firstDropDownB", second_drop_down_val, third_drop_down_val, fourth_drop_down_val, fifth_dd_val);
        workPlanReportList=setWorkPlanByTimeLine(timeLine, "firstDropDownA", second_drop_down_val, third_drop_down_val, fourth_drop_down_val);
        break;
    case "ORIGINAL BUDGET":
        List<TaskDetails> timeLine=getTimeLine("firstDropDownC", second_drop_down_val, third_drop_down_val, fourth_drop_down_val, fifth_dd_val);
        workPlanReportList=setWorkPlanByTimeLine(timeLine, "firstDropDownA", second_drop_down_val, third_drop_down_val, fourth_drop_down_val);
        break;
    case "REVISED BUDGET":
        List<TaskDetails> timeLine=getTimeLine("firstDropDownD", second_drop_down_val, third_drop_down_val, fourth_drop_down_val, fifth_dd_val);
        workPlanReportList=setWorkPlanByTimeLine(timeLine, "firstDropDownA", second_drop_down_val, third_drop_down_val, fourth_drop_down_val);
        break;

}

return workPlanReportList;
}// Closing of some method XYZ....

private List<TaskDetails> getTimeLine(String first_Drop_Down_Value, String second_dd_val, third_dd_val, fourth_dd_val, String fifth_dd_val){

    switch(second_Drop_Down_Value){

    case "Day":
        if(third_dd_val.equals("Details")){
            if(fourth_dd_val.equals("Hours")){
                if(fifth_dd_val.equals("startDate"){
                //prepare query & call DB for fetching days timeline for hours details of TOP DOWN BUDGET filtered by start date...
                }
                else// means endDate{
                //prepare query & call DB for fetching days timeline for hours details of TOP DOWN BUDGET filtered by end date...
                }
            }
            else{//means Dollars
                if(fifth_dd_val.equals("startDate"){
                //prepare query & call DB for fetching days timeline for dollars details of TOP DOWN BUDGET filtered by start date...
                }
                else// means endDate{
                //prepare query & call DB for fetching days timeline for dollars details of TOP DOWN BUDGET filtered by end date...
                }
            }   
        }
        else// means summary...
        {
            if(fourth_dd_val.equals("Hours")){
                if(fifth_dd_val.equals("startDate"){
                //prepare query & call DB for fetching days timeline for 'hours' "summary" of TOP DOWN BUDGET filtered by start date...
                }
                else// means endDate{
                //prepare query & call DB for fetching days timeline for hours summary of TOP DOWN BUDGET filtered by end date...
                }
            }
            else{//means Dollars
                if(fifth_dd_val.equals("startDate"){
                //prepare query & call DB for fetching days timeline for dollars details of TOP DOWN BUDGET filtered by start date...
                }
                else// means endDate{
                //prepare query & call DB for fetching days timeline for dollars details of TOP DOWN BUDGET filtered by end date...
                }
            }
        }
        break;
    case "Week":
            //....similar code as in case "Day" just here we need to fetch data week-wise
            break;
    case "Month":
            //....similar code as in case "Day" just here we need to fetch data month-wise
            break;
    case "Quarter":
            //....similar code as in case "Day" just here we need to fetch data quarter-wise
            break;
    case "Year":
            //....similar code as in case "Day" just here we need to fetch data year-wise
            break;
    }
}


private List<WorkPlanReport> setWorkPlanByTimeLine(List<TaskDetails> timeLine, String "firstDropDownA", String second_drop_down_val, String third_drop_down_val, String fourth_drop_down_val){

WorkPlanReport wpr=new WorkPlanReport();
// Here I have real mess..., Iterating the timeLine list and have switch case and inside switch case multilevel nesting of if else to decide which setter we need to use to set the value.

for example:

If it is "TOP DOWN BUDGET" in first drop-down, "Day" in second drop-down, "Details" in third drop down, "Hours" in fourth drop-down & "StartDate" in fifth drop-down, I have to call follwing code:

wpr.setTDBDetailsHoursByStartDate(taskDetails.getTDBDetailsByHourStartDayView());

If it is "TOP DOWN BUDGET" in first drop-down, "Day" in second drop-down, "Details" in third drop down, "Hours" in fourth drop-down & "EndDate" in fifth drop-down, I have to call follwing code:
wpr.setTDBDetailsHoursByEndDate(taskDetails.getTDBDetailsByHourEndDayView());

}

This code is more than 1000 lines, and I am deseparate to refactor it using some suitable design pattern.

WorkPlanReport & TaskDetails DTOs have few similar types of properties in common and many other different properties also.

I am not allowed to alter those DTOs because those are used in some related common code base.

Powershell - Print the line if the 2 patterns are found

I have the following lines:

<option title="ORACLEDB" selected="selected" value="1111">ORACLEDB</option>
<option value=""  selected="selected"></option>
<option title="TRINITY" value="3162">TRINITY</option>

And I would need to print it ONLY if "option title" and "selected" are found.

When I use:

select-string -pattern "option title","selected" -Path "C:\Users\am281h\Desktop\page.htm" -AllMatches

Then it prints me ALL the lines matching either "option title " or "selected", when the result should be only that first line.

Any suggestions please?

How to pass input argument from one python file to another

To simplify the problem, lets say I have 4 files. And right now I arrange them like the following

main.py (where I start the program)

global important_arg
important_arg = sys.argv[1]
if __name__ == "__main__":
    import worker_a
    import worker_b
    if important_arg == "0":
        worker = worker_a.worker()
        worker.run()
    elif important_arg == "1":
        worker = worker_b.worker()
        worker.run()

worker_a/worker_b.py

import main
import helper

class worker:
    def run(self):
        a = helper.dosth()
        b = helper.dosth_2()
        ....blah blah blah

helper.py (where worker_a and b both needed static function)

import main

important_arg = main.important_arg #This is not work I know, the problem is how to make this work.

def dosth():
   ...
   #I have tiny part need important_arg
   if important_arg == "0":
        print "This is worker A."
   elif important_arg == "1":
        print "This is worker A."
   ...

def dosth_2():
   ...

For sure in this pattern, my helper.py can no longer retrieve the important_arg from the main.py.

If I force it to run, no surprise,

The error will be

'module' object has no attribute 'important_arg'

How should I redesign the pattern, or anyway to pass that arg from the main.py to helper.py?

jeudi 26 juillet 2018

Utility : static class with static methods OR non-static class with static methods

Best design solution amongst the below for a Utility Class (say logger class):

  1. static class with static methods.
  2. non-static class with static methods with a private constructor (throwing method not implemented)
  3. non-static class with static methods having a singleton

I saw this answer but found it oversimplified & superficial.

Please elaborate. Language used :- C# (just for reference)

Interfaces or inheritance for DTO

I am designing a large set of DTOs in c# 7. Net 5. I want some of the DTOs to always have certain properties. For example, PersonDTO and LocationDTO should always have Id and Name properties.

Interface on DTOs seems odd and sometimes, abstract class on DTO seems wrong.

What is the best practice to impose constraints on my DTOs to ensure the DTOs have certain properties? Is base class with abstract properties better or an interface?

GROK Parsing Trouble- IP within brackets AND parentheses

I am having some trouble parsing the following log:

<14>Jul 26 13:37:17 NL-Syn1-RI Connection: User [SYNNAS\WIN7$] from [192.168.10.111(192.168.10.111)] via [CIFS(SMB2)] accessed shared folder [sysvol].

This is what I have at the moment for my GROK pattern:

<%{POSINT:syslog_pri}>(?(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+(?:(?:0[1-9])|(?:[12][0-9])|(?:3[01])|[1-9]) (?:2[0123]|[01]?[0-9]):(?:[0-5][0-9]):(?:[0-5][0-9])) ?%{SYSLOGHOST:log_source} %{WORD:service}: User [(?:%{WORD:user_domain})\?%{DATA:username}] from [%{IP:source_ip}|%({IP:source_ip})] via [%{DATA:protocol}] accessed shared folder [%{DATA:shared_folder}].

I am able to parse out everything up until "via [CIFS(SMB2)] accessed shared folder [sysvol]." The two fields "protocol" and "shared folder" display "null" on the GROK debugger. However, when splitting the log, beginning at "via", the two halves parse out perfectly fine with the current grok pattern. I tried many different ideas, but I haven't been able to find a solution.

Injecting A Factory Into A Class

I'm developing an application feature for generating some sorts of strings. I have an interface:

interface IStringGenerator
{
    string GenerateNext();
}

and for now I have implemented this interface in a class having a single constructor with one parameter:

class FixedLengthStringGenerator : IStringGenerator
{
    public FixedLengthStringGenerator(int length)
    { . . . }

    public string GenerateNext()
    { . . . }

    .
    .
    .
}

This implementation only generates the desired strings of a fixed given length length. GenerateNext() on each call returns a desired string, until there are no one left and then it returns null. Considering these, I need another implementation of IStringGenerator which can generate strings of length between a minimum and a maximum. I think it's natural to have something like this:

class MinMaxLengthStringGenerator : IStringGenerator
{
    int _MinLength;
    int _MaxLength;
    int _Length;
    IStringGenerator _StringGenerator;

    public MinMaxLengthStringGenerator(int minLength, int maxLength)
    {
        _MinLength = minLength;
        _MaxLength = maxLength;

        _Length = minLength;
        _StringGenerator = new FixedLengthStringGenerator(_Length);
    }

    public string GenerateNext()
    {
        if(_Length > _MaxLength)
            return null;

        string generatedString = _StringGenerator.GenerateNext();

        if(generatedString == null)
        {
            _Length++;
            if(_Length <= _MaxLength)
            {
                _StringGenerator = new FixedLengthStringGenerator(_Length);
                return _StringGenerator.GenerateNext();
            }
            else
                return null;
        }
        else
            return generatedString;
    }
}

But creating instances directly is not a good idea. Instead I can use a factory to get an instance of FixedLengthStringGenerator. But I still think it's not a good practice, because it depends on FixedLengthStringGenerator. And if I want to use another alternative class in the future, this way it's not possible to receive it from outside.

My question is whether it's right (from the patterns point of view) to inject a factory into my MinMaxLengthStringGenerator or not?

More precisely, consider

interface IFixedLengthStringGeneratorFactory
{
    FixedLengthStringGenerator Create(int length);
}

Should I declare MinMaxLengthStringGenerator's constructor like following?

public MinMaxLengthStringGenerator(int minLength, int maxLength, IFixedLengthStringGeneratorFactory factory)
{ . . . }

Regular expression for repeating pattern

I have text with the pattern: pagelimit=50&filtercolumn=Datacenter&filtervalue=abfg1&filtercolumn=MachineType&filtervalue=fg&filtercolumn=GPG&filtervalue=IPMI

I want to get back

  1. filtercolumn=Datacenter&filtervalue=abfg1
  2. filtercolumn=MachineType&filtervalue=fg
  3. filtercolumn=GPG&filtervalue=IPMI

There may be an unlimited amount of these.

I have tried a few things. I'm currently trying something like this:

(?:((filtercolumn=.*&filtervalue=.*)+),?)

But of course it doesn't work. I get:

  1. filtercolumn=Datacenter&filtervalue=vin1&filtercolumn=MachineType&filtervalue=sd&filtercolumn=APC&filtervalue=IPMI
  2. filtercolumn=Datacenter&filtervalue=vin1&filtercolumn=MachineType&filtervalue=sd&filtercolumn=APC&filtervalue=IPMI

Language is Golang

Make sure that functions are called

Im working on a project where we're creating many objects throughout the code base.

For some objects thus we decided to use factories to control the process of creating the objects and all their dependencies. This is an example of what we are trying to do:

class CreateBranchFactory implements CreateBranchInterface {

    private $branch;

    public function __construct() {
        $this->branch = new Branch();
        $this->branch->scenario = 'create';
    }

    public function createBranch($branchForm) {
        $this->branch->attributes = $branchForm->attributes;

        //Example of all the things that I need to do after creating my object
        $this->setOfficialNameAndPrinterName($branchForm->official_name, $branchForm->printer_name, $branchForm->name);
        $this->createDependencies1();
        $this->someOtherFunction();

        return $this->branch;
    }

    public function setOfficialNameAndPrinterName($offName, $printerName, $branchName) {
        $this->branch->official_name = $offName ?? $branchName;
        $this->branch->printer_name = $printerName ?? $branchName;
        $this->branch->save();
    }

    public function createDependencies1() {

    }

And to have a proper contract I created an interface for this. This interface specifies the functions that should be defined

interface CreateBranchInterface {

    public function setOfficialNameAndPrinterName(String $offName, String $printerName, String $branchName);

    public function createDependencies1();
}

My problem though, is that the contract is specifying all the functions that should be defined, but isnt controlling which functions should get called. Is there any design pattern that I can use, that makes sure that those functions get called??

Decorator Pattern (Private vs Protected)

I noticed that most of the examples use protected for the Instance that is being decorated. Could I use private too?

public abstract class CoffeeDecorator implements Coffee {
    protected Coffee decoratedCoffee;

    public CoffeeDecorator(Coffee c) {
        this.decoratedCoffee = c;
    }
    ...
}

Looking for feedback on a new printer design, (pseudocode) C++

I'm currently creating a new design for a printer service and I wanted feedback on how you guys think the current design is. This will be coded in C++03

I've tried to adhere to SOLID principles by giving every class/interface one responsibility and separating all functionality into separate interfaces.

The functionality which this printer will have (so far) is as follows:

  • Print Logos
  • Print Lines (horizontal)
  • Print Barcodes (1D or 2D (QR codes))
  • Print Text (Left, Center, Right Aligned), this text will also be formatted with a Font
  • Then there is a Printer class which holds the functions the outside world will call.

so yeah feedback is welcome (Below is the class design in pseudocode)

interface ILogo
{
    void PrintLogo();
}

class WatermarkLogo inherits ILogo
{
    void PrintLogo();
}

-----------------------------------------------------

interface ILine
{
    void PrintLine();
}

class PlainLine inherits ILine
{
    void PrintLine();
}

class DottedLine inherits ILine
{
    void PrintLine();
}

-----------------------------------------------------

interface IBarcode
{
    void PrintBarcode();
}

class OneDimensionalBarcode inherits IBarcode
{
    void PrintBarcode();
}

class TwoDimensional inherits IBarcode
{
    void PrintBarcode();
}

------------------------------------------------------

interface IText
{
    Font m_font;
    void PrintText();
}

class TextLeftAligned inherits IText
{
    void PrintText();
}

class TextCenterAligned inherits IText
{
    void PrintText();
}

class TextRightAligned inherits IText
{
    void PrintText();
}

class TextLeftRightAligned inherits IText
{
    void PrintText();
}

-----------------------------------------------------
enum FontStyleType
{
    Normal = 1,
    Bold = 2,
    Italic = 3,
    Underlined = 4
}

class FontStyle
{
    FontStyleType GetFontStyle();
}

enum FontFamilyType
{
    Arial = 1,
    Calibri = 2,
    TimesNewRoman = 3
}

class FontFamily
{
    FontFamilyType GetFontFamily();
}

class Font
{
    unsigned int m_size;
    FontFamily m_fontFamily;

    unsigned int GetFontSize();
    FontFamily GetFontFamily();
}

-----------------------------------------------------

class Printer
{
    IBarcode m_barcode;
    ILine m_line;
    IText m_text;

    void SetBarcodeType(const IBarcode& barcode);
    void SetLineType(const ILine& line);
    void SetTextAlignment(const IText& text);

    void PrintBarcode(const std::string& barcodeToPrint);
    void PrintLine();
    void PrintText(const std::string& textToPrint);
}

mercredi 25 juillet 2018

Calling Thread.Sleep in Subscriber thread causes Publisher thread to sleep

I have implemented Publish and Subscribe pattern in my application but when I called Thread.sleep() method in any one Subscriber or any one of my Subscriber throws exception then all others subscribers and publishers gets affected by this so how can I prevent this from happening.

I have created one small demo of above problem

Publisher Code

import java.util.Random;

public class Publisher extends Thread {

    Broker broker = Broker.getInstance();
    Random random = new Random();

    @Override
    public void run() {
        while (true) {
            System.out.println("Published " + new Timestamp(System.currentTimeMillis()));
            broker.updateSubscribers(Integer.toString(random.nextInt(250)));
        }

    }
}

Subscriber Interface

public interface Subscriber {

    public void onUpdate(String message);
}

MessageSubscriber code

import java.util.logging.Level;
import java.util.logging.Logger;

public class MessageSubscriber extends Thread implements Subscriber {

    Broker broker = Broker.getInstance();

    @Override
    public void run() {
        System.out.println("MessageSubscriber started...");
        broker.subscribe(this);
    }

    @Override
    public void onUpdate(String message) {
        try {
            System.out.println(message);
            sleep(1000);                    // called sleep affects the publisher too
        } catch (InterruptedException ex) {
            Logger.getLogger(MessageSubscriber.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

As you can see I have called sleep method in MessageSubscriber which also affects the Publisher and makes it sleep too for that duration

Edit added Broker Code

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author hemants
 */
public class Broker {

    List<Subscriber> subscribersList = new ArrayList<>();

    private Broker() {
    }

    public static Broker getInstance() {
        return BrokerHolder.INSTANCE;
    }

    private static class BrokerHolder {

        private static final Broker INSTANCE = new Broker();
    }

    public void subscribe(Subscriber s) {
        subscribersList.add(s);
    }

    public void unsubscribe(Subscriber s) {
        subscribersList.remove(s);
    }

    public void updateSubscribers(String message) {
        subscribersList.stream().forEach(subscriber -> subscriber.onUpdate(message));
    }
}

Main class to run above code

public class PubSubPattern {

    public static void main(String[] args) {
        Publisher publisher = new Publisher();
        publisher.start();

        MessageSubscriber messageSubscriber = new MessageSubscriber();
        messageSubscriber.start();
    }
}

How to determine the most efficient and adaptive/flexible module architect in python?

The overall objective of a task is to select a subgroup of people from the entire group of people. The selection process will be based on some criteria.

Say, the entire group of people comes from 2 different databases.

1) Data Hosp – contains all hospitalization records of patients from year 2000-2010, each row represents a hospitalization record. One patient can have multiple hospitalization records (multiple rows on different occasions).

2) Data Pharm – contains all drug prescription information of patients from year 2000-2010, each row represents a prescription record. One patient can have multiple prescription records.

I want to use different rules for the selection process at different times. For example, we can select the subgroup if patients meet any of the following rule-based conditions:

1) Select if a patient has three or more hospitalizations in 2000-2010,

2) Select if a patient has three or more prescription in 2000-2010,

3) Select if a patient has 1) but not 2),

4) Select if a patient has 1) and 2),

5) Select if a patient has 2) but not 1)… etc

I am simplifying the complexity of the rules drastically, so in practice, I would like to create my own python module called “select_patient” so that I don’t have to rewrite similar codes that many times.

I have a fairly good understanding in python basic and intermediate concepts including creating function and simple module, but I haven’t created very complex modules yet, so I don’t know what the best path is to construct this module. I also don't know if I may be unaware of some of the more advance concepts in python that are necessary to create what I want to create.

Also, how do I create a module that’s adaptive to slight variations? For example, in the above conditions, criterion 1) only involves Data Hosp, while criteria 3-5) involve both databases. Furthermore, say if I want to modify condition 1) by adding another condition such that the hospitalization has to occur in urban areas (and not rural) areas.

One design approach I am currently trying is to create a big module in which the parameters will spell out all the conditions in parameters. For example

class select_patients(param1, param2, param3, param4… param20):
    def __init__():
    def test_cond1():
    def test_cond2():

The vast number of parameters allow me to specify under what user-driven circumstance, the different condition will be applicable. But I found this to be very burdensome to specify so many parameters as soon as from the get-go.

Another approach I am thinking of is a piece-meal approach, where I am breaking down the tasks and creating smaller functions first. For example

def test_cond1():
def test_cond2():
def select_patients(param1, param2…):
    if XYZ: # apply test_cond1()
    else: # apply test_cond2()

Is one approach more preferable than the other?

Since I haven’t used inheritance and iterator/generator (or other advance python concepts) before, are they potentially useful for what I am trying to do?

Implementing MVVM from scratch [on hold]

I was learning about the MVVM pattern but some concepts have being hard to solidify in my head. In this cases, for myself, is usually good to implement a simple version of what I'm studying to fix the concepts in my head.

Unfortunately I could't found good resources on the internet about implementing a MVVM framework form scratch, only about how to use it; mainly in the windows platform.

TL;DR Does someone know of any good resources that teaches how to implement a MVVM framework from scratch?

Thanks in advance.

PS: My goal is not to implement a new framework to use in projects, but just to learn how its insides work. For a real project I would use an existing and tested framework.

Move from Monolith to Microservice Design

In our company we have reached a point where a monolith may not be the best solution. There is no need for improvement in performance, but due to the increasing modularity and customer-specific changes, the effort to operate the monolith is becoming more and more difficult.

The current situation:

The application runs centrally and provides and manages various data. Currently, all data are stored in a central database and are connected to each other by PKs and FKs. The data covers a broad spectrum such as material data, stock, orders and configuration.

Just as we imagine:

All individual parts should run independently of the other parts. That means orders, material, stock, configuration and logs are independent services that manage your data themselves. To keep the data up-to-date we wanted to use a message broker like RabbitMq. This should be done with C# and MSSQL.

So much for the initial situation and now for the questions 😊

  • Let's say we want to display data from two different sources on one UI. Does this require a new service that combines the data and makes it available to the UI?
  • What does it look like the other way around? For example, if the data is changed by the user, will the UI service simply forward it to the relevant service?
  • Let's assume we have services A and B which in turn contain data A and B. A is dependent on B, i.e. A contains B. What do the interfaces look like in such a case? Does each service get an externally visible interface (REST/WCF), which makes it possible to manipulate data or only A and B can only manipulate date over the message bus?
  • Is it common to have two interfaces, one external like WCF/Rest and one internal like RabbitMq?
  • Is there a "design pattern", Book, Websit that says, for example, as long as condition A then do it like this and otherwise like this? (For the Microservice Design)
  • Currently we use WCF for communication because only Windows clients are used and in my opinion it is quite easy to use. We would also like to stick to this for the external interfaces, but maybe there are alternatives that can do the same (including callbacks perhaps)?
  • There is also the question of rights management. Is there a simple pattern with roles, groups, etc. that can be applied to a microservice architecture? Authorizing every method call sounds very costly.
  • How is the data kept in the database? In case Service B needs data from Service A, will the data from A needed to run Service B be stored twice (at A and B) and changes will be transmitted from A to B via some kind of interface?
  • And last but not least, how is the program structured? So let's say I have type A objects on service A and I consume the service with service B, I don't want to copy the classes to service B in order to use it. Does a common project which contains transfer objects make sense here or does this contradict the design?

I know that many questions depend strongly on the intended use and do not make sense in some environments, however I would like to ask you to share your experiences because there are many different opinions on this topic on the Internet. And by the way, we don't need any scalability, because the workload is more or less low.

Manage messages with multiple consumers of one Kafka topic

I am implementing a workflow leveraging Apache Kafka where I have multiple producers and multiple consumers.

In a nutshell, something like an order processing workflow where:

  • Producer receives and publishes an 'Order' to a Topic. Consumer_1 takes the 'Order', validates it and publishes the same 'Order' to the same Topic.
  • Consumer_2 receives the 'Validated Order' and checks stock in Warehouse. Once confirmed it publishes same 'Order' to same Topic.
  • Consumer_3 receives 'Validated & Warehouse confirmed Order' and sends for dispatch to the same Topic etc...

I've created an object of type 'Order' for my consumers to process with State as a local variable that each consumer updates upon completion.

With the above approach of multiple Producers/Consumers and One topic I see an issue of maintaining state of my messages (validated, warehouse confirmed, dispatched etc), where each consumer has to process all messages and check that state corresponds to the current consumer's responsibility. Also with this approach all consumers will have to belong to different consumer groups in order to receive all messages (which is not ideal) and hence ack all messages (even those not destined for them).

Other approaches to this I thought about are creating multiple Topics (one per 'state', but in that case my 'Order' message will be used for publishing to multiple Topics, which seems to go against Kafka principles.

I could also create different 'types' of Orders, i.e. ValidatedOrder, WarehouseConfirmedOrder, DispatchedOrder whereby removing the state check in my consumers, but introducing a 'Type' filter instead, which seems to be very similar to my original state solution.

What are the best practices and alternative techniques one could apply here?

Any documentation on the above you could point me to?

How do I correctly use generics in this case?

Below is my Transformer Interface

    public interface Transformer<I, O extends State> {

    public O transformToState(I input);
}

This is one of my Transformer Impl

public class GoldTransformer implements Transformer<BusinessObject, Gold> {

    @Override
    public Gold transformToState(BusinessObject input) {
        GoldBO goldbo= (GoldBO) input; // redundant casting line
        //do some transformation with BO to make it a state with some business logic

    }
}

Here is my another Transformer Impl

public class SilverTransformer implements Transformer<BusinessObject, Sliver> {

        @Override
        public Gold transformToState(BusinessObject input) {
            SilverBO goldbo= (SilverBO) input; // redundant casting line
            // again do some transformation with BO to make it a state with some business logic

        }
    }

Both SilverBO and GoldBO Implements BusinessObject which is a marker interface. And Silver and Gold extend State. I really find the casting annoying and redundant is there a better way to use generics here? or a better pattern to use? I don't want to make any changes to state i.e. gold and silver.

how to find repeated patterns of numbers in rows of a matrix in matlab

I've searched the forum for my enquiry but I couldn't find anything related. What I'm looking for is this:

Say that I have a matrix with N rows (N is known) containing the same numbers but in different order in each row. I'd like to detect patterns of numbers in the different rows. For example if I have a matrix as below

1   2   3   8   9   7   4   5   6
1   3   2   7   8   9   4   5   6
1   2   3   5   6   7   4   9   8
1   2   3   7   8   6   4   5   9
1   2   3   4   5   6   7   8   9
1   2   3   7   8   9   4   5   6
1   3   2   4   5   6   7   8   9

a pattern is the sequence 1-2-3 in the rows 1,3,4,5,6 appeared 5 times, another pattern is the sequence 4-5-6 in the rows 1,2,5,6,7 appeared 5 times. Is there anything for this in matlab?

I hope I've explained well enough my question.

Concurrency pattern: worker with variable number of results

I want to create a worker pool in golang, to divide a big task in multiple jobs.

The problem is that the routines may produce multiple output as a result for the computation, so I cannot know in advance how many times I shall iterate over the results channel.

I know that I can use WaitGroup, but I was wondering if there is another pattern I can use, in order to let the main thread advanced on the computation and iterate over the results instead of waiting first every routine to be done.

Another solution I thought, which is not very elegant to me, is to create a Result struct or return an array of results. Since I can count the number of works, I know how many results arrays I'm gonna receive.

Confusing design pattern when creating a new parameter for the original function while using decorator

I'm using a decorator to shorten the functions that uses selected rows and the current row in PyQt-5. Here's the simplified decorator:

def call_with_selected_record(function):
    @functools.wraps(function)
    def wrapper(self):
        selected_rows = self.getSelectedRows()
        if selected_rows:
            function(self, self.currentRow())

    return wrapper

And the function looks like this:

@call_with_selected_record
def toggle_selected_records(self, row):
    doSomethingWithRow(row)
    return

Here's the confusing part for this design: When I try to use any function that uses this decorator, my IDE shows the row parameter as needed. But row parameter is satisfied by the decorator itself. So, whenever I try to use the toggle_selected_records function, I need to remember how its decorator works. Do I really need to check the wrapper of each decorator? Isn't this a bit confusing? Or is this the intended design for decorators? Nevertheless I came up with these solutions:

1-)Add this line to all functions that uses the same decorator:

row=self.currentRow()

So the function looks like this after the change:

@call_with_selected_record
def toggle_selected_records(self):
    row=self.currentRow()
    doSomethingWithRow(row)
    return

But this solution adds one line to all functions unnecessarily. It's redundant and beats the purpose of having a decorator.

2-)Replace all the row keywords in functions with args[1]. So the function looks like this after the change:

@call_with_selected_record
def toggle_selected_records(self, *args):
    doSomethingWithRow(args[1])
    return

This doesn't add any new lines to the function and eliminates the row parameter. But it creates a new confusion: *args doesn't do anything and it gives an error when a parameter is passed because of the wrapper. This solution also decreases the readability.

So, in short, I don't want to have a row parameter for the original function but want to use the row information that's provided by the decorator without adding something redundant to each function. What's the ultimate solution to this issue?

Handling sorted and filtered collections coming from APIs in a redux store

Redux guidelines suggest to

think at an app's state as a database

and to prefer key-based objects over arrays when it comes to store resources. This makes totally sense, since it simplifies 99% of the most common use cases when dealing with collections: search, find, add more, remove, read...

Unfortunately the downsides show up when it comes to keep a filterable and sortable collection of resources synched with APIs responses. For example a typical request:

GET /users?status=active&orderBy=name&orderDir=asc&lastID=1234&limit=10

will return a filtered, sorted and paged, list (array) of users. Typically the reducer will then take this array do something like:

users: {...state.users, keyBy(action.payload, 'id')}

This will merge new data with previously fetched ones breaking the computation done from APIS. The app must then perform a second, client-side, computation on the collection to reconstruct the expected list. This results in:

  • redundant computation (redo something that has been already done by the server)
  • duplication of logic (same filtering and sorting code deployed both client-side and server-side)
  • maintenance coast (client app developers must take the extra burden to keep filters and sort logic synched every time it changes on the backend to guarantee consistency)

Another downside, if you are implementing a sort of infinite loading, is that you must keep track of the lastID, since there is not way do deduce what is the last loaded id after results have been merged.

So the question:

What's the best approach to design stores and reducers that must deal with sorted/filterd/paged data fetched via APIs?

How to realize design pattern bridge

Program should create daily and weekly report of some shop. Report is created in sting and file format.

Where is here Abstraction and Implementation?

P.S. This is easy c++ task.Here isn't any hard realization.Just I want to understand what's Abstraction and what's Implementation

Static variable vs singleton

I'm making Java REST application. I wonder how should I implement my services - should I use static service variables for whole application or make services as singletons like it was made in Spring MVC. Is there any difference between singleton object and initializing object only once during application?

Constructor over-injection and Facade Service concept

I have a pretty simple interface which manages the update of business proposals, specifically during a nightly batch process each record is submitted here (but it might be used in other scenarios). This interface is used inside an EJB 2.0 Bean, which fetches records and "cycles" them. Beware names are translated from Italian to English so pardon possible errors. I also simplified some concepts.

public interface ProposalUpdateService {
    void updateProposal(final ProposalFirstType proposal);
    void updateProposal(final ProposalSecondType proposal);
}

The implementation of this interface has quite a lot of dependencies:

public class ProposalUpdateDefaultService implements ProposalUpdateService {
    private final ComplexService complexService;
    private final OtherComplexService otherComplexService;

    private final ProposalStep<Proposal> stepOne;
    private final ProposalStep<Proposal> stepTwo;
    private final ProposalStep<ProposalTypeTwo> stepThree;
    private final ProposalStep<Proposal> stepFour;

    public ProposalUpdateDefaultService(
            final ComplexService complexService,
            final OtherComplexService otherComplexService,
            final YetAnotherComplexService yetAnotherComplexService,
            final SimpleService simpleService,
            final OtherSimpleService otherSimpleService,
            final YetAnotherSimpleService yetAnotherSimpleService,
            final Converter<ProposalTypeOne, ComplexServiceType> converterProposalTypeOne,
            final Converter<ProposalTypeTwo, OtherComplexServiceType> converterProposalTypeTwo) {
        this.complexService = complexService;
        this.otherComplexService = otherComplexService;

        stepOne = new StepOne(yetAnotherComplexService);
        stepTwo =
                new StepTwo(
                        complexService,
                        otherComplexService,
                        yetAnotherComplexService,
                        converterProposalTypeOne,
                        converterProposalTypeTwo);
        stepThree =
                new StepThree(
                        simpleService,
                        otherSimpleService,
                        yetAnotherSimpleService);
        stepFour = new StepFour();
    }

    ...

As you can see this class encapsulate the update of a Proposal object, and this process is splitted in four phases. Those four phases my be arranged differently between different types of Proposal.

Here is the highly simplified implementation of those two updateProposal methods:

@Override
public void updateProposal(final ProposalTypeOne proposal) {
   stepOne.process(proposal);
   stepTwo.process(proposal);

   if (...) {
      stepFour.process(proposal);
   }
}

@Override
public void updateProposal(final ProposalTypeTwo proposal) {
   stepOne.process(proposal);
   stepTwo.process(proposal);
   stepThree.process(proposal);
   stepFour.process(proposal);
}

The two private fields

private final ComplexService complexService;
private final OtherComplexService otherComplexService;

are used for helper private methods.

As you can see this class just organize and delegate work, however it does depend on too many other classes. The same could be said for certain ProposalStep(s).

Would you accept this number of dependencies?
How would you refactor to simplify?

I've read about the Facade Service concept as a way to redure dependencies, and how I should group cluster of dependencies toghether, but here I don't really understand what to do.

I may group the Converter(s) and the Service(s) which uses them, but they'll be too many anyway.

mardi 24 juillet 2018

Is there a pattern to combine two classes provided by third party library?

I have two classes from third party libraries that have very similar functionalities lets call them class Car and class Bike. I cannot directly make changes to the class but I want to be able to abstract them so that I can use them like so

public bool drive(IDriveable vehicle)
{
    vehicle.Start();
    vehicle.Shift(Gear.Drive);
    vehicle.Accelerate();
    //so on...
}

Is there anyway I can do this?

Facade design pattern - partially implementing an interface across multiple classes

We're working on a small Android app and are required to implement a certain design pattern (Facade, Observer, Adapter, etc). We chose Facade.

The GUI wants to access different classes from the subsystem so to reduce coupling we're trying to use a facade interface to send those requests to the subsystem classes. Would this be a good case to use the facade pattern?

An issue that arose was each subsystem class needs to implement every method of the interface it implements. We don't want to do that; rather we want to spread that functionality across subsystem classes with each class implementing some methods of the interface. An idea I'm thinking we can do is to have a base 'mediatory' abstract class that implements the facade interface overriding every method with no implement, and then have subsystem classes extend the mediatory abstract class. Since it's an abstract class, it would allow for partial implementation of the methods across multiple classes, I think?

Is this advisable?

Physics Object Double Buffering

I've been working on a little game in python using a (very) basic physics engine I wrote. The original physics code was rushed, and so I've been cleaning it up and trying to make it less terrible. Here's the problem:

I wanted to make the collision detection (using SAT algorithm) decoupled from the collision response by having physics objects store their collision response function in a variable, which allows for different objects to behave as triggers, solid objects, force fields, etc. In doing this I had to make the response consist of two method calls (one for each object in a collision) which means that one call happens after the other. This causes problems because the changes to one object have an impact on the other object's response to the collision.

I've read about double buffering being used in displaying images and thought that it might be able to be used to solve this by buffering all changes to each object somehow and applying them after they have all been calculated. I've been having trouble coming up with a clean and flexible way of doing this. Does anyone know of a good way to deal with this non-simultaneous collision response?

(sorry if this is a wordy question, I felt that the background was required to make it clear what I was trying to do)

Pre-handle third party library method in Spring Boot

We are exploring Micrometer metrics collection library in Spring Boot 1.5.

Micrometer provides a static method in the Tag interface to create tags for metrics.

public interface Tag {
    String getKey();

    String getValue();

    static Tag of(String key, String value) {
        return new ImmutableTag(key, value);
    }
}

The implementation of ImmutableTag is as follows:

public class ImmutableTag implements Tag {
    private String key;
    private String value;

    public ImmutableTag(String key, String value) {
        requireNonNull(key);
        requireNonNull(value);
        this.key = key;
        this.value = value;
    }
...other methods...
}

Now, we are collecting some tags programmatically, and might end up with a null tag (which will throw an exception because of requireNonNull()). But on encountering a null, we are okay with replacing the tag value with a default string (say "unknown").

What is the best way to handle this?

I have thought of the following:

  1. Try / Catch: Surround all such statements in a try/catch block. I understand this can be expensive and difficult to maintain.
  2. Handle null on our end: Check for any null tag being passed, and replace it with default string. However, we will have a lot of such statements, and want to have some sort of configuration that this happens by default.
  3. Wrapper interface: Create a TagWrapper interface, replace null with default value, and call the Tag.of() method. Seems like the best option to me now, however, when this is no longer needed (maybe a method like this is introduced later in the library later), getting rid of the wrapper will include a lot of changes.

Is there some configuration in Spring that allows me to pre-handle third-party library methods without creating a wrapper?

SVG pattern change color of hovered element

I have a background with SVG pattern and I only want change the color of the hovered item, not all.

I've tried to use :hover on my polygon tag but it doesn't work.

svg:hover pattern polygon{
  fill:red;
  -webkit-transition: padding 0s;
}

polygon{
  -webkit-transition: all 0.75s ease-in;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>

  <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%">
    <defs>
      <pattern id="stars" patternUnits="userSpaceOnUse" width="100" height="100">
        <polygon points="50,9 60.5,39.5 92.7,40.1 67,59.5 76.4,90.3 50,71.9 23.6,90.3 32.9,59.5 7.2,40.1 39.4,39.5" fill="blue"/>
      </pattern>
    </defs>
    <rect width="100%" height="100%" fill="url(#stars)" />
  </svg>

</div>

Maybe I have to use JS but I don't know how. It's the first time I work with SVG, I've searched on the web but can't find anything helpful.

How to instantiate input based strategy pattern

The instantiation of strategy pattern is usually completely overlooked by the examples. Let's assume there is an input that defines which class to use. We'd have something along the lines of:

class Strategy {
    Strategy(){}
    virtual void runAlgorithm() = 0;
};

class A : public Strategy {
    A () {}
    static bool isA(char input){ return input == 'A'; }
    void runAlgorithm { /* Do A algorithm */ }
};

class B : public Strategy {
    B () {}
    static bool isB(char input){ return input == 'B'; }
    void runAlgorithm { /* Do B algorithm */ }
};

// Other algorithms

Strategy* createStrat(char input){
    Strategy* instance;

    // Define which algorithm to use
    if (A::isA(input)) {
        instance = A();
    } else if (B::isB(input)) {
        instance = B();
    } ...

    // Run algorithm
    instance.runAlgorithm();

    return instance;
}

As you can see, if we have multiple different algorithms this if/switch can get pretty big. Is there a pattern to make this code easier to humanly parse (i.e., a for loop and a call) without adding an array of pairs? The question could also be expanded to "How to instantiate an input based strategy pattern?"

Do not limit to this code, as it is just an example.

lundi 23 juillet 2018

Should we Deallocate memory before throwing an exception

I have an application which should throw an exception if it encounters a situation. Application aborts, excepted behavior.

Address sanitizer is reporting memory leaks for this scenario. Should I consider fixing the memory leaks in this case (or) Should I not do it as the application is terminating anyways and the memory will be reclaimed by the OS anyway.

Why self=[super init] ensure the singleton pattern?

I read many implementation of singleton pattern in Objective-C, and lots of the code contain such a line in the init method:

if ((self = [super init])) {
   ...
}

And according to this page, which is referred by many questions regarding [super init]: https://www.cocoawithlove.com/2009/04/what-does-it-mean-when-you-assign-super.html

self = [super init] "always returns the singleton instead of any subsequent allocation".

But why? The following is my implementation of a shared singleton

#pragma mark -
#pragma mark Constructors

+ (VoiceProfileManager*)sharedManager {
    static VoiceProfileManager *sharedManager = nil;
    //Executes a block object once and only once for the lifetime of an application.
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        sharedManager = [[VoiceProfileManager alloc] init];
    });
    return sharedManager;
}

- (id)init {
    if ((self = [super init])) {
    }
    return self;
}

@end

Using design pattern with modules, Ruby

As I understood: In Ruby, we use modules instead of classes when we don't need a state (if it's just a function that takes an input an produces an output).

Some design patterns depends on inheritance like template design pattern.

I am making a crawling libirary that takes a link as an input and produces an object containing the data.

It don't need a state so a module seems to be suitable for me instead of a class, I also need to use template design pattern as I am using different algorithms to produce data of the same structure.

Now my question, I need to use inheritance to implement template design pattern, but I don't need a state it just returns the data from the website.

Is implementing a design pattern a good reason to use classes (for inheritance)? or what is the best practice in such cases ?

Iterating over subclasses with different properties

I am interested in a design pattern or best practice approach to the following scenario:

Let's say we have multiple subclasses that derive from a common interface:

public interface IPerson{
    string Name;
}

public class SomePerson : IPerson{
    string Name;
    bool hasAccess;

    bool GetAccessInfo(){
    //implementation
    }
}


public class OtherPerson : IPerson{
    string Name;
    int NumberOfPoints;

    int GetNumberOfPoints(){
    //implementation
    }
}

Now let's assume we have a class which has a collection of IPerson objects:

public class PersonHandler{
     public List<IPerson> People;
}

So the question here is how would you iterate over the People collection and still be able to use the individual subclasses' members and methods like GetNumberOfPoints or GetAccessInfo all in one iteration?

I don't like checking the type explicitly and I also don't like having the subclass specific methods be in the interface, because it kind of defeats the purpose of OO design.

Maybe ideally those shouldn't be in the same collection? I'm looking for a language agnostic answer.

Removing dependency from a method

I'm currently in the middle of learning DI & IoC principles. So, I stumbled upon such scenario where I have a method with a dependency that can not be injected via constructor. Also, I can not pass it as a method parameter because creation of that instance is conditional + it can only be instanciated with parameters of its own. Here is a super-simplified version of my Employee and WorkYear classes:

public abstract class Employee
{
    public List<WorkYear> WorkYears { get; set; }

    public void StartWorking(DateTime joinedCompany)
    {
        List<PayPeriod> periods = // Calculating periods...
        WorkYear year = WorkYears.FirstOrDefault(y => y.CurrentYear == joinedCompany.Year);

        if (year == null)
        {
            // Here is the problem:
            year = new WorkYear(joinedCompany.Year, this, periods);

            WorkYears.Add(year);
        }
        else
        {
            // Logic when year not null
        }

        year.RecalculateAllTime();
    }

    // More code...
}


public class WorkYear  
{ 
    public WorkYear(int currentYear, Employee employee, List<PayPeriod> periods)
    {
        Employee = employee;
        EmployeeId = employee.Id;
        CurrentYear = currentYear;
        PayPeriods = periods ?? new List<PayPeriod>();

        foreach (PayPeriod period in PayPeriods)
        {
            period.WorkYear = this;
            period.WorkYearId = Id;
        }
    }

     // More code...
}

As you can see I only need a new instance of a WorkYear if Employee doesn't already have it. I found a thread that suggested to use simple factory class to solve similar issue. Such solution could work, but how do I handle parameters without which the WorkYear can not be instantiated?

Would be great to see an example of how to approach this problem.

Design Patterns for Performing Multiple Server Operations as a Single Transaction

Suppose you have a SaaS app and want to do the following when a user signs up:

  1. Validate their name, email etc.
  2. Create a Stripe Customer account for the user.
  3. Subscribe the new Stripe Customer to an existing Stripe Plan.
  4. Create a User record in your database which includes the Stripe info.
  5. Create a new session for the user.
  6. Redirect the user to your app's dashboard.

Ideally you want all these to happen in a single transaction, i.e if step 4 fails, you want to undo step 2 & 3...you don't want a dangling Stripe customer & subscription with no DB record.

What design patterns would you recommend to make such multi-step/multi-service process transactional?

For Context

I'm implementing this multi-step process using ES6 Promises in Node - pseudocode below:

async function signup_user_for_trial(req, res) {

  const {email, name, plan, password} = req.body

  if (!isValidEmail(email)) {
    throw new Error(...)
  }

  let customer = await createStripeCustomer(email)
  let subscription = await createSubscription(customer, plan)
  let user = await createDBUser(customer, name, email, password)
  let session = await createSession(req, user)

  return res.redirect('/dashboard')
}

How channel hooks work and what are the design considerations to keep in mind

I am creating a chat platform where I need to create channel adapters for facebook, slack, whatsApp etc. I need to support incoming chats from all these channels and there may be many more. Now, all I can find out over the internet is that webhooks play a central role in on boarding channels but I am unable to figure out how it all works out end to end and what design considerations should I keep in mind while designing this system/adapters

I figured I would have to provide webhook where channel users would be posting their chats but at the same time adapter would have to get webhook url of that channel as well so that messages from the platform can be sent to the user. For eg if user1 sends a message from slack using platform's webhhok, some other user can reply to him using his slack webhook.

But this way I would have to maintain a highly available cache service as well as data store that would maintain this mapping for this user <==> slack-webhook <==> platform-webhook

Is it the right way of doing it? If no, is there some industry standard way of doing it? Any help/feedback would be appreciated

Android - MVP using Activity/Context

I've been dabbling with MVP for android and have read from different sites about not passing an activity as argument into the presenter as it's anti-pattern but i have come across a problem where i need to use a third party method that requires the activity/context.

I've thought of using Dependency Injection, doing another abstraction or just pass it only to the method that requires it, rather than the constructor but i'm confused with what's better.

An example in Kotlin (Presenter)

fun Food(*should activity be passed here?*) { 
var bar = Foo(activity).build

Stand(bar, callback{})
}

Would be great if someone can enlighten me on this.