lundi 30 avril 2018

Anti-pattern name for firing events on an object member supplied at instantiation?

An object requires it be instantiated with an object upon which it can call a method to register than an event has occurred — rather than the instantiating code listening for events.

Is this an anti-pattern? If so, does it have a name?

Is there a reason to code this way?

What's the pattern that describes a read should be performed after an update?

I remember I read a pattern that says a read (GET) should be performed after and a record update (PUT). Can someone please let me know the name of the pattern and the wiki link? Thanks.

Composite design pattern definition

In the book Design Patterns : Elements of Reusable Object-Oriented Software, It says:

"The composite design pattern composes objects into tree structures to represent part-whole hierarchies."

In wikipedia the composite design pattern is defined as :

"The composite pattern describes a group of objects that is treated the same way as a single instance of the same type of object. The intent of a composite is to "compose" objects in to tree structures to represent part-whole hierarchies."

Picture of composite design pattern:

enter image description here

If my Composite stores components as directed acyclic graph( for example it only stores components which are sources of DAC in queue data structure and those sources have references to another components and so on... ) which is not tree because it violates some tree structure condition. Can I still say that I have used composite design pattern?

Can Dependency Injection be considered to be a replacement for factory method pattern?

According to wikipedia

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.

In dependency injection also(I have experience of spring so this may be in that context), we have Variables for each class defined using interfaces, and leave the concrete instantiation to the DI framework.

Am I missing something in this or can these be used interchangeably?

Using Singleton within the Android Room Library

I have always been told that using Singleton were bad. However, every example of the Android Room implementation seems to use the Singleton approach. Can someone please explain why is this the case?

Thanks

Looking for books having similar pattern rules as mentioned in the body of this post

One of the patterns i came across- The GUI should be attached to a Java bean class. And the bean class should have a listener associated with it. The bean fires and responds to events in response to user gestures in the UI.

Is there any book/blog where i can find more such patterns. Or what is the set of patterns called of which the above pattern is a subset.

Random pattern generator?

I am currently developing an app that will need to recognize and distinguish different patterns, and I currently need 54 unique, easily distinguishable patterns that are not too intricate for a normal mobile camera to read. The patterns can use any means possible to distinguish themselves, but I would like for each pattern to follow the same style. The goal is for the app to distinguish each pattern without it being too easy to distinguish them with the naked eye. I have considered using a simple 3x3 or 2x2 square sporting 4-9 different coloured squares for each pattern, but I've also seen images where there is a mash of colours with waves going through, used for similar puproses, but I am afraid this pattern will be too difficult for the app to distinguish between. Especially if there are 54 of them. Is there any application that I can use to generate these patterns while guaranteeing that no two patterns look too much alike? The best I've found so far is a knitting-pattern generator, but that makes a random sheet of pattern with no regards for uniqueness.

I hope I'm not asking for too much, but I can't seem to find a good algorithm to work this out anywhere. If no such program exists I will have to make these patterns myself, but I would like to avoid that at any cost, as it's likely to cause a lot of similar patterns.

Thank you all in advance.

Reverse Decorator Pattern

I would like to dynamically add new product data to database. The users go through various list selections (where they can select an existing value or add new) to categorize a product and in the and add a price and size. The categorization order is as follows:

Category->Subcategory->Producer->Product

E.g. A user can choose an existing category and subcategory, but add a new product by a new producer. So the new data which should be added to DB will be product and producer data. If the ordering of selections would be reverse:

Product->Producer->Subcategory->Category

The base product would be set at the beginning and a normal Decorator Pattern would work, but in reverse order I don't see how.

Could someone tell me how would I do this the right way?

Coupled vs Decoupled backend-frontend

I have an asp.net website project that uses APIs as a back-end, i need to totally decouple my front-end from my back-end apis, so I have created one RESTful service in my back-end project and now i want to consume it in the front-end. I assume i have two solutions:

  • Build my model only in the back-end, and add reference to the front-end, it will help avoid re-writing the same model in the front-end again.
  • Build two models in both back-end and front-end.

Pros: Solution 1) - it will help avoid re-writing the same model in the front-end again. - it will force front-end to be updated once the back-end changes.

Solution 2) - It should help decoupling my front-end from the back-end. - It won't function if my back-end changes, but it will avoid build errors.

Please advise which approach is better design, and if you have suggestions please share.

dimanche 29 avril 2018

Design pattern for calling different functions for different instances

I have a java code like this-

Sample obj;
if(obj instanceOf Class1) 
{
    method1(obj);
} else if(obj instanceOf Class2) 
{
    method2(obj);
} else if(obj instanceOf Class3) 
{
    method3(obj);
}

I want to write the logic of method1, mehtod2 and method3 in a different class. Is there a design pattern for that. I am using spring MVC.

Does my program utilize any design patterns, and if so then which one?

So does my program utilize any design patterns and if so then which one? And also if it doesn't utilize any design patterns then how would I edit this to utilize a design pattern? I've just been trying to look at design patterns and got kind of confused by some of them. Here is an interface, an implement class and a main class.

public interface StackADTInterface<T>
{
    public void push(T element);

    public T pop() throws EmptyCollectionException;

    public T peek();

    public int size();

    public boolean isEmpty();

    public String toString();
}

public class StackArraySec02Imp<T> implements StackADTInterface<T>
{
    public final int maxLength = 100;
    public int top = 0;

    public T[] stackArray;

    public StackArraySec02Imp()
    {
        stackArray = (T[])(new Object[maxLength]);
    }

    public StackArraySec02Imp(int initialCapacity)
    {
        stackArray = (T[])(new Object[initialCapacity]);
    }

    @Override
    public void push(T element) 
    {
        if(size() == stackArray.length)
        {
            System.out.println("Stack is Full");
        }
        else
        {
        stackArray[top] = element;
        top++;
        }
    }

    @Override
    public T pop() throws EmptyCollectionException 
    {

        if(!isEmpty())
        {
            top--;
            T retObj;
            retObj = stackArray[top];
            stackArray[top] = null;
            return retObj;
        }
        else
        {
            throw new EmptyCollectionException("Stack is Empty");
        }
    }

    @Override
    public T peek() 
    {
        T retObj = stackArray[top-1];
        return retObj;
    }

    @Override
    public int size() 
    {
        return top;
    }

    @Override
    public boolean isEmpty() 
    {
        boolean isEmptyFlag = false;
        if(top <= 0 && stackArray[top] == null)
        {
            isEmptyFlag = true;
        }

        return isEmptyFlag;
    }

    @Override
    public String toString()
    {
        String result = "";

        for(int i = stackArray.length - 1; i >= 0; i--)
        {
            result += stackArray[i] + "\n";
        }

        return result;
    }

}


public class mainArraymain 
{
    public static void main(String[] args)
    {
        StackArrayImplemList<Integer> newStack = new 
        StackArrayImplemList<Integer>();


        newStack.push(12);
        newStack.push(5);
        newStack.push(6);
        newStack.push(7);
        newStack.push(8);
        newStack.push(9);

        System.out.println(newStack.toString());
    }

}

Find a Decorator of a particular type when using the Decorator Pattern?

I'm building an app that needs to use multiple types of similar sensors. Since the sensors could also have different behaviours, or combinations of behaviours, I decided to use the decorator pattern.

In short, I have a hierarchy that looks like this:

enter image description here

So any of the concrete ISensorDecorator classes can decorate (wrap) any of the concrete IMeasureSensor classes, but since a concrete ISensorDecorator also is a concrete IMeasureSensor, they can wrap each other. So for example

IMeasureSensor sensor = new FilteredSensorDecorator(
    new CalibratedSensorDecorator(
        new AccelerometerSensor()
    )
);

is a valid statement that declares a filtered and calibrated accelerometer sensor.

Now let's say I have a method called setCalibration() in CalibratedSensorDecorator. Obviously I can't call

sensor.setCalibration();

because IMeasureSensor doesn't have a setCalibration() method. And trying to use

((CalibratedSensorDecorator)sensor).setCalibration()

won't work either, since sensor is a FilteredSensorDecorator.

How can I get to the CalibratedSensorDecorator in this particular case, and more generally to any specific decorator in any "chain" of decorators? I don't want to store them as separate variables, I want to do it dynamically.

GUI Framework based on Open GL

I have an idea to create simple cross-platform GUI framework, which will use Open GL for rendering. I want to use Open TK library for C#. How to achieve better performance using Open GL (is there any best practices etc). What pattern is better to follow: MVVM, MVP, MVC, or something else? How to handle UI events? How to implement the ability to use platform-specific features? How to organize dependency injection? I would hear some advice from people who had an experience in this area. Thank You.

samedi 28 avril 2018

Structural typing and Polymorphism - Adding super types

Below is an example code(polymorphic) taken from angular framework using TypeScript syntax,

export abstract class AbstractControlDirective {
   ...
}


AbstractControlDirective subtypes

export abstract class NgControl extends AbstractControlDirective {
     ...
}
export abstract class ControlContainer extends AbstractControlDirective {
   ...
}
export declare abstract class ControlContainer extends AbstractControlDirective {
  ...
}
export declare abstract class NgControl extends AbstractControlDirective {
    ...
}


NgControl subtypes

export class NgModel extends NgControl implements OnChanges, OnDestroy {
   ...
}

export class FormControlDirective extends NgControl implements OnChanges {
    ....
}

export class FormControlName extends NgControl implements OnChanges, OnDestroy {
   ...
}

export declare class FormControlDirective extends NgControl implements OnChanges {
    ...
}

export declare class FormControlName extends NgControl implements OnChanges, OnDestroy {
   ...
}

export declare class NgModel extends NgControl implements OnChanges, OnDestroy {
   ...
}

In general, there are many situations, that came across new requirements, to add obvious looking super type in intermediate layers of class hierarchy, that injects breakage in subtypes, unless using some design pattern. Using design pattern can make the class hierarchy less error prone but breaks the hierarchy structure.


To avoid this problem, Can we maintain this hierarchy without using extends keyword? TypeScript being structural typed...

Design Pattern for converting objects to/from bytes

I have a class A that contains instances of several other Classes B, C and D as shown.

I want to convert Class A and its contents to an array of bytes and store them in a file. Later I want to read the byte array from the file and convert it back to an instance of Class A as shown here. I'm having trouble designing an elegant solution that converts back and forth between objects and byte arrays.

One solution I considered was creating a single converter class that can convert back and forth between all my objects and byte arrays :

public Converter{

   public static ClassA getInstance(byte[] b){...return new ClassA()}
   public byte[] getBytes(ClassA classA){...}

   public static ClassB getInstance(byte[] b){...return new ClassB()}
   public byte[] getBytes(ClassB classB){...}

}

This approach results in a very large class with a lot of methods.

Another approach is to make a "Converter class" for each class that I want to store in the file.

public ClassAConverter extends Converter<ClassA>{

   public ClassA getInstance(byte[] b){...return new ClassA()}
   public static byte[] getBytes(ClassA classA){...}

}

public ClassBConverter extends Converter<ClassB>{

   public ClassB getInstance(byte[] b){...return new ClassB()}
   public static byte[] getBytes(ClassB classB){...}

}

This design however seems to have the disadvantage of creating a large amount of classes.

I'm that aware that Java Serialization achieves most of what I've described here, but I'm looking for a more flexible and customized solution that also enables the file to be parsed by other independant programs.

Is there any design pattern that could help implement the conversion logic more elegantly?

How should I handle failure between API calls

I have encounter a problem where a action can be done through either a sequence of existing Http requests like the following:

api1() -> api2() -> api3()

Or I will have to create a new API that does it at once so its something like:

apiNew() {
   api1();
   api2();
   api3();
}

Then I will just send request to apiNew() and let it do all of the three functions.

However, since all three apis involves database change, each individual API is wrapped with a transaction block.

Here is the problem, in case I call them separately. Then if api1() succeed but api2() failed, the database is in some in the middle state which will require manual change, so it can move to the correct state.

The way I am doing it now is to create the apiNew() and wrap all three in the same transaction block so all the database changes are going under the same transaction.

I am just wondering, is there some other way of doing this type of work, so I can reuse api1() api2() and api3() in a way that it does the error handling correctly without rewrite the code to a single API call.

Implementation of MVC pattern for single and multiple objects

I've implemented a student administration with MVC pattern (Tutorial: Link). I've decided to divid the students in "SingleStudentModel" and "MultipleStudentModel", but I'm not sure if that make sense in my case. In general, I'm not satisfied with my solution. Is it possible to handle single student and multiple students with one controller? Is it ok if a model import into a view class (see StudentsView.java)?

How can I improve this project?

Thanks in advance.

Student.java (Model, data class (?))

public class Student {

    private String name;
    private int nr;

    public Student(String _name, int _nr){
        this.name = _name;
        this.nr = _nr;
    }

    // get set
}

SingleStudentModel.java (Model)

public class SingleStudentModel {
    private Student student;

    // get set
}

StudentController.java (Controller -> SingleStudentModel)

public class StudentController {
    private SingleStudentModel model;
    private StudentView view;

    public StudentController(SingleStudentModel _model, StudentView _view){
        this.model = _model;
        this.view = _view;
    }

   // set get

    public void updateView(){
        view.printStudentDetails(model.getStudent().getName(), model.getStudent().getNr());
    }
}

MultipleStudentModel.java (Model)

public class MultipleStudentModel {
    private Collection<Student> students = new ArrayList<Student>();

    public Collection<Student> getStudents() {
        return students;
    }

    public void setStudents(Student student){
        this.students.add(student);
    }
}

StudentsController.java (Controller -> StudentsModel)

public class StudentsController {
    private MultipleStudentModel model;
    private StudentsView view;

    public StudentsController(MultipleStudentModel _model, StudentsView _view){
        this.model = _model;
        this.view = _view;
    }

    public void updateView(){
        view.printStudentList(model.getStudents());
    }
}

StudentView.java

public class StudentView {
    public void printStudentDetails(String _name, int _nr){
        System.out.println("Student: ");
        System.out.println("name: " + _name);
        System.out.println("nr: " + _nr);
    }
}

StudentsView.java

import com.mvc.model.Student;

import java.util.Collection;

public class StudentsView {

    public void printStudentList(Collection<Student> students){

        System.out.println("\nStudent list");

        for(Student item : students){
            System.out.println("name: " + item.getName());
            System.out.println("nr: " + item.getNr());
        }
    }
}

Main.java

 public class Main {

       public static void main(String [] args){

            //Single student
            SingleStudentModel model = new SingleStudentModel();
            StudentView view = new StudentView();
            StudentController controller = new StudentController(model, view);

            model.setStudent(new Student("John", 1));

            controller.updateView();

            //Multiple student
            MultipleStudentModel model2 = new MultipleStudentModel();
            StudentsView view2 = new StudentsView();
            StudentsController controller2 = new StudentsController(model2, view2);

            model2.setStudents(new Student("Zelda", 2));
            model2.setStudents(new Student("Link", 3));

            controller2.updateView();

            }
      }

vendredi 27 avril 2018

How to use pattern bridge in iOS swift

I'm trying use more pattern in my projects on iPhone, and now I'm interesting in abstractions. My question is how I can use Bridge pattern in real life. Please give me your swift real life examples or may be you know interesting literature/video about pattern in real life.

Cover with unit test WebRequest c#

public void HandleRequest(WebhookModel model)
{
        var strRequest = "cmd=_notify-validate&" + ipnContext.RequestBody;
        var webRequest = FormRequest(strRequest);
        var requestStream = _webRequestWrapper.GetRequestStream();
        var responseStream = _webRequestWrapper.GetResponse().GetResponseStream();

            using (StreamReader reader = new StreamReader(responseStream))
            {
                model.Verification = reader.ReadToEnd();
            }

}

private WebRequest FormRequest(string strRequest)
        {
            var webRequest = WebRequest.Create("some url is over here");

            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = strRequest.Length;

            return webRequest;
        }

Where _webrequestWrapper just a wrapper around WebRequest class. So, my question is how i can mock _webRequestWrapper.GetResponse().GetResponseStream()? The problem is that there is no problems with mocking GetResponse() cause of we create for it wrapper around WebRequest. But the problem is with GetReponseStream, because it returns a Strem object, how i can test HandleRequest() method? I really haven't any ideas about it. Please help me. Thanks

Pass a variable as a parameter while creating its object

I want to inject a variable as a parameter while creating its object using Guice. I am able to achieve it without using guice by using below code.

class A{
       private CountDownLatchFactory countDownLatchFactory;
       A(CountDownLatchFactory countDownLatchFactory){
             this.countDownLatchFactory = countDownLatchFactory;
       }
       public void createTimer(List<String> targets){
           // doing some stuff
           countDownLatchFactory.create(targets.size());
          //doing some stuff
       }
  }

  class B{
    private CountDownLatchFactory countDownLatchFactory;
       B(CountDownLatchFactory countDownLatchFactory){
             this.countDownLatchFactory = countDownLatchFactory;
        }    

    public void usingTimer(){
    //doing some stuff
    countDownLatchFactory.getCountDownLatch().countDown();
    //doing some stuff
   }
}

public class CountDownLatchFactory{

    private CountDownLatch responseLatch;

    /**
     * @param numTargets
     * @return
     */
    public void create(int numTargets) {
        responseLatch = new CountDownLatch(numTargets);
    }

    public CountDownLatch getCountDownLatch(){
        return responseLatch;
    }
}

The thing i am not able to understand is how can guice can can create a object using a parameter. The parameter can only be supplied using function of the class and if guice cant do that. Is there is a better way of doing it?

Does there exist a Pass/Fail Design Pattern?

Not quite sure what the formal term for such a pattern/problem, but here is what I'm facing:

I have an operation that is somewhat large. It can either pass or fail. Each pass or fail carries with it either the result of the successful operation, or information about why the operation failed. I am struggling to architect this function 'correctly'.

class Pass{
    int someGoodStuff;
    double someOtherGoodStuff;
}

class Fail{
    String failureMsg;
    float howMuchOperationWasOffBy;
}

class Operator{
    public ??? operation(){
    }
}

Approach 1: Fail states are like exceptions. Lets throw them. This allows me to include the failure information and make the return type just Pass. However, these fail states are not programming language errors, they are business logic fails. So, two things sit wrong with me about this approach: one, it confuses business logic fails with actual Java errors (which seems wrong) and two, it coopts the normal flow of execution without any really good reason to do so.

Approach 2: Functions in java like to return one object type, so have Pass and Fail both implement an interface Result, and have the return type of the function be that.

interface Result{...}
class Pass implements Result{...}
class Fail implements Result{...}
class Operator{
    public Result operation(){...}
}

However, the pass and fail states that the function returns are completely different. They have little to no overlapping variables or functions. This seems wrong and reduces me to have to instanceof all the important information out of the passes and fails.

Approach 3: Some sort of union object that can be either pass or fail (but not both)

class Result{
    public Pass pass=null;
    public Fail fail=null;
}

class Operator{
    public Result operation(){...}
}

This has the advantage that I can say things like

Result result=op.operation();
if (result.succeed()){
    doStuffWithPass(result.getPass());
}else{
    doStuffWithFail(result.getFail());
}

Which is basically what I was doing with instanceof, but nicer looking; the code now looks how you might expect it to. It is clear to follow.

However, Java has no real Union types. I have to make sure someone doesn't accidentally try to mess with the pass variables of a fail Result or vice versa. Furthermore, every method I call on the union type have to be predicated with figuring out whether it is a pass or fail (That If branch suddenly has to be everywhere)

Finally, although not a real concern yet, such a pattern I believe allocates space for both a Pass and a Fail for each Result, when I know that it can only ever be one of them (ie it should take up a space equal to Max(space(Pass),space(Fail)))

None of these approaches seems perfect. I feel like there should be a pattern to solve this kind of problem. Is there?

Is this PHP pseudo-DI pattern wrong / dangerous?

I have let's say a class, VehicleManager. This class manages the lifecycle and calling of Vehicle type Objects. Vehicles act as modules and extend the base Vehicle class.

So if you make a class bike, you never do new Bike(), you do VehicleManager->create('Bike',5);

My problem is, i want the construction of every vehicle to receive predefined parameters,and do some predefined actions, so my base Vehicle class has a private final constructor.

Example:

final private function __construct(Array $myCustomData){
  $this->customData = $myCustomData;
}

But still i want each vehicle type to have some custom initializion

So after doing

$newVehicle = new $ClassName($myCustomData);

Im doing

$newVehicle->initialize(); 

Is this acceptable? Thanks

Xamarin forms right design pattern with api's

I want to make an app which would be cross platform, android/ios/uwp. I have it right now in mvc architecture, could change it to mvvm. I would like to implement in future azure push notificion which needs separated api project for it. So here's my question , how should I do my whole project? Should I implement all api(my project api and push notification api) as one and create another xamarin forms project in which I would just get my data using for example rest api ?

Thanks in advance for help. :)

Design patterns with real time example in IOS - Swift 4

I want to learn Design patterns with real time example. So can any one Please suggest where I can start.

jeudi 26 avril 2018

MySQL Database Structure with revisions/history

I've been looking into various DB Structures for the task I'm trying to achieve but it seems like my ideas are flawed. I first looked into wiki's DB but seemed a bit complicated for what I want to do and then I saw https://www.themoviedb.org/movie/337167-fifty-shades-freed/changes this which looks closer to what I am trying to do.

I was thinking of having a table which will keep the final form and an extra table where it will keep all the revisions/history. I am not sure though if that would be too much. Although I am not sure the above example is using this method.

Getting Class Names from User in Decorative Pattern

I am trying to make a pizzashop program. I am using decorative pattern for this purpose. Simply my program is running like this line :

 Pizza basicPizza = new TomatoSauce(new Mozzarella(new PlainPizza()));

For every different topping or different sauce i want to get these information from the user. For instance if user enters "Salami,Cheese" i want these line of code:

Pizza basicPizza = new Salami(new Cheese(new PlainPizza()));

I found some information about reflection also newInstance() method but could not achieve my goal because of the inner classes.

Proactor pattern vs asyncronous completion token

I'm working on a client-server system. I want to implement an event handling pattern on server side. As I see there are two patterns to have an asynchronous server: Proactor and asynchronous completion token. I'd like to know more detail about the second pattern and also the difference of these two patterns.

Using Facade Like a wrapper

I usually see some people used facade like this.

public class FooFacade {
   Foo foo;

   public boolean isFunny(param1, param2) {
       IsFunnyInput isFunnyInput = new IsFunnyInput(param1, param2);
       return foo.isFunny(isFunnyInput);
   }
}

Is this a right approach? In my opinion, it is just adding one more class to the package. When you can also directly use Foo to do the same.

Libgdx passing actions of an actor to another actor

Ok so basically I'm trying to decorate a Libgdx Actor class with other actions

 public Shake(Button buttonToBeDecorated) {
      super(buttonToBeDecorated);
      Array<Action> actions = buttonToBeDecorated.getActions();

      for (Action action : actions)
            addAction((action));

      addAction(Actions.forever(new SequenceAction(
             Actions.moveBy(10, 0, 0.5f),
             Actions.moveBy(-10, 0, 0.5f)))
      );

 }

however actions from toBeDecorated class (which are also wrapped in SequenceAction) doesn't apply to instance of Shake. I'm sure that actions are passed properly because I am able to print them out. But I'm not getting combined effect, maybe some of you would know why ? Thanks

Overriding virtual boolean pure method without LSP breaking

For example we have the following structure:

class Base
{
    [pure]
    public virtual bool IsValid(/*you can add some parameters here*/)
    {
       //body
    }
}

class Child : Base
{
    public override bool IsValid(/*you can add some parameters here*/)
    {
       //body
    }
}

Could you please fill Base::IsValid() and Child::IsValid() with different bodies but without conflicts with LSP? Let's imagine it's just method for analyzing, we cannot change instance's state. Are we able to do it? I'm interested in any example. I try to understand whether virtual (bodied) boolean methods is anti-pattern or not in general case.

How to cover wth unit tests StreamWriter C#

How to test the next code sample?

using (StreamReader reader = new StreamReader(requestBody, Encoding.ASCII))
{
       ipnContext.RequestBody = reader.ReadToEnd();
}

The very first idea comes to my mind just create custom wrapper around StreamReader and inject it to class where it's needed. What do you thinks of it. Maybe you could give me more best solution. Thanks for your attention

C - Singleton Pattern Implementation with double-checked locking

as you know the singleton pattern ensures a class has only one instance, and provides a global point of access to it.

We are going to implement getInstance method respect to the double checked locking using with C programming language (POSIX library) in to the given template code below. Also, we should use semaphore.

Here is my code

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#define NO_OF_THREADS 10

struct Singleton {
   char *Data;  
};


struct Singleton *singletonObjectPointer;


int addresses[NO_OF_THREADS];
sem_t sem;

void *runner(void *params); /* the thread */
struct Singleton *getInstance();

int main()
{
    int i;
    sem_init(&sem,0,1);
    pthread_t threadIds[NO_OF_THREADS];


    for (i=0; i < NO_OF_THREADS; i++){
        pthread_create(&threadIds[i], NULL, &runner, (void *)(i));
    } 

    /* Wait until all threads are done */
    for (i=0; i < NO_OF_THREADS; i++){
        pthread_join(threadIds[i], NULL);
    } 

    /* Control addresses. All of them should be same */
    int prevAddr=addresses[0];
    for (i=1; i < NO_OF_THREADS; i++){
        if(addresses[i]!=prevAddr){
            printf("Object is created more than once\n");
            return -1;
        }
        prevAddr=addresses[i];
    }
    for (i=0; i < NO_OF_THREADS; i++){
        printf("Singleton Addresses for each thread %x\n",addresses[i]);
    }
    printf("Successful\n");
    return 1;
}

/**
 * The thread will begin control in this function
 */
void *runner(void *params) 
{
    int i = (int)params;
    printf("Thread %d\n",i);
    struct Singleton *s = getInstance();
    addresses[i]=s;
    pthread_exit(0);
}

//Fill this method
struct Singleton *getInstance(){

        singletonObjectPointer = (struct Singleton *)malloc(sizeof(struct Singleton));
        printf("---Address of singletonObjectPointer is %x\n",singletonObjectPointer);
        singletonObjectPointer->Data="This is object data"; 

    return singletonObjectPointer;
}

Is there a specific name to following pattern?

I designed a framework to expose some rest based webservices. The base classes looked like this (not exact code)

public interface WSService {
    public void init(WSRequest request);
    public List<String> validate();
    public void performAction();
    public WSResponse generateResponse();
}

Each new service, implements this webservice and implements its specific logic

public class WSOrders implements WSService {...}

Then, i implemented a WSProcessor which takes in specific class and then execute the methods and performs error checks/etc. for example

@RestResource(GET, "/getorders")
public Response getOrders (...){
    WSService getOrders = new WSOrders();
    WSRequestProcessor processor = new WSRequestProcessor(restInput);
    processor.process(getOrders);    
}

in WSRequestProcessor, i used the process method to first extract input from rest request, do application level validation (some headers validation etc). Then called metthods like this

public WSRequestProcessor{
...

    public void process (WSService service){
        service.init()
        service.validate();
        service.performAction();
        service.generateResponse();
    }
}

One thing to note that WSRequestProcessor handles all the exception handling, generic error response creation etc.

This pattern worked out pretty well to expose any of the resource for us. At the end of the day, to expose any resource, all i had to (or any developer) was to create WS<ResourceName> and implement their business logic there.

Create and fill very large autogenerated with cxf class

I have very large object generated with org.apache.cxf

This class look like this:

public class AcceptorBatchTransfer {

    @XmlElement(name = "Hdr", required = true)
    protected Header3 hdr;
    @XmlElement(name = "DataSet", required = true)
    protected List<CardPaymentDataSet1> dataSet;
    @XmlElement(name = "SctyTrlr", required = true)
    protected ContentInformationType1 sctyTrlr;

    getters and setters and not constructor

Header3 class look like this:

public class Header3 {

    @XmlElement(name = "DwnldTrf")
    protected boolean dwnldTrf;
    @XmlElement(name = "FrmtVrsn", required = true)
    protected String frmtVrsn;
    @XmlElement(name = "XchgId", required = true)
    protected String xchgId;
    @XmlElement(name = "CreDtTm", required = true)
    @XmlSchemaType(name = "dateTime")
    protected XMLGregorianCalendar creDtTm;
    @XmlElement(name = "InitgPty", required = true)
    protected GenericIdentification32 initgPty;
    @XmlElement(name = "RcptPty")
    protected GenericIdentification32 rcptPty;

    getters and setters and not constructor

And all nested classes look simular. I need create and fill this AcceptorBatchTransfer and I need write very very very much code((((((

It look like this

final AcceptorBatchTransferV01 acceptBTransfer = new AcceptorBatchTransferV01();
      request.setAccptrBtchTrf(acceptBTransfer);

      Header3 header = createHeader(paymentRequest.getInitgPty());
      acceptBTransfer.setHdr(header);

      final List<CardPaymentDataSet1> dataSets = acceptBTransfer.getDataSet();
      CardPaymentDataSet1 dataSet = createDataSet(paymentRequest);
      dataSets.add(dataSet);
...
private Header3 createHeader(String senderId) {
    final Header3 header = new Header3();
    header.setDwnldTrf(DWNLD_TRF);
    header.setFrmtVrsn(FRMT_VRSN);
    header.setXchgId(XCHG_ID);
    final XMLGregorianCalendar creDtTm = XMLGregorianCalendarConverter.asXMLGregorianCalendar(new Date());
    header.setCreDtTm(creDtTm);
    final GenericIdentification32 sender = new GenericIdentification32();
    sender.setId(senderId);//MEGAR
    header.setInitgPty(sender);
    return header;
  }

and 277 rows code for fill one object! I want simplify this process bu I do know how.

This classes was generatet with cxf and do not have constructors. Mabbe there are suitable design pattern? I can not create Builder because classes is autogenerated. Maybe I can create some wrapper....or somthing else?

Use delegator DP two inherit from few abstract classes

Can delegation DP can be used to inherit from two abstract classes or more ?

Pythonic way to setup property in Bridge design pattern

[Description]

  • I'm trying to build a module by using "Bridge" design pattern to decouple an abstraction from its implementation. I also need a property "try_limit" can be changed dynamically when running.
  • After some tries & errors, I wrote bridge.py which works as I expected, but I need to write property & setter twice in "Abstraction" & "Implementor" class respectively. Is there another pythonic way to do this?

  • bridge.py

    #!/usr/bin/env python3
    # -*- coding: utf-8 -*-
    import abc
    
    class Abstraction(object):
        def __init__(self, imp):
            self._imp = imp
    
        @property
        def try_limit(self):
            return self._imp.try_limit
    
        @try_limit.setter
        def try_limit(self, value):
            self._imp.try_limit = value
    
        def run(self, cmd):
            ret = self._imp.run(cmd)
    
            return ret
    
    
    class Implementor(metaclass=abc.ABCMeta):
        def __init__(self):
            self._try_limit = 0
    
        @property
        def try_limit(self):
            return self._try_limit
    
        @try_limit.setter
        def try_limit(self, value):
            self._try_limit = value
    
        @abc.abstractmethod
        def run(self, cmd):
            pass        
    
    
    class ImpA(Implementor):
        def __init__(self, realtime_display=False):
            super().__init__()
    
        def run(self, arg):
        # Implement A which use try_limit
        # try_limit can be changed dynamically when running 
    
    
    class ImpB(Implementor):
        def __init__(self):
            super().__init__()
    
        def run(self, arg):
        # Implement B which also use try_limit
        # try_limit can be changed dynamically when running
    
    

[Environment]

  • Python 3.6.3

Is there any architecture or framework support for the Android developer?

Basically, I'm a web developer. I worked with few years of experience. Nowadays, I am developing an android application for my university course. I found this article that makes me thoughtful. My curious my mind wants to know -

  1. Is there any design pattern/architecture or framework support like MVC that are useful for the Android developer?

  2. How code fragmentation is done in development for common materials like header-footer?

how to separate the first character of the pattern from the rest?

I am making a form and in my form there is a field called username. my username must follow a specific pattern:

  • it must be between 8 to 12 characters

  • it can be comprised of "uppercase letters", "lowercase letters" or "numbers" "_" "-" ".".

  • the starting character shouldn't be a number

how should I write the pattern format?

pattern="[a-zA-Z0-9-_.]{8,12}

i don't know the rest

please help

thanks in advance

Modeling API objects with respect to internal implementation

If you create a REST service that serves Banana objects, there are likely two different conceptual models of a Banana.

  1. What is used on the REST API you serve to the public
  2. What is used internally to the application, with possible DB fields that aren't exposed externally

Is it best to have a class that represents each, with available converters to go from one to the other?

class Banana {
  private String color;
}

class InternalBanana {
  private int id;
  private String color;
  private ZonedDateTime createdAt;

  public toBanana() {
    return new Banana(color);
  }
}

Some benefits I notice to this approach:

  • Marshalling to Json via jackson is simple
  • Banana can be used while test-driving the API code, which can't be said so much for InternalBanana.

Some cons:

  • Seems ripe for code duplication down the road
  • Converters of internal objects need to be updated any time the API is updated

Alternatively you could bundle everything into a single class and have it handle both cases:

class Banana {
  private int id;
  private String color;
  private ZonedDateTime createdAt;

  public String toApiJson() { ... }
}

Pros:

  • A single class, no duplication
  • Seems more robust to changes in the public API

Cons:

  • Rest API objects aren't actually modeled in the system anywhere
  • Marshaling to Json means writing a special ObjectMapper or toApiJson() method that only selects the appropriate fields
  • DB fields will often be null, requiring appropriate checks or use of Optional.

Which approach is likely to be the most efficient over the lifetime of a given service?

What is best way to reduce circular dependancy in following pseudo code

I am typically end of design my software architecture as follows, which is a dead end.

import ExtraWorld,SuperWorld;

class World{

 constructor(){
     let a = new ExtraWorld()
     let b = new SuperWorld()
 }
}
----
class SuperWorld extends World{
}

class ExtraWorld extends World{
}

How I can redesign the architecture and rename so that it makes much sense

mercredi 25 avril 2018

Best way(pattern) implement payment process by many types of payment in android

I have many types of payment in android app:

1. By barcode
2. By Nfc
3. By magnetic
4. By code
5. By somthing
........

I use Stratage pattern for this. I have Interface:

    public interface PaymentStrategy<T> {
    T pay(BigDecimal amount);
         }

I implement each type of payment. For example Barcode:

public class PaymentByBarcode implements PaymentStrategy<PaymentResponse> {

    private String barcode;
    private String userLogin;

    public PaymentByBarcode(String barcode, String userLogin) {
        this.barcode = barcode;
        this.userLogin = userLogin;
    }

    @Override
    public PaymentResponse pay(BigDecimal amount) {
        PaymentRequest paymentRequest = PaymentRequest
            .builder()
            .barcode(barcode)
            .userLogin(userLogin)
            .paymentType(PaymentType.BARCODE)
            .amount(amount)
            .build();
        PaymentResponse paymentResponse = makePaymentOnServer(paymentRequest);
        return paymentResponse;
    }
}

By person number:

public class PaymentByPersonNumber implements PaymentStrategy<PaymentResponse> {

    private String barcode;
    private String personNumber;

    public PaymentByPersonNumber(String barcode, String personNumber) {
        this.barcode = barcode;
        this.personNumber = personNumber;
    }

    @Override
    public PaymentResponse pay(BigDecimal amount) {
        PaymentRequest paymentRequest = PaymentRequest
            .builder()
            .personNumber(personNumber)
            .amount(amount)
            .paymentType(PaymentType.PERSON_NUMBER)
            .build();
        PaymentResponse paymentResponse = makePaymentOnServer(paymentRequest);
        return paymentResponse;
    }
}

And I have executor:

public class PaymentExcutor<T> {
    private PaymentStrategy<T> paymentStrategy;

    public PaymentExcutor(PaymentStrategy<T> paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    T ececutePayment(BigDecimal amount){
        return paymentStrategy.pay(amount);
    }
}

And for each tipy of payment I create concrete PaymentStrategy, set it to executor and try make payment:

PaymentStrategy paymentByBarcode = new PaymentByBarcode("12345", "test");
            PaymentExcutor<PaymentResponse> paymentExcutor = new PaymentExcutor<>(paymentByBarcode);
            PaymentResponse paymentResponse = paymentExcutor.ececutePayment(new BigDecimal(100));

This pattern work fine. I can add new type of payment easy and not rewrite code. But now I have some problem. In some cases I need confirm payment. Server send response wait confirmation of payment. On android side I need set one field (isConfirm = true) and send this paymentRequest(with isConfirm = true) to server. Bue=t I do not understend how can I doit with this pattern. My questions:

Can you say how similar tasks are implemented? Can there be an example? code on githab? article?

Good Scala pattern to consume from a Queue until there are no more messages?

I have a queue of N messages dispatched by an Actor, I want to consume them all. The actor will return either a Message type or a NoMessages type if the queue is empty.

I came up with this but doesn't feel idiomatic, and I'm not sure about how many threads I'm spinning up every time I call consume()?

What is a better way of doing this?

def main(): Unit = {

  val queue = system.actorOf(...)

  def consume(): Unit = {
    ask(queue, Read) foreach {
      case Message(m) => {
        // handle message
        consume()
      }
      case NoMessages =>  {
        system.shutdown()
      }
    }
  }
  consume()
}

Design patern for switchable basic/advanced user interfaces (Android)

I want my Android app to include two user-interfaces, one for advanced users and one for beginners, which users can switch between. I want the components to look different between the basic and advanced interface.* For instance, in advance mode I want

--------------------------------------
| icon | Title. Description | select |
--------------------------------------

and in the basic mode I want a button

--------------
| icon       |
| Long Title |
--------------

such that the drop-down menu in advanced mode (which includes options disabled and default) is replaced by a button (which toggles between disabled and default). These interfaces share common components, e.g., they both contain an icon and the drop-down menu (in advanced mode) behaves similarly the button (in basic mode), but they are also rather different.

Is there a design pattern for (an Android) app with a basic and an advanced user-interface?


* When the advanced interface simply includes more components than the basic interface, solutions seem straightforward. For instance, you can use
((View)findViewById(R.id.advancedComponents))
.setVisibility(basicView ? View.GONE : View.VISIBLE);
to add/remove advanced components. My problem is seems more complex.

Dependency injection issues with protocols

I have been researching various Dependency injection techniques as would like to introduce more of it into my app. I recently came across this article here

http://www.danielhall.io/a-swift-y-approach-to-dependency-injection

I quite like this approach as rather than doing my current approach of injecting viewModel and services into each new controller, it can be handled by a protocol. So I have setup a protocol like this

So first, I have created some viewModel protocols that looks like this

protocol ViewModel {
    associatedtype Service
    init (withService service: Service)
}

protocol ViewModelBased: class {
    associatedtype ViewModelType
    var viewModel: ViewModelType { get set }
}

So all viewModels that conform to viewModel have to have a service injected into it and it is up to the model to dictate which service is used. All classes that conform to ViewModelBased must contain a viewModel.

I have also created some more generics and protocols to allow controllers to be instantiated with a viewModel quite easily like this

   let loginModel = LoginModel(withService: LoginService())
   let controller = LoginController.instantiateController(with: loginModel)

This works fine but is rather cumbersome as every class that contains a viewModel requires this each time. So by researching the article Daniel hall created, I have come up with this

struct InjectionLoginModelMap {
    static var loginModel = LoginModel(withService: LoginService())
}
protocol LoginModelInjected { }
extension LoginModelInjected {
    var loginModel : LoginModel { get { return InjectionLoginModelMap.loginModel}}
}

I create one of these for each viewModel in the app. So instead of having to instantiate the viewModel myself each time, I just make sure my class conforms to the correct protocol each time. E.g.

class LoginController: UIViewController, LoginModelInjected {

This makes it easy to add multiple dependencies to a controller. It also means I no longer have to inject viewModel into controllers that need it as it is now handled by the protocol. So can initialise controller like this now

let controller = LoginController.instantiateController()

Then when I want to mock the services in unit testing, I can just call this

let loginService = MockLoginService()
let loginModel = LoginModel(withService: loginService)
InjectionLoginModelMap.loginModel = loginModel

This works quite well and is much less cumbersome than the previous method. My Concern however is that these models, once initialised will always be in memory. So even after I have finished with a controller and all its objects have been cleared from memory, the viewModel will remain even though it is no longer needed.

Was hoping for some advice on the best way to deal with this. I was considering maybe changing the InjectionLoginModelMap struct so viewModel is optional like so

struct InjectionLoginModelMap {
    static var loginModel : LoginModel? = LoginModel(withService: LoginService())
}
protocol LoginModelInjected { }
extension LoginModelInjected {
    var loginModel : LoginModel { get { return InjectionLoginModelMap.loginModel!}}
}

Then when I know I have finished with viewController and know that I no longer need access to that viewModel, I can just nillify it like so

InjectionLoginModelMap.loginModel = nil

However this too feels quite cumbersome and ugly. Would be very grateful if someone could give me some advice on best way to solve this. Also any other tips or advice on how others handle dependency injection would be much appreciated.

Thanks!

JSP Design pattern to handle changes to JAVA enums

We are building a framework Java Spring Controllers that interact with .jsp. The Java Spring Controllers have many enum's. My problem is that I want to access the enum, their values and their ordinals in jsp just like access the in Java.

For my enum

public static enum CurrentPosition {
        ON_TIME, SLIGHT_DELAY, DELAYED, CANCELLED, REACHED, BREAKDOWN
    }

I tried

<%@ page
    import="com.mnox.corporate.controllers.livetracking.TableMetaData.CurrentPosition"%>

This does not give me access to methods like values() or the ordinal.

I also tried JSTL

data.put("currentPositionEnumList", Globals.getEnumStringList(CurrentPosition.class)) ;

But this gives me only access to the enum values, not their ordinals

Finally I am left with writing code like below, to get list of all ride's on a particular enum value. This makes the code not flexible. Everytime I create a new enum, I have to change this code aswell.

private List<Long> listRideTrackingCurrentPositionOnTime, listRideTrackingCurrentPositionSlightDelay, listRideTrackingCurrentPositionDelayed,
            listRideTrackingCurrentPositionReached, listRideTrackingCurrentPositionCancelled, listRideTrackingCurrentPositionBreakdown;

I am new to JSP, is there a technology out there that solves this problem for me. I need complete access of my enum in jsp and html.

mardi 24 avril 2018

When does consumer implemented on blocking queue stop listening to messages

Hi have written a simple producer consumer problem using LinkedblockingQueue. My producer writes 1 to 10 in the queue and consumer reads from the queue using while loop inside run method as Below

    while(true){
                try {
                    System.out.println("Consumed: "+ sharedQueue.take());
                } catch (InterruptedException ex) {
}

As per definition of blocking queue, blocking queue is blocked if there are no messages in the queue and it waits until message is put in queue. Because I am use a while loop ,will my consumer be blocked indefinitely?

Factories in conjunction with XML-files to set up a program

up to this point I used config files (mainly XMLs) to store different configurations for my program. The program is highly modular. My idea was to create a hierarchy / multiple layers of factories that use each other, where the main factory reads in/parses the XML-file. The entire program is basically set up through dependency injection by the factories. However, I'm dealing with two issues:

  1. Is that the correct/standard way of setting up/configuring a program? What are my alternatives?
  2. How do I make sure that the configuration elements fit together. E.g. strategies will only work with specific other strategies. My feeling is that I either have to use A LOT of if-else constructs or a lot of factories that set up a certain "combination of config-elements", which will explode with the amount of possible combinations.

Reactor pattern with video streaming

When quality is top priority of your live video chat streaming server where there's a socket per thread for every in and out stream, Will a reactor pttern implementation harm the video quality in the terms of drop frames , packet loss etc..??

Update Model in Service Layer without reading the whole entity in MVVM

As known, the service layer is responsible for updating (and of course reading, writing and deleting) the models (or I may call them entities). Let us ignore Repository layer for now, because I do not like it, it just hides a lot of Entity Framework features.

The flow of data in a well designed system should be:

Service (model) <<<-->>> Controller (mapping Model <-> ViewModel)

To be able to update the Model in the database by the above data flow, I have to read the whole model from the database to the service to the controller, and use AutoMapper (for example) to map the data I got from the ViewModel to the Model (now we have the old model with some changed values). Now I can pass that edited Model back to the Service, and execute DbContext.Update(Model).

The cons of that is:

  • We had to issue additional read query to read the whole model (We had to do that, otherwise, DbContext.Update(Model) will leave the none mapped Property to default).

  • Also, Update query has been generated for the whole model (although I might only changed small part of the Model.)

I sometimes find that design patterns forces to hide a lot of feature which may make the program more efficient.

Is there any approach (or let us say a design pattern or any editing to service pattern) where I can map ViewModel to Model, and pass the Model to the Service, and update only the mapped Properties (so there is no need to read the whole entity before mapping the properties)?

no matching function for call to C++ constructor [duplicate]

This question already has an answer here:

#include "Generator.h"
#include <math.h>
#include <stdlib.h>
#include <time.h>

Generator::Generator(int inputbits):bits(inputbits)
{
    srand(time(NULL));
    bits=rand() % int(pow(2, inputbits));
}

Generator::~Generator()
{

}

int Generator::getBits()
{
    return bits;
}

.

#ifndef GENERATOR_H
#define GENERATOR_H


class Generator
{
    public:
        ~Generator();
        int getBits();
        static Generator* getInstance();
    private:
        Generator(int);
        int bits;
};

.

#endif // GENERATOR_H


#include "Generator.h"
#include "Proxy.h"

Proxy::Proxy(int inputbits):bits(inputbits)
{

}

Proxy::~Proxy()
{
    //dtor
}

.

#ifndef PROXY_H
#define PROXY_H
#include "Generator.h"

class Proxy: private Generator
{
    public:
        ~Proxy();

    private:
        Proxy(int);
        int bits;
};

#endif // GENERATORPROXY_H

These are my code. Error happens like this

||=== Build: Debug in FinalProject (compiler: GNU GCC Compiler) ===|
C:\Users\1\Desktop\2018 spring OOP\designpattern\FinalProject\Proxy.cpp||In constructor 'Proxy::Proxy(int)':|
C:\Users\1\Desktop\2018 spring OOP\designpattern\FinalProject\Proxy.cpp|4|error: no matching function for call to 'Generator::Generator()'|
C:\Users\1\Desktop\2018 spring OOP\designpattern\FinalProject\Generator.h|12|note: candidate: Generator::Generator(int)|
C:\Users\1\Desktop\2018 spring OOP\designpattern\FinalProject\Generator.h|12|note:   candidate expects 1 argument, 0 provided|
C:\Users\1\Desktop\2018 spring OOP\designpattern\FinalProject\Generator.h|5|note: candidate: Generator::Generator(const Generator&)|
C:\Users\1\Desktop\2018 spring OOP\designpattern\FinalProject\Generator.h|5|note:   candidate expects 1 argument, 0 provided|
||=== Build finished: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

Issues happens here : Proxy::Proxy(int inputbits):bits(inputbits) which is constructor of Proxy. I made some base class called Generator, and derived class which is private subclass of Generator and has private constructor. I cannot get why this error happens. Please enlighten me if you any idea. It would be apprieciated.

Java - why would one use the state design pattern over saving the state in a variable?

I am very new to Java so excuse me if this sounds like a dumb question.

Why is such a big effort made when following the state-design-pattern (creating an interface, context and concrete sub-classes for each state) when you could just save the state of a given object in a variable and then make decisions based on switch and if-else statements later on?

Send data from local to remote database

Suppose I have a database locally and I want to send data to a remote database. How would I know that there is a connection between the remote and local databases and know when there is no connection between them? In case of no connection, the data would be written to the logs and when the connection comes back up we would sort the data according to their timestamp locally and then send it to the remote server.

I was thinking of keep pinging the remote database, if we get a response to the ping then it would mean that the remote database is accepting requests otherwise there is no connection. But this would spam the server with lots of requests. Is there any better way?

Refactor switch to strategy pattern c#

I investigated a lot about refactoring switch to a hierarchy of classes by means of applying strategy pattern. All samples end up with instead of creating switch statement it just creates the dictionary with the same keys as in switch cases and as values it uses new classes for each case. What is the reason for doing this? According to SOLID open-closed principle, we still needed to go to the class with a dictionary and ADD NEW KEY over there simultaneously with adding the new class for type. We anyway forced to edit class with a dictionary, as for me it violates Open close principle Could anyone give me a good example of refactoring switch statement?

Make method testable for unit tests c#

So , i have the following code structure

public void method1(int index)
{
   switch(index)
   {
       case 1:
           Method2();break;
       case 2:
            Method3();break;
   }
 }

 public void Method2()
 {
     var entity = new SomeEntity();
     repo.Add(entity);

     var anotherEntity= new AnotherEntity();
     repo.Update(anotherEntity);
 }

While covering method2 with unit test, i ran into issue, that if i want to check that entity add to db, anyway it runs an update method too. How i can split it somehow, just wanna get maybe some best practices for method in which it's needed to do multiple operations with db. Thanks for helping me!

Design architecture for Flutter (MVC a good idea?)

my friends and I are developing our first cross-platform mobile application and we came across Flutter. We think its the perfect fit for our idea, but we have some troubles to find the right design architecture. We are used to the MVC principle, which isn't as common in Flutter as it is in other languages. Nevertheless, we found an article using the MVC principle: https://proandroiddev.com/mvc-in-flutter-ebfba2a78842

Is it a good idea to use it in that way? Would we still need Redux? What could you recommend us?

Thank you

Design pattern c++ [on hold]

Vous écrivez une application qui devra réaliser des cocktails. Un cocktail contient différents ingrédients (en fonction de la commande) et il peut vite devenir complexe à préparer. Néanmoins, les étapes du processus de préparation restent toujours les mêmes : ajouter un alcool, ajouter un sirop etc. quel patron de conception (design pattern) approprié pour préparer ces cocktails?

Optimal pattern to store dynamic tables from csv files in MySQL database

I want to import the table structure and the given data from uploaded CSV files into my database for later procession.

The files may vary in their number of columns and rows.

At the moment this is my approach using 3 tables:

  • csv_tables
    • id (PK)
    • name
  • csv_columns
    • id (PK)
    • csv_table_id (FK)
    • position
    • name
  • csv_datas
    • id (PK)
    • csv_column_id (FK)
    • row
    • value

It works ok, but I wonder if there is an better pattern known for this. I also do not like to iterate over all those DB entries to reconstruct the table and send it to my frontend wich expects the data in this format:

{
"table":
  {
    "name": "My table",
    "headings": ["col1", "col2"],
    "dataRows": 
      [
       {"col1": "my data 1", "col2": "my data 2"},
       {"col1": "my data 3", "col2": "my data 4"}, 
      ]
  }
}

Builder pattern does't return "this"

I used RestTemplateBuilder in spring boot today, and found its methods do not return "this", instead, they return a new builder instance.

public RestTemplateBuilder basicAuthorization(String username, String password) {
    return new RestTemplateBuilder(this.detectRequestFactory, this.rootUri,
            this.messageConverters, this.requestFactory, this.uriTemplateHandler,
            this.errorHandler, new BasicAuthorizationInterceptor(username, password),
            this.restTemplateCustomizers, this.requestFactoryCustomizers,
            this.interceptors);
}

This is the first time I saw builder pattern not returning "this" at the end. Is there any good reason to do so?

Use TOXI Solution in DataBase with Json data 101

we want to project a new database schema for our Society's application.

The program is developed in c# nancy serverside and react-redux-graphql on clientside. Our Society often must iplement repentine changing for treat new business data. So we want to realise a solid corefor the fundamental and no subject to decadence data eg: Article (Code, description, Qty, Value, Price, categoryId).

But often we need to add particular category to an article, or special implementation only for a limitated period of time. We are thinking to implement a TOXI like solution for treat those situations. But in TOXI pattern iplementation we wan to add a third table for define each tag data type and definition. Here is a simple explanatory image:

enter image description here

In the Metadata whe have two columns with JSON data: DataType and DefinedValue

  • DataType define How the program (eventually a func in db) must cast the varchar data in articoli_meta.value

  • DefinedValue is not null define if the type must have a serie of predefined value eg: High, Medium, Low etc...

Those two column are varchar and contain JSON with a predefined standard, a defined standard from our programming team (ev. an sql func for validate those two Columns)

I Understand thath this kind of approach is not a 'pure' relational approach but we must consider that we often pass data to the client in json format so the DefinedValue column can easily quered as string and passed to interface as data for a dropdown list.

Any ideas, experience or design tips are appreciated

lundi 23 avril 2018

Is it a natural design pattern to use closures and dynamically defined functions in Python?

I find that defining functions which ask the user to define and then pass in another function to be a very natural design pattern for me. For example,

def gradient_descent(x0, grad_f):
    x = x0
    for _ in range(100):
        x -= 0.1 * grad_f(x)
    return x

Implements a generic gradient descent routine; all the user has to do is define the gradient function for f. This is basically the interface used by scipy.optimize, and the programs I write tend to use various function closures and dynamically defined functions in a similar way.

However, I have found myself facing some serious difficulties in taking advantage of parallelism with multiprocessing since functions can't be pickled. I know that there are ways around this, but it makes me question whether programming like this is even a "pythonic" way to do things.

Is this a natural design pattern in Python? Is there a better way to design programs that will likely need to be refactored to use multiple processes?

Session layer design patterns

I am planning to build an app that will mainly fetch data from different services and display them to current logged in user.

The thing is that all the data that I fetch from three different api's I am not allowed to store them in database, so I will have to use session in that case.

My question is :

Does anyone has a suggestion on how to design a scuh application, is there any specific >design pattern that is based on session that I could possibly follow ?

in javaScript factory pattern i am not g undefined value

var peopleFactory = function (name,age,height){

var temp = {};

this.name = name;

this.age = age;

this.height = height;

temp.printPerson = function(){

console.log(this.name+''+this.age+''+this.height);

document.write(this.name+''+this.age+''+this.height);

};

return temp;

};

var person1 = peopleFactory('tanmay',27,5.11);

var person2 = peopleFactory('chinmay',37,5.12);

person1.printPerson();

person2.printPerson();

Create pattern of difference of two arrays of objects and apply it to another array in Javascript

I have array of two different objects (which can contain additional arrays of objects):

var array1 = [{"x":10,"y":10},{"a":10,**"b":10**,"c":10}]

and another array:

var array2 = [{"x":10,"y":10},{"a":10,**"b":25**,"c":10}]

I need "what is different on second array":

var tmp = **[{},{"b":25}]**

and now update array1 with the pattern tmp

Can someone help me on this? Your time is greatly appreciated.

What are the names of these design patterns and their use cases?

Suppose the following simple Object class:

class Object
{
public:
    Object();

    // Sets the name of this object
    void setName(const std::string &name);

private:
    Uuid id;
    std::string name;
}

We can encapsulate it using the following design patterns:

Design Pattern 1

class ObjectManager
{
public:
    ObjectManager();

    // Creates and stores an object, returning an unique id
    Uuid createObject();

    // Sets the name of object specified by id to name
    void setObjectName(Uuid id, const std::string &name);

private:
    std::vector<Object> objects_;
}

This pattern completely encapsulates the concept of Object. It provides calling code with identifier handles that can be used with an interface to manipulate the created objects.

Design Pattern 1 - Usage

 Uuid id = manager.createObject();
 manager.setName(id, "Hello World");

Design Pattern 2

class ObjectManager
{
public:
    ObjectManager();

    // Adds object to this manager (creates copy for example, could use shared_ptr)
    void addObject(const Object &object);

private:
    std::vector<Object> objects_;
}

This pattern puts the onus on calling code to create the object, modify it and then add it to the manager.

Design Pattern 2 - Usage

 Object object;
 object.setName("Hello World");

 manager.addObject(object);

Questions

  1. What are the names of these two design patterns?
  2. What are the pros and cons of each pattern?
  3. When should a programmer prefer one over the other?

Note: Please excuse the ambiguous title, I will update it once I have more information on the patterns to better represent the question.

Sortable Interface for different types of components react dnd

I was going through react dnd's documentation on creating a sortable example where I found a working example at http://react-dnd.github.io/react-dnd/examples-sortable-simple.html. I have use case similar to this where my list contains items of different types.

Is adding a common wrapper component over each type of list item, considered a good design option? This will help me retain the present architecture and not mess up things.

Something on below line

Overloading a method with a difference of list/array of type . Is that a correct approach?

I have a method in businessservice as follows,

public void ProcessModelId(int modelId){
   //method logic for a modelid....
}

Now the requirement is to send list of ids, so should i modify existing method or can i overload another method wit list of ids? like below?

 public void ProcessModelIds(List<int> modelIds){
   foreach(var i in modelIds){//method logic for each modelid....}

    }

which one is correct way in design perspective? or that doesn't matter?

Is downcasting in this situation acceptable?

I am currently part of a project creating a client-server model to automate a certain task. At a certain point in the project I had to perform downcast to do certain things. Generally, down-casting means your design is flawed. I raised this issue to my lead engineer but she said

It is okay to downcast an interface to its derived class but not an concrete class

I didn't really understand her explanation. Without delving into major details, I will supply a pseudo code describing the actual project scenario. Please note the following is an close enough analogy.

We have a base class UniversalAnimal

class UniversalAnimal{
    private:
        Type type;
        Colour color;
        int weight;
        int legs;
        int wings;
        int fins;
        int fangs;   
        // other common attributes for all animals; getters and setters 
}

So the universal animal class is like a place holder class for any animal. Note, it has fins (fishes), fangs (snakes) and wings (birds).

There is a AnimalFactory class which returns a GenericAnimal interface on the Type. For instance,

GenericAnimal animal = animalFactory.getAnimal(uniAnimal)

After getting a GenericAnimal from the factory; there are certain model specific methods to be called for further processing in the program. In order to call these specific methods, the GenericAnimal animal must be down casted to the corresponding derived class. For example;

class Snake implements GenericAnimal{
    int poisonLevel;
    int fangLength;
    int length;
    bool isPoisonous;

    void setPoisonLevel(int level){
       this->poisonLevel = level;
    }

    int getPoisonLevel const{
       return this->poisonLevel;
    }

    // other getters and setters
    // other methods overriding interface GenericAnimal
}

To set poison level to a snake;

UniversalAnimal uniAnimal = UniversalAnimal();
uniAnimal.setType(Type::SNAKE);
uniAnimal.setColour(Colour::BROWN);
uniAnimal.setFang(2);
uniAnimal.setFins(null);
//irrelevant attributes to snake like wings, fins are set to null by default

GenericAnimal gAnimal = animalFactory.getAnimal(uniAnimal);

if(gAnimal instanceof Snake)
  // checked downcasting
  Snake snake = (Snake) gAnimal;

snake.setPoisonLevel(3);
// call other methods specific to snake
}

Though this is an checked downcasting and will not throw a runtime exception; down-casting is generally means flaws in design. Also if the client who uses the factory needs know the type of the object then, I believe, using factory is a wrong design choice. Please give me insights and possible alternate design (if this design is wrong) for this problem.

dimanche 22 avril 2018

Desing conflict when programming with inheritance

So I am programming tree types of generic(key, value) bynary search trees, the basic one, which is unbalanced, it has add, search and delete operations. It has a Node(another k,v generic clases, used to store this data) attribute which is the root of the tree.The Next type of tree is a Red-Black Tree, so the big questions is how to use Java inheritance to code this new class using the first one as a basis. Its confusing to me because,althought both classes have a root attribute, one has a Node atribute and the other should have a Red-Black Node (which should extends from Node, adding a color attribute). I am kind of assuming that people know how a binary seach Tree works.Thanks in advance.

Stop a DispatcherTimer in a service class when application is closed

I am wondering what is a proper pattern for handling stopping of the DispatcherTimer when the application that uses this instance is closed. As the DispatcherTimer is not stopped, the app is not fully closed & disposed.

I can only think of the following:

public class ReminderServiceClass : IDisposable
{

    public ReminderServiceClass ()
    {

        this.Timer = new DispatcherTimer()
        {
            Interval = TimeSpan.FromMinutes(value: 10)
        };
        this.Timer.Tick += this.Timer_Tick;
        this.Timer.Start();
    }


     public void Dispose()
    {
        MessageBox.Show("Dispozed");
        this.Timer.Stop();
    }
}

and then in the view model / user control class call the reminderService.Dispose() method (or use it within a using block, however it doesn't seem right for 'ReminderService' class).

However, I don't like this approach because this means that ViewModels, User Controls or other classes need to be aware that there is a DispatcherTimer and are responsible for remembering that a Dispose needs to be called.

Is there any pattern which allows a more 'self-contained' approach for classes which use DispatcherTimer? Or perhaps I should use something else instead?

Thanks!

alternate solution for printing pattern using python

I want to print pattern using python and i have done it but i want to know other solutions possible for the same:-

A B C D E F G F E D C B A
A B C D E F   F E D C B A
A B C D E       E D C B A
......
....
A                       A

and here is my code:-

    n=0
for i in range(71,64,-1):
    for j in range(65,i+1):
        a=chr(j)
        print(a, end=" ")
    if n>0:
        for l in range(1,3+(n-1)*4):
            print(end=" ")
    if i<71:
        j=j+1
    for k in range(j-1,64,-1):
        b=chr(k)
        print(b, end=" ")
    n=n+1
    print()

Singleton with multi instance management

I'm trying to develop something with let's say :
A class : User
Several instances of User : "john", "joe", ...
I would like that each name is instanced only one time, so if the user tries to create an User wich name already exists, it returns the existing user instance.
With the singleton, I can only make one instance.
How can I do that?

How to get rid of ifs in this case?

I have the building process for Criteria SQL requests but this repeating if() extremely horrible. I want to get rid of theirs. May by Reflection API help me but my struggle is failing. Maybe some who help me with a small example.

@AllArgsConstructor
class PhoneSpecification implements Specification<Phone> {

    private final @NonNull PhoneFilter filter;

    @Override
    public Predicate toPredicate(Root<Phone> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        Predicate predicate = cb.conjunction();
        if (nonNull(filter.getId())) {
            predicate.getExpressions().add(cb.equal(root.get("id"), filter.getId()));
        }
        if (nonNull(filter.getNote())) {
            predicate.getExpressions().add(cb.like(root.get("note"), toLike(filter.getNote(), ANY)));
        }
        if (nonNull(filter.getNumber())) {
            predicate.getExpressions().add(cb.like(root.get("number"), toLike(filter.getNumber(), ANY)));
        }
        if (nonNull(filter.getStatus())) {
            predicate.getExpressions().add(cb.like(root.get("status"), toLike(filter.getStatus(), ANY)));
        }
        if (nonNull(filter.getOpName())) {
            predicate.getExpressions().add(cb.like(root.get("opName"), toLike(filter.getOpName(), ANY)));
        }
        if (nonNull(filter.getOpLogin())) {
            predicate.getExpressions().add(cb.like(root.get("opAccLogin"), toLike(filter.getOpLogin(), ANY)));
        }
        if (nonNull(filter.getOpPassword())) {
            predicate.getExpressions().add(cb.like(root.get("opPassword"), toLike(filter.getOpPassword(), ANY)));
        }
        if (nonNull(filter.getRegFrom()) && nonNull(filter.getRegTo())) {
            predicate.getExpressions().add(cb.between(root.get("regDate"), filter.getRegFrom(), filter.getRegTo()));
        }
        return predicate;
    }
}

I thying something like this:

Lists.newArrayList(Phone.class.getDeclaredFields()).forEach(field -> {
    field.setAccessible(true);
    try {
        field.get(filter)
        //...
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
});

But I confused can I get value and type, and name of field...

Maybe reflection isn't a good way and you know better? Design pattern or something else?

This filter DTO:

@Data
class PhoneFilter {
    private Pageable pageable;
    private Integer id;
    private Timestamp regFrom;
    private Timestamp regTo;
    private String number;
    private String opLogin;
    private String opPassword;
    private String opName;
    private String status;
    private String note;
}

samedi 21 avril 2018

Entity Component System removing entity

This is my first attempt to implement Entity Component System in my project and I'm not sure how some of its mechanics works. For example do I remove an entity? Since all systems are using entities list throughout whole game loop, every attempt of deleting element of that list is condemned to ConcurrentModificationException. Going by this advice I've tried to setting some kind of "toRemove" flag for entities and look for it every time system iterate through list

public class DrawingSystem extends System {

    public DrawingSystem(List<Entity> entityList) {
        super(entityList);
    }

    public void update(Batch batch) {
        for (Entity entity : entityList) {
            removeIfNeccesarry(entity);
            //code

            }
        }

        public void removeIfNeccesarry(Entity entity){
            if(entity.toRemove){
                entityList.remove(entity);
            }
        }

    }

but that didn't help getting rid of the exception. I'm sure there is a elegant solution to this problem since this design pattern is broadly used but I'm just not aware of it.

Nested call in Java (Decorator Pattern)

I'm working on a basic Pizza program.The program add toppings into pizza by using Decorator Pattern Design.

public static void main(String[] args) {
    Pizza pizza = new PizzaBakery();
    //lets put Onion,Pepper and Salami into pizza:
    pizza = new Salami(new Pepper(new Onion(pizza)));}

My code works well and manage to create pizza&put its toppings. The problem is that, I'll take pizza&Toppings orders from an input file.

Input file example:

AddTopping 7 HotPepper Soudjouk Salami (7 is the ID of the pizza)

AddTopping 1 HotPepper Onion

.....

and adding toppings into pizza must be nested(like new Salami(new Pepper(new Onion(pizza))) ) .Is there any different way/method to use instead of writing many if-else statements ?

Which pattern would you suggest for "do different things depending on configuration"?

Consider, in an MVC architecture, you have the following action:

    public String cancelMovement() {
    try {
        movementService.cancelMovement(movement);
    } catch (AppException e) {
        showMovement();
        this.addActionError(getText(e.getKey()));
        return INPUT;
    }
    return "saved";
}

Now the requiments change: : depending on movement.type, you should either just cancel the movement, or cancel movement + productService.revert(product) .

Question: What pattern would you use in this situation?

My considerations:

  1. I don't want to change the implementation of movementService.cancelMovement(movement), as it violates the open/closed principle (and single responsibility)
  2. In other situations I have used the decorator pattern (two different implementations of MovementService, one will cancel, the other will delegate to cancel and then revert(product). In this situation this doesn't seem appropriate because
  3. The MovementService has several other methdos (initiate, confirm,...) and a second implementation of MovementService wouldn't make sense for those methods.
  4. You would still need a place to determine which strategy to use (if movement.status.equals(type1)... do this; else do that)

Any suggestions are welcomed!

Add value to a match

I have many instructions like this one:

x.match('pattern') && x = 'pattern' + y;

Or similarly:

var a = 'pattern';
x.match(a) && x = a + y;

Is it the best way to write such instruction or is there a better way to write the same?

Why was cakePHP designed to use Inheritance over Composition even though it's mostly considered a bad design?

CakePHP Applications being made in our company tends to become unmaintainable as it becomes more complex. I figured that one specific reason is inheritance which makes the functions in child classes depends a lot on it's parent classes and vice-versa (implementing template method pattern). Why is CakePHP designed this way and not friendly in using Dependency Injection, Strategies, or Factory patterns?

vendredi 20 avril 2018

Wait for a function to finish before continuing in javascript

What I trying to do is to make the save method to wait for this.collection.create() before executing the save because otherwise it might crash.

class UserRepository extends BaseRepository<User>
{
    constructor()
    {
        super();

        this.collection = this.db.collection('users');
        this.collection.create().then(res => {
            if (res.code === 200)
            {
                // collection successfully created
            }
        }).catch(err => {
            if (err.code === 409)
            {
                // collection already exists
            }
        });
    }
}

class BaseRepository<T>
{
  protected db: Database = Container.get('db');
  protected collection: DocumentCollection;

  public save(model: T): void
  {
    this.collection.save(model);
  }
}

And then I can use it like this:

const userRepository = new UserRepository();
userRepository.save(new User('username', 'password'));

I can think of two solutions

  1. Run this.collection.create() synchronously
  2. Create a property called isCollectionReady and make a small loop in save method that wait for isCollectionReady value to change to true.

Is there any better way to do that?

What is the best way to implement "GetAll, GetBy" methods in repository pattern with Entity Framework Core?

I implement a repository pattern in my pet-project and I have a little question about realization of methods which return collections of items (for example: GetAll, GetBy). In current implementation the code of that methods look like below:

public IEnumerable<T> GetAll()
{
    return _context.Set<T>().ToList();
}

public IEnumerable<T> GetBy(Expression<Func<T, bool>> predicate)
{
    return
        predicate == null ?
            throw new ArgumentNullException(nameof(predicate)) :
            _context.Set<T>().Where(predicate).ToList;
}
public async Task<IEnumerable<T>> GetAllAsync()
{
    return await _context.Set<T>().ToListAsync();
}

public async Task<IEnumerable<T>> GetByAsync(Expression<Func<T, bool>> predicate)
{
    return
        predicate == null ?
        throw new ArgumentNullException(nameof(predicate)) :
        await _context.Set<T>().Where(predicate).ToListAsync();
}

I think that casting to list is not a good idea, so I tried to rewrite my code with using "yield return" and Enumerable, like below:

public IEnumerable<T> GetAll()
{
    foreach (var item in _context.Set<T>().AsEnumerable())
    {
        yield return item;
    }
}

But I have not found sample how to implement async version of this code. Could you give me some advice about best implementation of this stuff?

How can I clean up my Java Streams?

I have this stream, as well as quite a few others, where I abuse a bunch of calls to get the job done. Seems like an anti-pattern when taking advantage of J8.

+    Arrays.stream(resources)
+        .map(this::ingestFromFile)
+        .collect(Collectors.toList())
+        .stream()
+        .map(Container.class::cast)
+        .map(Container::getAll)
+        .flatMap(Collection::stream)
+        .collect(Collectors.toList())
+        .forEach(
+            dataType -> {
+              loaderConstants.getRepo(dataType.toString()).save(dataType);
+              LOGGER.log(Level.INFO, "Saved: " + dataType);
+            });

How can I shorten this up and what pitfalls should I look out for in the future to avoid this type of development?

Lowering tightly-coupled dependencies when waiting for client message

I'm currently designing a server-client game and would like to lower the amount of tightly-coupled dependencies within the game. Basically, I would like the client to change its state when receiving a message from the server. The pseudocode would look something like this:

    switch(inputThread.getMessage()){
    case "dead":
        die();
        break;
    case "heal":
        heal();
        break;
    }

The problem is that changing what gets sent on the server end requires me to also change the client end, which could be problematic if I want to send a large variety of messages. What design pattern could I use to separate the client and server?

Java Simple Factory with constructors using different parameters

I have two ways of saving data in my application: save to database and save to file. Since I don't want client code dealing with construction of objects I created a class that (to my understanding) is simple factory with a factory method. Code below:

public static DataPersister createDataPersister(Boolean saveToDb, Session session, String filename) {
    if (saveToDb) {
        return new DatabaseDataPersister(session);
    } else {
        return new FileDataPersister(filename);
    }
}

With this setup client code doesn't have to deal with constructing anything or deciding whether to save to DB or file - it can just call a save() method on an object returned by the factory like so:

DataPersister dataPersister = DataPersisterSimpleFactory.createDataPersister(this.savetoDb, this.session, this.filename);
dataPersister.save(this.data);

My question is - is this solution breaking SOLID principles? In order to create e.g. a DatabaseDataPersister client code needs to pass on a filename parameter, and this implementation of DataPersister won't have any use of it. I feel like it doesn't sit right with something similar to Interface-segregation principle but not quite that.

And if the solution is indeed a code smell - how do I go about cleaning it?

Pass field name/type as a parameter to a method in Java

I have a List of LocalizedAttributes

public class LocalizedAttribute<T> {
    T value;
    Locale locale;
}

I have a class which stores the list of the localized attributes;

public class A {
    .
    .
    private List<LocalizedAttribute> localizedAttributes;
}

I have a class which has some book related info.

public class B {
    private String title;
    private String summary;
    private List<String> authors;
    private List<Map<String, String>> publisherRoles;
}

I create a bunch of books

B bookRelatedInfo1 = new B(); ///fill in values;
B bookRelatedInfo2 = new B(); ///fill in values;
B bookRelatedInfo3 = new B(); ///fill in values;

I add this in an object of class A

A.setLocalizedAttributes(ImmutableList.of(
            new LocalizedAttribute(bookRelatedInfo1, new Locale("US")),
            new LocalizedAttribute(bookRelatedInfo2, new Locale("DE")),
            new LocalizedAttribute(bookRelatedInfo3, new Locale("JP"))
))

Now I want to extract list of localized titles, summary separately.

getLocalizedTitles(List<LocalizedAttribute> localizedAttributes) {
    return localizedAttributes.stream()
        .map(localizedAttribute -> {
            Locale locale = localizedAttribute.getLocale();
            B b = (B) localizedAttribute.getValue();
            return new LocalizedAttribute(b.getTitle(), locale);
        })
        .collect(Collectors.toList());
}

Now If I want to get list of summary I need to write the exact same method again except for b.getTitle and so on. Is there a cleaner way to do this?

jeudi 19 avril 2018

Architecture of desktop application Java/JavaFX

I want to write JavaFX desktop application.

I want to do it right, design proper architecture. But i don't know how to start designing architecture. What are the best design patterns or how to choose proper architecture for our solution. It has to be standalone app and in the future communicate with REST server.

Any tips about architecture of desktop application? In this project i want to develop some architectural skills.

I am confused on how to implement singleton pattern to my code and get it to call on my object classes and methods

As the title suggest, I'm trying to implement the singleton design pattern to my code. My code has a main class and 3 inherited classes. I would like to create only one object that is able to use all of the functions in the code. This is my first time dealing with design patterns so my code might be everywhere. Here is the code:

class geniusATM {

    private String name, address;
    private int pin, ficoScore;
    double checkingBalance, savingBalance, mortgageBalance;

    public geniusATM() {

    }

    geniusATM(String nam, String addr, int pn, int fs, double cB, double sB, double mB) {
        name = nam;
        address = addr;
        ficoScore = fs;
        checkingBalance = cB;
        savingBalance = sB;
        mortgageBalance = mB;
    }

         //setters and getters are here
        }

       class Checkings extends geniusATM {
        //stuff here
          }

       class Savings extends geniusATM {
        //stuff here
         }

       class billPay extends Checkings {
       //stuff here

       }

     public class singletonObject {

      private static singletonObject ob;

    private  singletonObject() {
        geniusATM matt = new geniusATM("Matt", "124 Road Drive.", 1234, 3462, 560.00, 500.50, 472.29);

    }

    public static singletonObject getObject() {
        if (ob == null) {
            ob = new singletonObject();
        }
        return ob;
    }

    public static void main(String[] args) {


    }


}

How to make independent module with delayed callback information in Java project?

Im writing a project in Java with Spring boot. Im trying to write independent module (maven module) which sends data to verification.

Process looks like:

  1. Post data to REST API, get verification ID.

  2. Ask REST API (using ID) after some time about verification status or make REST endpoint and automatically get informed by external API when verification is done.

So in my independent module I got REST endpoint which gets data from fronted and sends it to external API. Then I retrieve assigned ID (which needs to be added to User Entity) and I don't know how to pass it to Main project module. My independent module does not know that Main module exist. Also I don't know how to pass verification status when my independent module will be informed by external API.

Is my idea a good approach at all ? Or maybe I should place REST endpoints in Main module and treat my independent module as service (through interface) which only sens data and retrieve ID? But then REST endpoint which expect information from external API also must be in Main module and I won't feel that this is separated functionality.

Thanks for any architecture advices.

wordpress design pattern name

Wordpress have a very nifty feature to add custom types: the field post_type in wp_posts. to create a new post type, plugin auothor needs to come up with a new value to put in the field and more tables that links to the wm_post table.

this feature repeats itself in many other cms systems.

My question is: is there a name for this design pattern?

Is this cyclic dependency

class foo{
Bar b;
}

class bar{
Class clazz = foo.class;
}

Does the above snippet show cyclic dependency. Class foo has a reference of bar class object. Class bar has reference to foo class itself.

Validation pattern of javascript

my validation is only input 0-9 and x,X

do not input 'space' or 'negative' numbers.

what type of pattern use??

/[^\dxX]/gi it not work on -1 , -2 ,etc

How to solve circular dependency in Scala?

I faced a problem with circular dependency in my Scala app. To give you more context, I have the structure below:

trait BTService extends CService with PMService

trait PMService extends CService

trait CService

In BTService I need some functionality from CService and in PMService also. I can see that there is a redundant dependency here (CService) but how can I avoid it?

Code design with Java Generics

Consider the following code:

interface A<T> {
  boolean someMethod(T obj);
}

class B<T> {
   T obj;
}

class C<T> {
  B<T>[] bObjs;

  public someMethod(A<T> aParam) { 
    //do some stuff
    if(bObjs!=null && aParam!=null) {  
       for(B<T> bObj: bObjs) {
         if(aParam.someMethod(bObj.obj) {
           //doSmth
         }
       }  
      //do smth
    }
    //do smth
  }

Problem: use of bObjs and aParam is optional, but it force users of class C to use the type parameter, even when not needed. Is there a way of designing the problem so that this is unnecessary? If I use a wildcard generic such as B<?>[] bObjs and A<?> aParamthen I can't use the method aParam.someMethod(bObj.obj). Is there any way of type checking/type casting to allow use of this method without requiring type parameters? The actual code is obviously more complex, and involves a lot of logic where aParam is used if present - the use of bObjs is pretty much limited to use of a single method involving aParam.

Thanks a lot!

Complex object inside another one

I have the following class

class A {
private:
   B b;
public:
   A();
}

class B {
public:
   void foo();
   void bar();
   void foz();
   ........
}

B has a lot of methods. Sometimes is needed for a "customer" of class A to use method of class B. I could return a reference of B, but in this case I should return a const reference because returning a non-const reference of a private object is not good programming. If the reference is const, foo, bar and so on can't be called because they aren't const. So the only "clean" way seems to recreate the same interfaces in A using delegation to B. But this approach is not really good because I should recreate all the interfaces in A. As alternative I could set B as public in A, but it seems "strange" to me. What should I do in this case?