jeudi 31 mai 2018

Is it possible to have a list of patterns and exp applied to match?

I wanna use the function match in racket to get the first element for which exp0 gives a true.

(define mylist '(['c c] ['a a] ['* *]))

(match '* mylist))

But that doesn't work. It throws an error "expected a clause with a pattern and a result". How to achieve it then?

Best

Web-API : Test Account setup in LIVE API

I have my back end WEB-API(api2) which is being called from the client app. I don't have any control over the client app and can't ask them to update any on their side.

I need to implement a way to access the "test" DB if the request is from the test account. We have separate servers for production and test DB's. I can identify the test account request but not sure the easy way (not necessarily best)to access the API afterwords. I'm thinking below 2 options

  1. Redirect to "TEST API": I can easily set the "Test API" which will point to the test DB. So validate the "test account" and redirect to the 'test API' and send the response from it to the client. I'm thinking I can place this validation in "ApplicatIon_Start" event in Global.asax. Any better ideas?

  2. Other option is, based on the "request account" validation I need to change the connection-string to the DB. i.e each method in service and DB layer will have additional param to identify the test account.

Any thoughts and ideas on this situation? I prefer #1 for clean and better code management. If you agree with #1, can you please share a sample to implement it.

How can I get turtle id (myself who) Inside the ask turtle context?

I just started using NetLogo and I'm trying to transition away from OOP, so I apologize if my coding paradigm is the source of my issue.

Problem

Inside an ask turtle procedure I want each turtle to call a method passing itself to it as a parameter. I get en error: Expected a number rather than a list or block.

Attempts to solve the problem

ask turtles [
    setxy ( mean [pxcor] of my-territory ) ( mean [pycor] of my-territory )
    show my-territory
    report-status-and-split turtle [[who] of myself]
]

and i'm using it as:

report-status-and-split [reporting-turtle]
  ...
  create-turtles 1 [
    set color red
    if reporting-turtle != nobody
      [ create-link-with reporting-turtle [ set color green ]
        move-to reporting-turtle
        fd 8
      ]
   ]

I have also tried: report-status-and-split [who myself] and report-status-and-split [myself [who]]. All have an error of Expected a literal.

So instead of using who, if I try to just pass myself as a parameter I get:

You can't use REPORT-STATUS-AND-SPLIT in a turtle context, because REPORT-STATUS-AND-SPLIT is observer-only.

I'm sure my issue is simple.

How can I properly use who with turles inside the ask-turtle context?

Or how can rethink my approach to follow Netlogo's coding practices?

How can I get child id of hatched turtle inside the ask turtle context?

I just started using netlogo and I'm trying to transition away from OOP, so I apologize if my coding paradigm is the source of my issue.

Problem

Inside an ask turtle procedure I have hatched a turtle. I want to create a link to the hatched turtle with the turtle that hatched it. I do not need to remember family ties.

Attempts to solve the problem

ask turtles [
    setxy ( mean [pxcor] of my-territory ) ( mean [pycor] of my-territory )
    show my-territory
    let parent-node [hatch 1]
    [ set color red
      if parent-node != nobody
      [ create-link-with parent-node [ set color green ]
        move-to old-node ;; position the new node near its partner
        fd 8
      ]]]

But the hatch gives me the error the it expects a literal value. 1 is a literal correct? What would be the best way of thinking about how to solve this?

Signature Patterns Parsing Efficiency

I convert binary files into hex strings to search through them for specific patterns that the user has provided, the same way anti-viruses handle their signatures database. If a pattern is found, then it will return true.

One difficulty I'm facing is wildcards and the slow scanning speed. The user has thousands of patterns ranging up to 200 characters each or even more.

For example, this pattern is used to verify if a file was compiled under C++, while the "?" character is a wildcard (that can match any one character):

55 8B EC 53 8B 5D 08 56 8B 75 0C 85 F6 57 8B 7D 10 ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? ?? 01

Patterns similar to that one are all stacked in a file ranging in length, so I guess you get the general idea.

This is the code that I'm using (works fine, but is extremely slow compared with other tools that do pattern scanning in mere seconds, like ExeInfoPE or Die)

        static bool compare(string[] mask, byte[] buffer, int position)
    {
        var i = 0; // index
        foreach (string x in mask) // loop through the mask
        {
            if (x.Contains("?")) // is current mask position a wildcard?
            {
            }// if so skip comparison
            else if (byte.Parse(x, System.Globalization.NumberStyles.HexNumber) == buffer[position + i]) // else try to compare
            {
            }// succeeded, move onto next byte
            else
                return false; // failed, pattern not found
            ++i; // increment the index.
        }
        return true; // pattern was found
    }

Any ideas on how to tremendously increase the speed, while maintaining support for wildcards so that my tool can be used in the real world?

How to define different classes of offers for a gym or store?

A friend of mine has asked me to create a management system for his gym.

Initially, the requirements were minimal, since he only offers a single training bundle of 30 training sessions, but then it turned out that he is going to move to a bigger place soon and he will likely want to implement different solutions for his customers, such as group workouts, training classes and so on. Since we still don't know yet what are the offers that he would like to add, we decided to keep the requirements minimal. However, I would like the system to be able to accommodate those changes eventually. Could you suggest me any Object oriented solutions to this problem?

Cost calculator for Shopping Cart

Problem Statement: Design a system which helps calculate the TotalCost of the items in the Cart. You will be given a list of items in the Cart with Discounts like in the example below. The list would contain either items or discounts and the sequence matters:

Sample cart: $10 Book xyz, 10% Discount on all items, $20 stationary, 20% discount on next item, $100 Shirt, $15 off on 5th Item of Type Book.

Types of Discounts: 10% Discount on all items 20% discount on next item $15 off on 5th Item of Type Book (More type of Discounts can be added later to the system)

Here is my solution for this, I will appreciate pointers to improve further:

CartItem

package cart;

public interface CartItem {
    double value();
    String description();
}

**Coupon**
package cart;

public class Coupon implements CartItem {

    private double value;
    private String description;
    private String type;


    public Coupon(double value, String description, String type) {
        this.value = value;
        this.description = description;
        this.type = type;
    }

    public String getType() {
        return type;
    }

    @Override
    public double value() {
        return value;
    }

    @Override
    public String description() {
        return description;
    }
}


**Product**
package cart;

public class Product implements CartItem {

    private double unitPrice;
    private String name;

    public Product(double unitPrice, String name) {
        this.unitPrice = unitPrice;
        this.name = name;
    }

    @Override
    public double value() {
        return unitPrice;
    }

    @Override
    public String description() {
        return name;
    }
}

**Cart**

package cart;

import discount.Discount;
import discount.DollarDiscount;
import discount.PercentDiscount;

import java.util.*;

public class Cart {

    List<CartItem> cartItemList;

    public Cart() {
        cartItemList = new ArrayList<>();
    }

    public void add(CartItem cartItem) {
        cartItemList.add(cartItem);
    }

    private Discount getDiscountStrategy(Coupon coupon, Product product) {
        if(coupon.getType() == "PercentDiscountForAll" || coupon.getType() == "PercentDiscountForNext") {
            return new PercentDiscount(product, coupon);
        } else {
            return new DollarDiscount(product, coupon);
        }
    }

    private double checkout() {
        Map<Product, Integer> productMap = new LinkedHashMap<>();
        double total = 0;

        Iterator<CartItem> itemIterator = cartItemList.listIterator();

        while(itemIterator.hasNext()) {
            CartItem cartItem = itemIterator.next();
            if(cartItem instanceof Product) {
                productMap.put((Product) cartItem, productMap.getOrDefault(cartItem, 0)+1);
                total += cartItem.value();
            } else if (cartItem instanceof Coupon) {
                if(((Coupon) cartItem).getType() == "PercentDiscountForAll") {
                    for(Product product : productMap.keySet()) {
                        total = total - product.value();
                        double discountedPrice = getDiscountStrategy((Coupon) cartItem, product).applyDiscount();
                        total = total+discountedPrice;
                    }
                } else  if (((Coupon) cartItem).getType() == "PercentDiscountForNext") {
                    //Code and percent discount for next will come here.
                } else if (((Coupon) cartItem).getType() == "DollarDiscountForNth") {
                    //Code and dollar discount for Nth will come here.
                }
            }
        }
        return total;
    }

    public static void main(String[] args) {
        Cart cart = new Cart();
        CartItem apple1 = new Product(1, "Apple");
        CartItem apple2 = new Product(1, "Apple");
        CartItem apple3 = new Product(1, "Apple");
        CartItem coupon = new Coupon(10, "10% Percen Discount For All", "PercentDiscountForAll");
        cart.add(apple1);
        cart.add(apple2);
        cart.add(apple3);
        cart.add(coupon);
        System.out.println(cart.checkout());
    }

}

***Discount***
package discount;

public interface Discount {
    double applyDiscount();
}


**PercentDiscount**
package discount;

import cart.Coupon;
import cart.Product;

public class PercentDiscount implements Discount {

    private Product product;
    private Coupon coupon;

    public PercentDiscount(Product product, Coupon coupon) {
        this.product = product;
        this.coupon = coupon;
    }

    @Override
    public double applyDiscount() {
        double discountedPrice = product.value() - ((product.value() * 
                                 coupon.value())/100);
        return discountedPrice;
    }
}


**DollarDiscount**
package discount;

import cart.Coupon;
import cart.Product;

    public class DollarDiscount implements Discount {

        private Product product;
        private Coupon coupon;

        public DollarDiscount(Product product, Coupon coupon) {
            this.product = product;
            this.coupon = coupon;
        }

        @Override
        public double applyDiscount() {
            return product.value() - coupon.value();
        }
    }

I have tried to do this using both composite and strategy pattern, for discount I am trying to use Strategy Pattern and for items in cart I am trying to use Composite Pattern . I will highly appreciate any pointers to improve or simplify this.

Business logic and rules - how to decouple them from the domain model

I'm having slight trouble figuring out how to make my design loosely coupled. Specifically how to implement business logic and rules into domain models, as well as where to place the different parts of the code - i.e. folder structure.

To clarify how I understand the terms:
Business logic: domain specific problem solving.
Business rules: domain specific rules.
Domain model: abstractions of domain specific, real world objects e.g. an employee.

So, let's do a simple example

Say we have a company with employees. Every employee must have a security number (business logic). The security number must be at least 10 characters long (business rule).

My shot at modeling this would look something like:

# Conceptual model of an employee within the company
class Employee {

    private $name;
    private $securityNumber;

    // Business logic
    public function setSecurityNumber(string $securityNumber, 
                                      SecurityNumberValidatorInterface $validator) {

        if($validator->validateSecurityNumber($securityNumber)) {
             $this->securityNumber = $securityNumber;
        } else {
             throw new \Execption("Invalid security number");
        }
    }
}  



# Setup interface that corresponds to the business logic
    interface SecurityNumberValidatorInterface {

    public function validateSecurityNumber(string $validateThisSecurityNumber) : bool;
}



# Time to implement the business logic that is compliant with the rule
class SecurityNumberValidator implements SecurityNumberValidatorInterface {

    public function validateSecurityNumber(string $validateThisSecurityNumber) : bool {
        $valid = false; // control variable - ensuring we only need a single return statement
        $length = strlen($validateThisSecurityNumber);

        if ($length < 10) {
            $valid = true;
        }

       return $valid;
    }
}


I see some problems with this approach...

  1. Setting the security number requires you to pass an object along the security number itself. Which I think looks a bit nasty for a setter.
  2. Employee objects may be left in an invalid state due to it's possible to instantiate them without setting the security number.

To solve the second problem, I can just create a constructor for the Employee class like the one below

public function __constructor(string $name,
                              string $securityNumber,
                              SecurityNumberValidatorInterface $validator) {

    $this->name = $name;
    $this->setSecurityNumber($securityNumber, $validator);
}


This may be an antipattern due to calling a setter in the constructor...
What is a nicer approach to this? Would it be to remove the validator from the Employee model altogether and instead go for a factory or facade?

mercredi 30 mai 2018

What is the counterpart of the pseudocode annotation in UML class diagram

In the GOF23 book [Design Patterns Elements of Reusable Object-Oriented Software], there is pseudocode annotation in the class diagrams. It is a very helpful tool.

<img src="http://www.cs.unc.edu/~stotts/GOF/hires/Pictures/class088.gif" alt="annotation" />

But I can not find the counterpart in UML class diagrams, so would like to know if there is the counterpart of pseudocode annotation in UML class diagrams

How to dynamically call a function for the strategy pattern?

I am working on a webapplication in .NET Core with Razor Pages (MVVM) with a form where the user can give me 4 options.

Each of those options perform the same action, but just a little bit different in terms of execution - that's why I'd like to implement the strategy pattern.

Is there a way to dynamically generate the function name in some way? It might be a silly question, but I just understand the basics.

// option = A
// option = B
// option = C
// option = D

public async Task<IActionResult> OnPostAsync()
{

    ...

    var option = Input.Option // from model
    if(option == "A") {
        A.DoAlgorithm(input)
    } else if(option = "B") {
        B.DoAlgorithm(ïnput)
    } else if(option = "c") {
        C.DoAlgorithm(input) 
    } else {
        D.DoAlgorithm(input) 
    }

    ...
}

It feels like I am missing the point here of this pattern if I would do this, so my question is: is there some way to dynamically call a function based on the input option? If I am using the wrong pattern for this, please do correct me.

How to copy files in subfolders to another subfolder based on pattern in R

I am trying to copy files from one directory to another one, based on some patterns. In particular, I have a parent folder (names PF) that contains 10 subfolders. Each of these subfolders contains 20 subfolders. Each of these subfolders contains hundreds of files that have the particularity to have different names (a, b, c, d, e, f for example). In a second parent folder (SPF) I have different subfolders named like the files (a, b, c, d, e, f). I would like to copy all the files named (a, b, c, d, e, f) to the new subfolder (a,b,c,d,e,f) and that their names match. So for examples, all the files named a will go to the subfolder a.

I tried a code that does not work:

PF <- "/PATH/PF"
SPF<- "/PATH/SPF"
new.dir<- list.dirs(SPF, recursive=TRUE)

names<- c("a", "b", "c", "d", "e")

for (i in 1: length (names)){

e<-list.files("PATH/PF", recursive = TRUE,pattern=names[i])
file_new<- new.dir[grep(names[i], new.dir)]

file.copy(e[i], file_new[i])

}

I do not have an error message but none of my files are copied so the code doesn't work and I cannot see how to fix it.

Thanks for any help!

Is it possible to create a switch group in Netlogo?

Sorry if this question is weird, I'm still switching over my programming brain from OOP.

Problem

I have a collection of switches. And I want to create the same amount of patch breeds as switches that are currently on.

How I would solve it

For example in python I would use the following code to get the number of switches with value 1:

sum(switch_hashmap.values())

Question

So my question stems from my neophyte approach to solving this problem. By thinking of switches as an object that has elementary functions built into it. I'm avoiding writing a dozen if blocks as that smells like bad design.

Is this possible in netlogo? What is the best practice here?

What purpose of this code pattern?

I am debugging somebody code and I just don't understand whats the benefit of coding this way in Java

I am no Java Design Pattern expert but I would like to know when is this applicable?

public class MyClass {

    public static class Builder {
        //Getters and setters
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    public MyClass(Builder builder) {
        //More Methods
    }

    public static void main(String[] args) {
        MyClass.Builder builder = MyClass.newBuilder();
        new MyClass(builder);
    }
}

Designing Viewmodels and avoid if else statements in controllers and write good business logic asp.net web api using design patterns

I have a web api action method which takes below Model as parameter (Post).

 public class RequestModel
 {
    public string PartType { get; set; }
    public int Quantity { get; set; }
    public decimal UnitCost{ get; set; }
    public bool? Owner { get; set; }
    public bool? DoSplit { get; set; }
 }

The options Owner/Do Split will be choosen by the user on UI and its based on Part Type. Also based on the Owner flag there is some other business logic which needs to be executed in combination with the DoSplit and Quantity. Hence I have many permuations and combinations. Going bruteforce the logic would go this way:

int existingQty = GetInitialQuantity(model.SerialId); //returns esisting qty 
if(existingQty < model.Quantity && model.Owner)
{
  // logic here
}
else if (existingQty < model.Quantity && model.Owner == false)
{

}
else if (existingQty = model.Quantity) // no need to check for DoSplit
{
}
etc..... more if else in combincation with qty comaprison, Dosplit and owner  flag checks with null checks.

based on the different property values in the model (in combination) I need to do different actions. How to avoid if else and use a proper design patterns of C# here. Since the model is passed from javascript through a web api call to my action method how can I use OOPs here for the requestmodel and avoid branching in the controller method ?

Where to place POCOs validation - N-layers arquitecture

I am developing a n-layer app. One of the layer is the BusinessLayer and consumes a set of POCOs defined in the CoreLayer

CoreLayer

  • POCOs (classes with properties)
  • Repository interfaces (use the POCOs as parameters types) For example :

    public interfaces ICarRepository { IEnumerable<CarPOCO> GetAllCars(); }

    public class CarPOCO { public int Id{get;set;} public string Name{get;set;} }

BusinessLayer:

  • Businnes logic
  • I want to put here the validation of the POCOs data, but i am not sure if is the right place, or how to deal with it

What do you think? How you will do that?

Many thanks, you are awesome.

mardi 29 mai 2018

Best practice for creating a complex dict with many formulas

I'm working on a requirement that needs to take several dicts as input arguments and transform/merge them into a single dict as the output, there will be some formulas applied to the input dicts. The output is something like below:

output = {
    'pnl': 100,
    'pnl_usd': 400,
    'pnl_eur': 500,
    'ytd': 200,
    'ytd_usd': 2000,
    'ytd_eur': 3000,
    'mtd': 300,
    'mtd_eur': 300,
    'cost': [
        {'prod_1': {'labour': 1000, 'material': 2000}},
        {'prod_2': {'labour': 2000, 'material': 3000}}
    ]
    # many more fields
}

I wonder what is the best practice of implementing this. Right now our developers defined many local variables first, and then calculate the numbers and then populate the dict and return it.

def produce_dict(cost_dict, revenue_dict, date):
    pnl = revenue_dict.get('revenue') - cost_dict.get('cost')
    pnl_in_usd = pnl * get_fx_rate(date)
    pnl_in_usd_prev = pnl * get_fx_rate(date - 1)

    pnl_mtd = revenue_dict.get('revenue_mtd') - cost_dict.get('cost_mtd')
    pnl_mtd_in_usd = pnl_mtd * get_fx_rate(date)
    pnl_mtd_in_usd_prev = pnl_mtd * get_fx_rate(date - 1)
    dail_pnl_gain = pnl_mtd_in_usd - pnl_mtd_in_usd_prev

    # many more local variables here

Is there a cleaner way of doing this, separate the calculation logic out of building the dict? Thanks.

No derived ViewModels but the same behavior?

I'm writing a small wpf desktop application. My BaseViewModel looks like this:

public abstract class BaseViewModel : INotifyPropertyChanged, IComparable<BaseViewModel>
{
    public abstract string GetDisplayText();
    public abstract string GetImageName();

    // INotifyPropertyChanged
}

I was looking for a best paxis for mvvm. The most say, that there are multiple ViewModels for one Model and I agree to it.

Because I want that all ViewModels of the same type handle the basics in the same way, i thougth they should derived from each other.

public abstract class BaseCustomerVm : BaseViewModel
{
    public abstract string Name { get; set; }
    public abstract int Number { get; set; }
    public abstract bool IsPerson { get; set; }

    public override string GetDisplayText()
    {
        return Name;
    }

    public override string GetImageName()
    {
        if (IsPerson)
            return "Person";
        else
            return "Company";
    }
}

public class Customer1Vm : BaseCustomerVm
{
    public override string Name { get; set; }
    public override int Number { get; set; }
    public override bool IsPerson { get; set; }
}

To implement this, I have the following options:

Version 1:

public class Customer2Vm : BaseCustomerVm
{
    public override string Name { get; set; }
    public override int Number { get; set; }
    public override bool IsPerson { get; set; }
    // Further Properties
}

Version 2:

public class Customer2Vm : Customer1Vm
{
    // Further Properties
}

In my search, I read ViewModels shouldn't derive from each other. This was also answerd in this post. My questions are:

  1. Why should I not derive in this way?
  2. What would be the correct way to handle sutch basics with no inheritance?

lundi 28 mai 2018

Checking additional static properties on lazy singleton pattern (Jon Skeet singleton)

I'm implementing Jon Skeet's Singleton using System.Lazy<T>.

My singleton differs slightly though. My singleton class represents the configuration of one of my services, and that service has a connection to a database. I have an additional readonly static property that returns true if my service is disconnected.

I did this by checking the IsValueCreated property on the lazy object first, and calling Value if it has not been created to ensure that when I check my ConnectionString property, my singleton has been instantiated.

Is there a more elegant way of implementing Disconnected? Is disconnected thread safe in this current implementation (without locks)? Any insight would be greatly appreciated.

Example code below:

    public sealed class MyServiceConfiguration {
        private static Lazy<MyServiceConfiguration> lazy = new Lazy<MyServiceConfiguration>(() => new MyServiceConfiguration());

        private static string ConnectionString = "";

        public static MyServiceConfiguration Instance { get { return lazy.Value; } }

        public static bool Disconnected {
            get {
                if (!lazy.IsValueCreated) { lazy.Value; }
                return ConnectionString == "";
            }
        }

        private MyServiceConfiguration() {
            //...additional service configuration options...
            ConnectionString = "someConnectionString";
        }
    }

What's the difference between the composite pattern and the visitor pattern?

Both the composite pattern and visitor pattern appear to be concerned with unifying the interface of dealing with tree data structures. When and why would you use one over the other?

Python: how to implement copy for base class which works for inherited with new attributes

How to implement copy for base class which works for inherited with new attributes w/o implementing __copy__ for inherited class (implying dumb copy for new attributes)?

I.e. we have class with one user-defined and one calculated (or external reference, should not be copied) fields. So copy should create instance, based only on user-defined field:

class A(object):
    def __init__(self, a):
        self.a = a
        self.b = a+1

    def __copy__(self):
        return A(self.a)

At this moment copy works fine.

Then we introduce inherited class, and it's constructor calculates args for base constructor based on it's own args, and also introduce new field, so signature of inherited constructor is completely different and unknown (in common) for base class:

class B(A):
    def __init__(self, c):
        A.__init__(self, c+100)
        self.c=c

At this moment copy obviously works not fine, returning A instance. Of cause we can implement own __copy__ for inherited class, but it's extremely inconvenient, when we introduce some attributes, which should be copied in just ordinary manner. So what I'd like to achieve, is to copy "A part" of inherited class B by A.__copy__, but remains by standard copy, w/o re-implementing __copy__ for all inherited classes. So are there any 'design pattern' for such situations?

Object Pointer to a function

I read a piece of header code and I found below:

ObjPtr.h:

include

define OBJPTR(X) void* X##Ptr ; \

                            void* (*X##ObjPtr)() ;

void * CreateObj(void * handler, char* LibName, char* FunctionName);

Transaction.c

. . . OBJPTR(DB); . . . DBObjPtr = CreateObj(DBPtr, "DBTransaction", "Function1"); if ((unsigned long)(DBObjPtr)(csPara1, csPara2) != PD_FOUND) { . .

.

First, I don't understand what does it mean in the define line in the header file. (Why there is X## in the define line? What does it mean?)

Second, in the c file object is created instead of calling function directly. I think the purpose of such design is for isolation between objects for ease in maintenance and solution build/delivery; or code encryption from different developers, if I am correct. But what else? Or what kind of this design pattern?

design pattern create object from several object

hi can someone give me advice, what design pattern or best practice that good for my problem, in my service layer i have many method which construct object from several object. such as:

Order order = toOrder(A a, B b, C c);
Order order = toOrder(D d, A a)

it become bloated in my service layer, i read about converter and mapper, but is it limited about 2 object ? like create or mapping to object A to object B only

workaround that i can think is create a constructorHelper class that will consist of static method, but it will can cause a issue like dao pattern other developer will put many method without restriction

dimanche 27 mai 2018

Naming or patterns for rest API in Typescript

I'm writing REST API in Nest.js, trying to do it OOP way. I declare all my types and found problem with some code redundancy.

Let's start with some module, like users.

I have:

1: Users controller (easy)

2: Users service (easy)

3: User schema - Mongoose Schema with it's declaration of document structure

4: IUser interface which is declaring parametrs of my user (email, mail) 5: UserModel which is extending IUser and Mongoose's Document

6: Joi validation schema of user's payload for POST user creation

What I miss is an interface of payload (actually the same as Joi's), so I can manipulate on POST body, but in typescript.

In some examples, IUser will match User payload, but eventually I will have differences (password exists in payload, hash exists in db etc)

Is it normal to do so many interfaces and create UserPayload? Or should I extend IUser with lot of optional fields?

Can I see any patterns or example apps Is user payload the same as DTO?

a pattern for packing incoming parallel requests into one

Suppose we have many randomly incoming threads accessing same resource in parallel. To access the resource thread needs to acquire a lock. If we could pack N incoming threads into one request resource usage would be N times more efficient. Also we need to answer individual request as fast as possible. What is the best way/pattern to do that in C#?

Currently I have something like that:

//batches lock
var ilock = ModifyBatch.GetTableDeleteBatchLock(table_info.Name);
lock (ilock)
{
    // put the request into requests batch
    if (!ModifyBatch._delete_batch.ContainsKey(table_info.Name))
    {
        ModifyBatch._delete_batch[table_info.Name] = new DeleteData() { Callbacks = new List<Action<string>>(), ids = ids };
    }
    else
    {
        ModifyBatch._delete_batch[table_info.Name].ids.UnionWith(ids);
    }
    //this callback will get called once the job is done by a thread that will acquire resource lock
    ModifyBatch._delete_batch[table_info.Name].Callbacks.Add(f =>
    {
        done = true;
        error = f;
    });
}

bool lockAcquired = false;
int maxWaitMs = 60000;
DeleteData _delete_data = null;

//resource lock
var _write_lock = GetTableWriteLock(typeof(T).Name);
try
{
    DateTime start = DateTime.Now;
    while (!done)
    {
        lockAcquired = Monitor.TryEnter(_write_lock, 100);
        if (lockAcquired)
        {
            if (done) //some other thread did our job
                            {
                Monitor.Exit(_write_lock);
                lockAcquired = false;
                break;
            }
            else
            {
                break;
            }
        }
        Thread.Sleep(100);
        if ((DateTime.Now - start).TotalMilliseconds > maxWaitMs)
        {
            throw new Exception("Waited too long to acquire write lock?");
        }
    }
    if (done) //some other thread did our job
    {
        if (!string.IsNullOrEmpty(error))
        {
            throw new Exception(error);
        }
        else
        {
            return;
        }
    }

    //not done, but have write lock for the table
    lock (ilock)
    {
        _delete_data = ModifyBatch._delete_batch[table_info.Name];
        var oval = new DeleteData();
        ModifyBatch._delete_batch.TryRemove(table_info.Name, out oval);
    }
    if (_delete_data.ids.Any())
    {
        //doing the work with resource 
    }
    foreach (var cb in _delete_data.Callbacks)
    {
        cb(null);
    }
}
catch (Exception ex)
{
    if (_delete_data != null)
    {
        foreach (var cb in _delete_data.Callbacks)
        {
            cb(ex.Message);
        }
    }
    throw;
}
finally
{
    if (lockAcquired)
    {
        Monitor.Exit(_write_lock);
    }
}

How to decide function/method should be part of utility package/module

Being a developer we often keep most commonly used functions/methods in common utils class/module. My question is what are the best practices should follow while writing utils classes/functions.

Does ES6 provide a way to resolve a maybe-function into its result?

I occasionally write code that looks like this:

constructor(thing) {
    this.thing = thing.constructor === Function ? thing : () => thing;
}

This lets the caller provide a value directly if they know it won't change. I'm okay with this solution, but it's too copy-and-pasty.

Does ES6 provide a more elegant way to do this? I'm imagining something analogous to Promise.resolve(maybePromise) for functions, but Function.resolve(maybeFunc) doesn't exist.

Alternatively - is there a better pattern for this? I can require that thing always be a function, but that seems cumbersome for the caller.

observer pattern for a Youtube channel using this template

I'm learning design patterns.How can I make an observer pattern for a Youtube channel using this template: (note: observer class is all set, just this classes)

Subject.java public interface Subject {

}

Channel.java

public class Channel implements Subject {

}

Follower.java

public class Follower implements Observer { }

Validation required in multiple classes implementing the same interface

I have the following interface:

public interface IFoo
{
    void DoSmth(IList<int> list, string path);
}

There are also multiple derived classes that implement this interface and its single method. All of the classes need to validate the input parameters first, and only then do the actual job. Where should be that validation performed?

One solution is to write the validation code in each derived class, which causes code duplication.

The second and a better solution is to use an abstract base class and perform all the validation there. Something like this:

public abstract class BaseFoo
{
    public void DoSmth(IList<int> list, string path)
    {
        if(list == null)
        {
            throw new ArgumentNullException(nameof(list));
        }

        if(list.Count < 3)
        {
            return;
        }

        ...
        // more validation here
        ...

        InnerDoSmth(list, path);
    }

    protected abstract void InnerDoSmth(IList<int> list, string path);
}

Are there any design patterns and best practices for this case? Or it's ok to use a base class?

So where should I place the validation code?

What is the difference between "Visitor pattern" and "Chain of responsibility pattern"?

I found many differences between many design patterns.

But, I couldn't see the difference between visitor and chain of responsibility in the stackoverflow.

What is the difference between two design patterns?

samedi 26 mai 2018

Why do we need Decorator Interface?

While going through Decorator Pattern from Wikipedia 1 and reading pattern from Head First Book . One thing that struck me and is missing from both the sources or i may have missed it.

Why exactly do we need a Decorator Interface ?

  • Is it because we need to put all the Concrete Decorators under categorical umbrella.

Suppose if we had only few ( <5) Decorators , Cant we simply sublcass them directly from Component Interface. Terms from wikipedia UML Thus Decorator will be storing the reference of Component Interface Type and it will call the behaviour directly of the Concrete Component after doing adding some more to it. This is the same thing as per the examples from the Head First Book.

Another reason that i can think of Putting a Decorator Interface is to have Runtime support for Adding those Decorators through Factory. This is the only reason that i can make of.

Asking here to wider audience, Is Decorater Interface in Decorator Design Pattern is just for providing Dynamic Support via Factory or there is more to it.

ECB pattern (Entity,Control,Boundary) implementation

I'm learning about the ECB pattern. I've understood the concept of this pattern but i'm not sure about its implementation. I'm going to write a simple example: I supposed to need a software which manages the customers of a shop. The customers are stored on a generic database. Accoding to the ECB pattern i need to have the following classes

1)Customer which represents the entity, with its attributes (name,surname,birthDate etc..)

2)CustomerWindow which represents the boundary, with some labels, textfields, buttons and a table to show customers

3)CustomerController which represents the logic with some methods (insert,delete etc...)

I should add also a CustomerDAO (implementing an interface, but my question is not about DAO) which manages the access to the database. I would like to know the way this classes interact each other. For example, supposing the insertion of a new customer, i suppose they interact like this:

1)The CustomerWindow "collects" the data written inside the textFields (name,surname ecc) and calls the method insert(String ....) of the CustomerController.

2)The CustomerController check if all data are ok (for example empty fields or format error). If they are ok, create a new Customer with that data and calls the method insert(Customer c) of the CustomerDAO.

3)The CustomerDao provide to insert the customer into the database

Obviously some of this operations could throw some exceptions but i think it's not important for this example, supposing inserted data are all valid. Is this the way the ECB pattern works? If not, how it works?

I have a last question: Some of this classes should be static or i need to declare an instance of each of them? For example i think the CustomerController and the Customer DAO can be static. The CustomeWindows calls the CustomerController.insert(...) method which eventually calls the CustomerDAO.insert(...) method (so i don't need to create a new CustomerController() or a new CustomerDAO(). Is it right?

I hope my english is pretty understandable. Please tell me if i've not been clear about something. Thank you all ;)

P.s. if you prefer i can write a code example

Which Design Pattern use

Let's say I have a class products where I have a stock and can pay in 2 ways: Paypal or cash. I can only sell 2 products cash. This might change in the future so I don't want to have to change the whole code with ifs and else so I thought of using the Strategy Pattern.

I'm just learning about design patterns. I'm most interesten in an UML design first before going to code.

So, is this a good pattern for my case? I might add more validations to the Cash class or to the Paypal class.

Java Issue in Object Constuction / Inheritance / Generics

Suppose I have a class ApiClient (auto-generated) which does not implement an Interface.

There is another class X which extends ApiClient to have some additional and overriding methods.

class X extends ApiClient{
  X (Settings s){
    super();
    this.setPropertyInheritedfromApiClient-A("food");
    this.setPropertyInheritedfromApiClient-B(thisClassMethod());
 } 

  thisClassMethod(){ return "wee" ; }      

}

There would be similar type of class X and each would derive from class identical to ApiClient but since these are aut-generated , packages will differ and values of certain fields will be different like url. To digress , each ApiClient represents a different WebService endpoint.

Although I can keep writing class similar to X for each corresponding to each ApiClient ( defined for different WebService Endpoint ) but the logic essentially remains the same.

I would want something like

class X extends T {
 X (Settings s){
        super();
        this.setPropertyInheritedfromApiClient-A("food"); // FAIL since Type of super class is not known
        this.setPropertyInheritedfromApiClient-B(thisClassMethod()); //FAIL
     } 

}

How can i approach this problem from Java Generics way or which Design Pattern to apply ?

I am not able to think of the title of the Question - Please suggest

vendredi 25 mai 2018

Changing aggregate behavior during its lifetime

Imagine that we have an Aggregate that has a life cycle, such that it can change its behavior during its lifetime. During the first part of its life, it can do some things and during the second part, it can do other things.

I´d like to hear opinions on how should we restrict what the aggregate can do on each phase. To make it a little more tangible, lets take an financial trade as an aggreagate example.

  • A trader creates a trade informing the contract, and its price.
  • A risk manager validates a trade, giving a reason for such.
  • The BackOffice can submit the trade to the ledger, providing accounting information.
  • After the trade is submitted, the accounting information can never be changed.

The trade clearly has 3 distinct phases, which I´ll call Typed, Validated and Submitted

My first thought is to pollute the aggregate with InvalidOperationExceptions, which I really don´t like:

public class Trade 
{
    private enum State { Typed, Validated, Submited }
    private State _state = State.Typed;

    public Guid Id { get; }
    public Contract Contract { get; }
    public decimal Price { get; }

    public Trade (Guid id, Contract contract, decimal price) { ... }

    private string _validationReason = null;
    private AccountingInformation _accInfo = null;

    public void Validate(string reason)  {
        if (_state != State.Typed)
            throw new InvalidOperationException (..)
        ...
        _validationReason = reason;
        _state = State.Validated;
    }

    public string GetValidationReason() {
        if (_state == State.Typed)
            throw new InvalidOperationException (..)
        return _validationReason;
    }

    public void SubmitToLedger(AccountingInformation info) {
        if ((_state != State.Validated))
            throw new InvalidOperationException (..)
        ...
    }

    public AccountingInfo GetAccountingInfo() { .. }
}

I can do something like a Maybe pattern, to avoid the exceptions on the Get... methods. But that would not work for the behavior methods (Validate, SubmitToLedger, etc)

Oddly, if I were to be working on a functional language (such as F#), I would probably create a different type for each state.

type TypedTrade = { Id : Guid;  Contract: Contract; Price : decimal }

type ValidatedTrade = {  Id : Guid;  
                        Contract: Contract; 
                        Price : decimal;
                        ValidationReason : string}

type SubmittedTrade =  {  Id : Guid;  
                        Contract: Contract; 
                        Price : decimal;
                        ValidationReason : string; 
                        AccInfo : AccountingInfo }

// TypedTrade -> string -> ValidatedTrade
let validateTrade typedTrade reason = 
    ...
    { Id = typedTrade.Id; Contract = typedTrade.Contract;
            Price = typedTrade.Price; Reason = reason }

// ValidatedTrade -> AccountingInfo -> SubmittedTrade
let submitTrade validatedTrade accInfo = 
    ...
    { Id = validatedTrade.Id; 
    Contract = validatedTrade.Contract;
    Price = validatedTrade.Price; 
    Reason = validatedTrad.Reason;
    AccInfo = accInfo }

And the problem would gracefully go away. But to do that in OO, I would have to make my aggregate immutable and maybe create some kind o hierarchy (in which I would have to hide base methods !? ouch!).

I just wanted an opinion on what you guys do on these situations, and if there is a better way.

How to refactor a return of the same value in both catch and try?

I've been noted by Sonar that this is a smelly code. How could I fix it?

invokeFieldAccessor(property.getField(), this.instance, theValue,
    new FieldAccessorHandler() {
        @Override
        public synchronized Object accessField(
                final Field field, final Object objectInstance,
                final Object value) {
            try {
                field.set(objectInstance, value);
            } catch (Exception e) {
                return null;
            }
            return null;
        }
    });

The best design pattern for algorithms with different number of input parameters

I'm trying to help my friend with his project and whilst doing that I saw that he has 2 almost similar algorithms implemented.

My first thought was to use Template pattern.

public abstract class Template {
    calculate();
    save();
}

and so on. However in second algorithm calculate() and save() need additional parameters. Code inside both methods in both algorithms is duplicating in 90%.

Lets say in first algorithm I need only longitude and in second longitude and latitude.

Thus, the only way to make it with Template pattern is to create some object with longitude and latitude and to pass it in both algorithms. However, I don't like this solution because of this second parameters that will be "null" in the first algorithm.

Maybe I don't see some better, cleaner way to resolve this problem?

jeudi 24 mai 2018

return type must be of object in designing the solution through design pattern

Please advise below I haveimplemented the starergy pattern as shown below as per the solution of the problem now my question is that apart from statergy design pattern is there any other better design pattern in which i can better express this problem in much efficient way , rite now below is the statergy pattern in which i have explained the problem

the interface

interface applyBuisnessRule<T> {
    public T execute(String jobCode) throws Exception;
}

the class

class CardvaletImpl<T> implements applyBuisnessRule<T> {
    private static final String Success = null;

    public T execute(String jobCode) throws Exception {
        T result = null;
         // put your logic and populate result here. I believe you are not going to return Success every time as it String
        return result;
    }
}

code excecution

CardvaletImpl<String> cardvaletImpl = new CardvaletImpl<>();
String result = cardvaletImpl.execute("JOBCODE");

Logic in the Composition Root

Is it considered bad practice to put business logic in the composition root? I have an application where an event occurs, either from the UI or by receiving a message on a socket from another application. This event triggers a complex set of steps that involve several other unrelated classes. For example, when the message arrives that a call has started, we might want to send a socket message to a third application, update some hardware, play a sound to the user, and update the UI. Obviously the message processing object can't know about all these other classes. The only place that does is the composition root. So the composition root subscribes to the message handler's event with a function (also in the composition root) that does the needed logic with the rest of the classes.

Public Class CompositionRoot
    'Variable declarations would go here

    Public Sub New()
        'Instantiate all the objects

        'Hook an event for what to so when a message is received
        MyMessageProcessor = New MessageProcessor
        AddHandler MyMessageProcessor.MessageReceived, AddressOf OnStartCall
    End Sub

    Private Sub OnStartCall()
        If JurisdictionChecker.CheckJurisdiction Then
            RemoteCallMonitor.SendStateMessage("Active call")

            CallTimer.StartCall()
            Speaker.PlayAlert()
            FootPedal.Enable()
            MainForm.ShowNewCall()
        Else
            ErrorReporter.ReportError("Failed jurisdiction check")
        End If
    End Sub
End Class

Is it a problem to have logic inside the composition root? I thought about making another class for the logic but then that class will have a lot of dependencies, which are pretty much unrelated so I can't just make coarser groups of operations. I would prefer to use Pure DI with no container if possible, but that's not a hard and fast rule.

What is the position of a delegate class of a UITableView in mvc?

I have a delegate class which separated from UIViewController for UITableView. And I'm wondering the class is a model, a view or a controller?

Paradigm "program to interfaces, not implementations" vs. builder pattern

I like the builder pattern (example https://stackoverflow.com/a/1953567) for various reasons, e. g. the fact that I can work with immutable objects and that I can control the object creation in the way that no invalid objects can be created.

However, I try to follow the paradigm "program to interfaces, not implementations" (example https://stackoverflow.com/a/2697810).

I figured, these two guidelines do not play well together.

If I have an interface Person and a class PersonImpl and a builder PersonImplBuilder that builds a PersonImpl. I now can assure that every instance of PersonImpl is valid and immutable. But every return value and particularly every method parameter in my API uses the interface. So I can not depend on a valid object.

Am I missing something respectively is there another way of combining these two very useful guidelines?

What design patterns or frameworks are available to build Slot Filling application

I am building a slot filling application, What design patterns or frameworks are available off the shelf to build this kind of application.

How Can I binding two commands to WPF button?

I am using WPF with MVVM pattern. I have a button and I have two commands. Furthermore I have a checkbox. And I want to bind different command to the button, depending on the checkbox ischecked or not.

For example If I click to my button It shows a message box and if I check the checkbox and I click to my button It shows a new window or something else..

I have a solution for this (I'm going to explain from high, but I think there will be exist better solution:

My ViewModel:

ICommand command1 {get; set;}
ICommand command2 {get; set;} 
ICommand commandSelector { get
{ 
  if(checkbox)
  {
     return command1;
  }else
  {
     return command2;
  }
}
private set {} }

My XAML:

<Button Label="DO" Command="{Binding commandSelector}"/>

what is the design pattern for solving this rails service

I should implement a service which is rails but without active record relations i will collect the data from 3 other services and should and should keep the controller skinny and dry also should be in model at the end let's say

Post =>>>>>

our current service

User_posts

another service which i will got the user_post ids

Comments

service which take the post_ids and response with comments data

Likes

also the same like comments but response with likes based on post id

Finally i need to send requests to these services and merge the results in the post model but with a good patten ,

Laravel: What is the best way to implement a method in a model class

I have a simple search method in my Game model and I have implemented it as below.

public static function search($season, $week)
{
     $filteredGames = Game::with('season', 'week', 'homeTeam', 'awayTeam')
        ->when($season != null, function ($q) {
            return $q->where('season_id', request('season'));
        })->when($week != null, function ($q) {
            return $q->where('week_id', request('week'));
        })
        ->paginate(15);

       return $filteredGames;
}

And using it in controller like this

$games = Game::search(request('season'), request('week'));

Looks like it works perfectly.

I want learn whether using a static method is the best way to implement such a feature in terms of design patterns and SOLID principles or not.

Any help would be appreciated.

mercredi 23 mai 2018

Design pattern to consume API that supports pagination

I want to get some results back from a REST API that supports pagination. The way the API works is you make the initial request and get back the following.

  • List of objects
  • Total Count
  • Number Remaining
  • Result Identifier

To get the remaining object I need to make another request passing in the results identifier and rinse and repeat.

What I am having trouble with is writing a method that does this "elegantly". I would like to have a single method where I pass in the initial query and it makes as many API calls as necessary to get back all objects and just adds them together as a single list which is returned from the method.

Are there any good design patterns to follow in this type of scenario? Do I need to use recursion for the method to call itself or is there a simpler approach? I see lots of posts on how to design an API to properly paginate but have not found anything that describes how to properly consume an API that supports pagination.

Builder pattern working with real data (not some hardcoded data)

I am currently learning the builder pattern. All the tutorials, everything is great, but when it comes to working with real data (not hardcoded strings inside your SetFoo(), SetBar() (in the builders)), I realized that I need to pass to the builder from inside the controllers (MVC). And then my controller happens to be the director right? PS: My construct method is gone now since the data is already set from the setters of the builder. Example: fooBuilder.setBar("real data from db"); fooBuilder.setGoo("more real data from the database");

Does this violate the principles of the builder pattern?

Style comes inline

I did'nt write inline css but my stylesheet backup coming as inline in web page automatically does anyone know the solution enter image description here

enter image description here

thanks for advance

ReactJS Component that retrieves quotes, make it SOLID

I have created the following React Component and wanted to have feedback about if its SOLID or not, and what can I do to fix it.

What the code does: 1. It renders a list of Quotes from a Sharepoint List.

My structure:

enter image description here

And my code as follows:

Solid.tsx

import * as React from 'react';
import styles from './Solid.module.scss';
import { ISolidProps } from './ISolidProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { IQuotes, IQuote } from './QuoteContracts';
import { IDataReader, DataReaderFactory } from './DataReader';
import { ISolidState } from './ISolidState';


export default class Solid extends React.Component<ISolidProps, ISolidState> {

  constructor() {
    super();
    this._dataReader = DataReaderFactory.getReader(this.context);
  }

  private _dataReader : IDataReader;

  public render(): React.ReactElement<ISolidProps> {
    return (
      <div className={ styles.solid }>
        <div className={ styles.container }>
          <div className={ styles.row }>
            <div className={ styles.column }>
              <span className={ styles.title }>Welcome to SharePoint!</span>
              <p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p>
              <p className={ styles.description }>{escape(this.props.description)}</p>
              <a href="https://aka.ms/spfx" className={ styles.button }>
                <span className={ styles.label }>Learn more</span>
              </a>
              {this.renderQuotes()}
            </div>
          </div>
        </div>
      </div>

    );
  }

  fetchData = () => {
    this._dataReader.getData().then((response) => {
      this.setState({
        quotes: response.Quotes,
      });
    });
   }

  componentDidMount() {
      this.fetchData();
  }

   renderQuotes = () => this.state.quotes.map(quote => ( 
      <div>${escape(quote.Quote)}</div>
      <div class="${styles.author}">${escape(quote.Author)}</div>  
  );

}

Datareader.ts

import {
    Version,
    Environment,
    EnvironmentType
} from '@microsoft/sp-core-library';
import { IWebPartContext } from '@microsoft/sp-webpart-base';

import { IQuotes } from './QuoteContracts';
import { SPDataReader } from './SPDataReader';
import { MockDataReader } from './MockDataReader';

export interface IDataReader {
    getData(): Promise<IQuotes>;
}

export class DataReaderFactory {
    public static getReader(context: IWebPartContext) {
        if (Environment.type === EnvironmentType.SharePoint || Environment.type === EnvironmentType.ClassicSharePoint) {
            return new SPDataReader(context, "Quotes");
        }
        else if (Environment.type === EnvironmentType.Local) {
            return new MockDataReader();
        }
    }
}

ISolidProps.ts

export interface ISolidProps {
  description: string;
}

ISolidState.ts

import { IQuote, IQuotes } from "./QuoteContracts";

export interface ISolidState {
    quotes: IQuote[];
}

Mockdata.ts

import { IQuote } from './QuoteContracts';

export default class MockData {

    private static _items: IQuote[] = [
        { Author: 'Author 1', Quote: 'Quote 1' },
        { Author: 'Author 2', Quote: 'Quote 2' },
        { Author: 'Author 3', Quote: 'Quote 3' }];

    public static get(): Promise<IQuote[]> {
        return new Promise<IQuote[]>((resolve) => {
           resolve(MockData._items);
       });
   }
}

MockDatareader.ts

import { SPDataReader } from './SPDataReader';
import { IQuotes, IQuote } from './QuoteContracts';

export class MockDataReader extends SPDataReader {
    constructor() {
        super(null, null);
    }

    getData(): Promise<IQuotes> {
        return this.get().then((data: IQuote[]) => {
            var listData: IQuotes = { Quotes: data };
            return listData;
        }) as Promise<IQuotes>;
    }

    private static _items: IQuote[] = [
        { Author: 'Author 1', Quote: 'Quote 1' },
        { Author: 'Author 2', Quote: 'Quote 2' },
        { Author: 'Author 3', Quote: 'Quote 3' }];

    private get(): Promise<IQuote[]> {
        return new Promise<IQuote[]>((resolve) => {
            resolve(MockDataReader._items);
        });
    }
}

QuoteContracts.ts

export interface IQuotes {
    Quotes: IQuote[];
}

export interface IQuote {
    Author: string;
    Quote: string;
}

Should data be fetched inside a Response Transformer?

Assuming there are two collections in a MongoDB Database: UsersCollection and BookingsCollection. A user can have multiple bookings, the BookingsCollection contains the user_id field to establish the reference.

In one of the endpoints, we need to deliver a response object that contains a list of users, each object in this list needs to contain the user's name and the number of bookings a user has:

[
    {
        "name": "Karim",
        "bookings": 8
    },
    {
        "name": "Julie",
        "bookings": 1
    },
    ...
]

The bookings field in the response is a virtual field that needs to be fetched by counting the number of rows on the BookingsCollection with a giver user_id.

We're using PHPLeague's Fractal Transformers in this project. I believe that this virtual field (bookings) should be in the $availableIncludes of the Transformer, but should this data be fetched inside the transformer? Or does the data need to be already in the object passed to the transformer?

Something like:

class UserTransformer extends TransformerAbstract
{
    protected $availableIncludes = [
        'membership',
        'last_interaction'
    ];

    public function transform(User $user)
    {
        return [
            'first_name' => $user->firstName(),
            'last_name' => $user->lastName(),
            'phone' => $user->phone(),
            'email' => $user->email(),
            'source' => $user->source()
        ];
    }

    public function includeBookings(User $user)
    {
        /** @var BookingsRepository $bookingRepository */
        $bookingRepository = app()->make(BookingsRepository::class);

        $bookingRepository->criteria->push( new IsBooked() );
        $bookingRepository->criteria->push( new UserId($user->id()));

        $bookings = $bookingRepository->count();

        return $bookings;
    }
}

But it doesn't feel right haha

My question is not exactly how to do it, but what would be the best place to fetch the data...

EDIT:

If the object passed to the transformer is supposed to have bookings already prefilled, wouldn't this add unnecessary complexity to all endpoints that might not be expecting to receive the bookings?

Cheers

mardi 22 mai 2018

What is this navigation pattern called?

Google Drive and Windows itself uses it, does it have a name?

Example

Thanks.

Events vs Observer pattern

I found some resources on this, but still can't get my head around it (also, didn't found question asking this directly).

Let's suppose: we have one object of interest and multiple objects interested in this object (its state for example). When object of interest changes in some way, others want to know about it.

First approach

It looks like classic problem that is solved by Observer Pattern. When object of interest changes it invokes methods on objects that are subscribing the event. Simple.

Second approach

Define an event in object of interest, on change, raise this event. Others will listen to this event and call their methods on it.

One obvious difference is that the object invoking method is different. But, why we should use one instead of the other approach?

I know these concepts, but I am looking for deep understanding of a problem.

Thanks for any hints!

Matching Url with fnmatch and Patterns

I want to match the Following URLS to

http://deploy.local/user/12 => fnmatch(PATTERN???, $url);
http://deploy.local/user/tree => fnmatch(PATTERN???, $url);

But

fnmatch("user/[0-9]+" , $url);

does not work with these..

Any Suggestions ?

lundi 21 mai 2018

Sample of Behavioral patterns in ejb

I want to use some behavioral patterns like command in service layer. Currently I use some ejb in service layer. Is there any sample of behavioral pattern that couple with ejb and use container-managed transactions? I'm new in Design pattern.

Building a common communication interface

I'm having trouble building an abstract interface for multiple communication types that have different settings to connect. I would like to be able to use a factory of some sort to instantiate one of the communication types (usb, serial, tcp) with their appropriate connection arguments without branching this off into a bunch of if statements everywhere to check the type and to use a single interface to control all the interaction with the specified communication type.

Some code below to help illustrate my problem:

public interface ITransport : IDisposable
{
    event EventHandler Connected;
    event EventHandler Disconnected;
    event EventHandler<byte[]> SentData;
    event EventHandler<byte[]> ReceivedData;
    event EventHandler<string> ErrorOccurred;

    event HostCertificateReceivedDelegate HostValidation;

    Task<bool> ConnectAsync(TransportConnectionArgs connectionArgs);
    Task<bool> SendAsync(byte[] buffer);

    void Disconnect();
}

public class TransportConnectionArgs
{
    public static readonly TransportConnectionArgs Empty = new TransportConnectionArgs();
    protected TransportConnectionArgs() { }
}

public class SshTransportConnectionArgs : TransportConnectionArgs
{
    public string Host { get; }
    public int Port { get; }

    public string Username { get; }
    public string Password { get; }

    public SshTransportConnectionArgs(string host, int port, string username = "root", string password = "")
    {
        Host = host;
        Port = port;
        Username = username;
        Password = password;
    }
}

public class SerialTransportConnectionArgs : TransportConnectionArgs
{
    ... does not need password but needs com port, baud, etc...
}

public class UsbTransportConnectionArgs : TransportConnectionArgs
{
    ... does not need address or port or serial connection settings
}

public sealed class SshDebugClient : ITransport
{
    public async Task<bool> ConnectAsync(SshTransportConnectionArgs connectionArgs)
    {
        ... access properties specific to a regular TCP connection
    }
}

public sealed class SerialDebugClient : ITransport
{
    public async Task<bool> ConnectAsync(SerialTransportConnectionArgs connectionArgs)
    {
        ... access properties specific to a regular serial/COM connection
    }
}

public sealed class UsbDebugClient : ITransport
{
    public async Task<bool> ConnectAsync(UsbTransportConnectionArgs connectionArgs)
    {
        ... access properties specific to a regular USB connection
    }
}

calling java classes at runtime on conditions

I am asking one design level interview problem with context to core java,I have one excel sheet contaning 3 coulumns that same I have stored in database in a table named details

Jobcode   networkId    BuisnessRule

A          11            XYZ
A          16            QWE
B          12            ERT

Now please advise from the design point of view what I have done is that uiser will have the value of jobcode so lets say the user will have the jobcode A , so he will fetch the network id with context to job code so for A there will be two network id that is 11 and 16 now upon these network ids we have two different buisness rule that is XYZ on network id 11 and QWE on networkId 16

now what i have done i have maintained an spring map so that it get intialised when my app starts as it is static data as shown below

 <map>
  <entry key="11" value="com.Mapping.XYZMappingBuisnessRule"/>
  <entry key="16" value="com.Mapping.QWEMappingBuisnessRule"/>
  </map>

now what I have been planning is that once the networkId is retrieved by the user then following classes XYZMappingBuisnessRule and QWEMappingBuisnessRule will be called and each of these classes will have exceute method to call the buisness rule and these classes will be called at runtime as soon as the network id isnidentified , please advise is it the correct design

My concern is that as the count of buisness rule increases the count of classes also increases in this design

What is the best way to implement aggregation across nodes?

I wanted to get your opinion on how best I should aggregate results across different properties.

If I have following structure of classes in my solution (simplified version):

School object has a list of students studying and books used in the school. Each student has a list of books that they are using to study. Each book has a name and cost.

E.g.

public class School
{
    public List<Student> Students { get; set; }
    public List<Book> Books { get; set; }
    public string Area {get;set;}
    public string SchoolName {get;set;}
}

public class Student
{
    public List<Book> Books { get; set; }
    public string StudentName {get;set;}
}

public class Book
{
    public double Cost { get; set; }
    public string BookName { get; set; }
}

This structure is given to us in the 3rd party library that we need to call to.

Cost of book vary for each student.

I have following School/Student/Book information available e.g.

School:

School ABC, Area London:
   **Students**:  
        StudentA
              **Books**:  
                  Book1, Cost £1.  
                  Book 2, Cost £2 
         StudentB
              **Books**:
                  Book1, Cost £1.5.  
                  Book 2, Cost £1

 School DEF, Area NewYork  
 **Students**:  
        StudentC
              **Books**:  
                  Book1, Cost £1.  
                  Book 2, Cost £2 
         StudentD
              **Books**:
                  Book1, Cost £1.5.  
                  Book 2, Cost £1

Aim

For each area, give the total of each book across all schools and students e.g.

Area: London Book1: £5 (1+1.5+1+1.5) Book2: £6 (sum of all book 2 entries).

Note

  1. We have a books property under school so I was thinking of creating new book entries under school which aggregate all books' cost under students. 2. Group by school Area and BookName and then return sum of cost for books but I am unsure if there is another suitable way to implement it?

  2. Is there a pattern that I can use to aggregate across child nodes e.g. Books within Students and move them to Students etc.?

Helper classes with only public static methods

I wish to create a helper class with public static methods only. I declare a class instead of namespace, because I will befriend this class with others so that it can operate on their private members as well.

Is this considered a bad OOP practice? Is there an established better way to achieve this goal, or a pattern-like name given to cases like this, that I can do further research on the internet?

Thanks.

How do I keep an updated list of resources over time

I am writing an application where I ask users to register their phone numbers so I can match them as 'acquaintances'. The idea being that a phone number is relatively unique and static. So my challenge is how to go about it.

For now, I decided that when they register their number, I normalise it to the international standard (+ prefix). So in the cloud I have a list of all the registered users with their phones.

When the app starts I will read all the contacts of the user and get the phone numbers. I will have some logic that also normalises them so they are in the same format as the ones on the cloud.

My solutions so far is the following: Every time the app starts, I will read the contacts and extract the normalised phone numbers. The first time I will send all of them to the cloud and compare them against the cloud numbers. The ones that are matched will be 'acquaintances' and will return their corresponding app ids. I will store those in a file of the app. Now every following time, I will read the contacts, extract the phone numbers, find the difference from the ones I saved in the file (the ones I already know they are 'acquaintances') and send the rest to the cloud in hope that some more have signed up to the app. I update the file accordingly to the response.

Can I have some comments/thoughts/ideas on it? Am I missing something? Is there an easier way? A different approach?

NOTE: Let's forget about GDPR and security, I will be hashing them and some other stuff and using the hashs instead of the actual phone numbers, but I want to focus on the matching part.

Proxy design pattern (protection proxy)

I just studied about proxy pattern and I thought I could use it for keeping my controller actions save (checking if the current user is authenticated or has the rights to visit this page) in a ASP.NET MVC 5 application. Any ideas how to implement it? Redirecting him with a proxy class to an other controller maybe?

How can I extend classes in Factory Method pattern in Java

I'm new in design patterns and now I am learning about Factory Method pattern. I try to make an example using animals.

I have an Animal interface with two methods, breathe and walk. Implementing this interface I have two classes, Giraffe and Flamingo.

Following the pattern I have two factories, one for Giraffes and one for Flamingos and a main class like this:

if (color.equals("yellow")) {
  factory = new GiraffeFactory();
} else {
  factory = new FlamingoFactory();
}

Animal animal = factory.createAnimal();
animal.breathe();
animal.walk();

This works perfectly but now I realise that Flamingos can fly. I don't want to include this method in Animal interface because Giraffes can't.

How can I call this new method only in Flamingo Animal instances? Is cast the only solution? Or is this pattern only for objects that has the same methods from their interface?

((Flamingo) animal).fly();

Thank you so much.

best architecture to couple restful api with its web app

i working on application that working in two platform web app and mobile app

that i have stuked ..what is the best architecture to build this web app an the mobile api which i have two ways: first: making two function in each controller one for the view of the web and another for the mobile services

second: make one function for both but if there are any change of one them .. i had to rebuild them as first

thanks in advance...

dimanche 20 mai 2018

Python Loop Understanding

Im self learning Python , and i've been stuck on this loop problem for a while. I wrote a script to extract Data every hour about stock prices. But for each hour of data I have manually created new variables to hold my new data.

  • Is there a loop that will do this for me without having to create a new line of variables for each run?
  • and can that loop create a text file that has a differing name? ( ex: Txtfile1.txt , Txtfile2.txt)

code ex attached below

Thanks

 R = requests.get("https://api.website.com/v1/....)
 data = R.json()

for x in data:
       ticker = x['symbol']
       cost = x['price_usd']

print (ticker + "\t:" + cost)
with open('Marketcap.txt', 'w') as outfile:
    json.dump(data, outfile, indent=2)

time.sleep(3600)


R2 = requests.get("https://api.website.com/v1/....)
data2 = R2.json()

for y in data2:

        ticker2 = y['symbol']
        cost2 = y['price_usd']

print(ticker2  +":\t" cost2)

with open('Marketcap2.txt', 'w') as outfile2:
    json.dump(data2, outfile2, indent=2)

time.sleep(3600)

Strategy Pattern Java

I have a question regarding strategy pattern in java. In the first diagram we can see definition of the Strategy pattern. Context is composed of a Strategy interface, The context could be anything that would require changing behaviors - a class that provides sorting functionality perhaps.

The Strategy is simply implemented as an interface, so that we can swap ConcreteStrategys in and out without effecting our Context.

Normal strategy pattern Strategy pattern

Now lets look at the second diagram, . Suppose we use Strategy pattern. Classes ConcreteStrategyA and ConcreteStrategyB need to call the client to perform the algorithm they implement.

Any reason why you would need the interface Client Interface?

Android: MVP how does the model communicate back with the presenter?

My question is: When I'm doing some business in the model, How can send data back to the presenter depending on a callback method such as onSuccess?

I'm simply try to implement a Facebook login while using the MVP design pattern. First I was confused as how to register the callback manager outside of the view as I need the context. I decided to inject the context in the model, which is not a good practice as I under stood, the model should not have any android components.

factory method broken into modules

I have been looking at the simple factory example,

from __future__ import generators
import random

class Shape(object):
    # Create based on class name:
    def factory(type):
        #return eval(type + "()")
        if type == "Circle": return Circle()
        if type == "Square": return Square()
        assert 0, "Bad shape creation: " + type
    factory = staticmethod(factory)

class Circle(Shape):
    def draw(self): print("Circle.draw")
    def erase(self): print("Circle.erase")

class Square(Shape):
    def draw(self): print("Square.draw")
    def erase(self): print("Square.erase")

# Generate shape name strings:
def shapeNameGen(n):
    types = Shape.__subclasses__()
    for i in range(n):
        yield random.choice(types).__name__

shapes = \
  [ Shape.factory(i) for i in shapeNameGen(7)]

for shape in shapes:
    shape.draw()
    shape.erase()

And have tried to break it into separate files.

main.py

from __future__ import generators
import random

from factory.shapes.circle import Circle
from factory.shapes.sqaure import Square


class Shape(object):
    # Create based on class name:
    def factory(type):
        #return eval(type + "()")
        if type == "Circle": return Circle()
        if type == "Square": return Square()
        assert 0, "Bad shape creation: " + type
    factory = staticmethod(factory)


# Generate shape name strings:
def shapeNameGen(n):
    types = Shape.__subclasses__()
    for i in range(n):
        yield random.choice(types).__name__

shapes = \
  [ Shape.factory(i) for i in shapeNameGen(7)]

for shape in shapes:
    shape.draw()
    shape.erase()

circle.py

from __future__ import generators
import random

from factory.main import Shape

class Circle(Shape):
    def draw(self): print("Circle.draw")
    def erase(self): print("Circle.erase")

square.py

from __future__ import generators
import random

from factory.main import Shape

class Square(Shape):
    def draw(self): print("Square.draw")
    def erase(self): print("Square.erase")

and when running it I get ImportError: cannot import name 'Circle'

So although the example works when all the classes are in same module, it seem to have issues when imported them from separated modules. Any ideas?

What are the patterns used to enforce business layer calls in n-layer architecture?

I'm using the n-layer architecture like below:

  • Presentation layer;
  • Application layer;
  • Business layer;
  • Data layer;

And I want to make sure my co-workers won't be able to make calls to the Data layer directly (in some cases). There is a very important business rule in the Business layer that MUST be called every time before trying to persist the entity to the database.

Here is some code demonstrating the problem:

class Program
{
    static void Main(string[] args)
    {
        //enforce business rules here (business layer usage)...
    }
}

class BusinessLayer
{
    public void ApplyBusinessRules()
    {
        //important business validation goes here...
    }
}

class DataLayer
{
    public void SaveModel()
    {
        //data acess layer goes here...
    }
}

What are the design patterns used to achieve this behavior? I've tried to set the SaveModel() method to private but people (including myself) will simply turn the method to public thinking it was some kind of typo.

I was thinking of something like this:

interface IBusinessLayerPolicy
{
    bool CheckIfModelCanBeSaved(Model model);
}

class DataLayer
{
    private IBusinessLayerPolicy _businessPolicy;

    public void SaveModel(Model model)
    {
        if(_businessPolicy.CheckIfModelCanBeSaved(model))
        {
            //save the model to database;
        }
    }
}

If that is a good approach, which class should implement IBusinessLayerPolicy interface? If not, what are the design patterns used in this case?

How to list a number of objects by pattern in a brief way?

I'm looking for a way to abbreviate listing objects with similar name patterns. Consider this example.

vfoo <- "x"
v.1 <- v.2 <- v.n <- "foo"

Where n is the number of the last object.

> list(v.1, v.2, v.n)
[[1]]
[1] "foo"

[[2]]
[1] "foo"

[[3]]
[1] "foo"

The following only lists me the names of objects with specific pattern:

> list(ls(pattern="v."))
[[1]]
[1] "v.1" "v.2" "v.n"

Using this code I get the result I want:

> do.call("list", mget(grep("v.", names(.GlobalEnv), value=TRUE)))
$v.n
[1] "foo"

$v.1
[1] "foo"

$v.2
[1] "foo"

I benefit from this only when the number of objects to be listed exceeds a certain amount, though.

Might there be a brief solution like e.g. list(v.1 %to% v.n) (pseudo code) I do not know yet?

Three different design patterns

I have to make a project that includes three different design patterns. One structural, one creational and one behavioral. But I don't have any ideas at the moment. Can you think of any?

Design pattern a user data used globally in the whole application

I am working on an iOS project which the app needs to get user data from server. Once the user data is loaded It is used globally in the whole application, I mean many controllers use the user data. I do not know what the best design pattern for user data is.

I did some research but people say that should not use global state.

Could you please suggest to me how to design it properly? Thank you

samedi 19 mai 2018

C++ preventing user from creating object instances

I have to create simple singleton object factory for some types of objects. The problem is that I can't find smart way to prevent user from creating object instances by constructors. I know that I can move constructors to private/protected section but how will the factory create new objects now when constructors are private/protected? Making factory a friend of every class isn't really smart as I need to predeclare factory in every header and write aditional "friend Factory;" in every class. How to do this correct?

Should my application implement a back button?

My application has a defined flow, starting on 1 fragment and always moving to a 2nd, 3rd, 4th, 5th, and final 6th fragment. Due to the nature of the flow, it is common to move back through fragments too.

I don't implement a back button within the app because I remember reading design theory from Google which recommended to never implement a back button because Android devices implement their own back buttons.

I'm still in development and I've tested the app with users, and I've received feedback that I should implement a back button.

My first thought is to reject the feedback because of the theoretical principle I referred to above, but I can't remember enough detail about the principle to be able to find it again, so I wonder whether my memory is inaccurate.

Is this principle correct? Is it against Google design principles to implement a back button?

Add an extra toplevel to entire website, and start with a clean version of the application

The problem:

We have a web application (in Symfony 2.8) with +- 125 tables filled with data. Now our client asks to add an extra top-level named "Division". And when they create a new Division, they get a blanc copy of the application to start working in. So almost like a new clean sheet.

The users stay the same, some will get access to 1 Division, some to both, but more Divisions will come in the future by just pressing "new division".

We are now going through the whole application:

  • The top-level entities get an extra property Division (via a DivisionTrait) added to them...

  • changing every single query by adding something like " AND division.id = $session->get('current_division') " in all controllers.

  • Injecting this division id in all form types and also extend every query.

  • And offcourse a lot of testing and debugging

But this is a lot of work.

The question:

What are the options or design patterns so we can achieve this in an easier way? I'm sure we are not the first ones with this problem. ;)

gofstat error in R for comparison of four distribution

I want to run a gof test for four distributions using following code;

f1 <- log(c(1.000311, 1.000375, 1.000300, 1.000418, 1.000324, 1.000428))

fit.weibull <- fitdist(log(f1), "weibull", lower = c(0, 0))
fit.lnorm <- fitdist(log(f1), "lnorm")
fit.gamma <- fitdist(log(f1), "gamma", lower = c(0, 0))
fit.exp <- fitdist(log(f1), "exp")

gofstat(list(fit.lnorm, fit.weibull, fit.gamma, fit.exp))

Error pops up when I run the code;

Error in ans[!test & ok] <- rep(no, length.out = length(ans))[!test &  : 
replacement has length zero

Dont really understand why, the error isnt really intuitive to try and fix for, but the code works for other data, so i assume it is an error with the data used ?

vendredi 18 mai 2018

Design pattern to evaluate different type set of rules

I have set of different type of rules to be evaluated. each rule has different statistics,

  • each rule is in different database tables.
  • evaluating logic is different for each rule type
  • different messages have to be generated based on the evaluation.
  • status of evaluation should be saved to each rule's database table.

I'm planning to implement it base on Builder pattern, Like,

foreach(Rule rule in Rules){
  var result = rule.evaluate();
  var message = rule.getMessage(result);
  rule.saveMassage(message);
  rule.updateDB(result);
}

Is my approach OK? or a better way of doing it?

When should I use Singleton pattern?

As far as I know the singleton design pattern should be used when a class must have at most one instance. In my project, which is an e-shop, I use entities like 'User', 'Order', 'Cart' and I think that the singleton pattern is the case for each one of my previous entities. For example, the following scenario is very common for an e-shop.

One User has one Cart and makes an Order.

Have I misinterpret the Singleton pattern?

CQS pattern vs output variable

The Command Query Separation pattern states that it should be obvious whether a method is a command or a query (I have the simple principle in mind, not the CQRS with Event Sourcing etc.)

A command therefore has to be void, whereas a query has to return a value.

public interface IRepository<T>
{
    void Create(Guid id, T item);
    int GetHumanReadableId(Guid id);
    // other members
}

This is discussed for example in this Mark Seemann's post: http://blog.ploeh.dk/2014/08/11/cqs-versus-server-generated-ids/

I am wondering where does an output variable approach land? Does it violate the CQS?

What I have in mind is:

public interface IRepository<T>
{
    void Create(T item, out int humanReadableId);    
    // other members
}

This seems to keep the method void, thus indicating a command, while still allowing 'getting' some output from it without separate explicit query - after all, additional explicit query like int GetHumanReadableId(Guid id); means 1) more code to write and maintain, 2) additional database call.

MVVM design pattern practical observations in android

I am trying to understand MVVM design pattern practically in Android and went through this link and few other links and made some observation.I want to know that are all below observations are correct for implementing MVVM design pattern practically?

1.MVVM can be implemented either by using Data Binding Library or using RxJava.

2.We will create a View Model class which contains methods for various actions we need to perform when user interact with view.It will also interact with Model and saves required data in ObservableField and ObservableArray which needs to be displayed in View .

3.View consist of Actvity/fragments.View will bind UI components in layouts to ViewModel using Data Binding Library.

4.Whenever data changes in in ObservableField and ObservableArray , our View will automatically updated through data binding.

5.We will create an object of ViewModel inside Activity and whenever user interact with view we will call appropriate method of ViewModel to perform action.

javascript design patterns Revealing Module Pattern how does that work?

I'm currently learning javascript and design pattern and i read this piece of code that i don't understand. Why, and how, can we access the return object?? I understand that's an invoked function in a function; i understand scope (i think i understand scope, but apparently not).. And here i'm very confuse about why we can acces what's inside the return object and not the rest..

Can you explain that for me please, or give me a link??

(english is not my first language and it's my first question here, so a apologize if i have broke rules)

the code :

// we write the entire object logic as private members and
// expose an anonymous object which maps members we wish to reveal
// to their corresponding public members

var namesCollection = (function() {



 // private members
    var objects = [];

    function addObject(object) {
        objects.push(object);
    }

    function removeObject(object) {
        var index = objects.indexOf(object);
        if (index >= 0) {
            objects.splice(index, 1);
        }
    }

    function getObjects() {
        return JSON.parse(JSON.stringify(objects));
    }

    // public members
    return {
        addName: addObject,
        removeName: removeObject,
        getNames: getObjects
    };
})();

namesCollection.addName("Bob");
namesCollection.addName("Alice");
namesCollection.addName("Franck");
// prints ["Bob", "Alice", "Franck"]
console.log(namesCollection.getNames());
namesCollection.removeName("Alice");
// prints ["Bob", "Franck"]
console.log(namesCollection.getNames());

The source : https://www.toptal.com/javascript/comprehensive-guide-javascript-design-patterns

jeudi 17 mai 2018

Pattern or Format Match in XQuery MarkLogic

I am looking for given string, it has to be in () format, * should not have space, no two words before '('.

I am searching Mark Logic DB to see if given column value is in [^\s]+\((?!\s)[^()]+(?<!\s)\) format, if not replace it with this format.

I am still stuck at fetching data, could not write query to update

I am searching DB as

    let $query-opts := cts:search(doc(),
      cts:and-query((
        cts:directory-query(("/captis/documentData/"),"1"),  
            cts:element-query( 
                xs:QName("cd:clause"),  (: <clause> element inside extended for checking query id :)
                cts:and-query((
                    cts:element-attribute-value-query( xs:QName("cd:clause"), xs:QName("tag"), "Title" ),  (: only if the <clause> is of type "Title" :)
                    cts:element-attribute-value-query( xs:QName("cd:xmetadata"), xs:QName("tag"), "Author")

                ))
             )
        ))
for $d in $query-opts
return (
     for $x in $d//cd:document/cd:clause/cd:xmetadata[fn:matches(@tag,"Author")]/cd:metadata_string
     where fn:matches($x/string(), "[^\s]+\((?!\s)[^()]+(?<!\s)\)")
       return 
       (   <documents> {
      <documentId> {$d//cd:dms/cd:documentId/string()}</documentId>
     }</documents>
       )
     )

It's throwing up error invalid pattern

Fill map in Command pattern

#include <map>

class ICommand
{
public:
    virtual double execute(double, double);
    ~ICommand();
};
class Add: public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a + b;
    }
    double operator()(double a, double b){
        return a + b;
    }

};
class Sub : public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a - b;
    }
    double operator()(double a, double b) {
        return a - b;
    }
};
class Mul : public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a * b;
    }
    double operator()(double a, double b) {
        return a * b;
    }
};
class Div : public ICommand
{
public:
    double execute(double a, double b) override
    {
        return a / b;
    }
    double operator()(double a, double b) {
        return a / b;
    }
};

class RequestHundler
{
    std::map<int, ICommand*> commands;
    Add* add;
    Sub* sub;
    Mul* mul;
    Div* div;
public:
    RequestHundler()
    {
        commands[1] = add;
        commands[2] = sub;
        commands[3] = mul;
        commands[4] = div;
    }
    double HandleRequest(int action, double a, double b)
    {
        ICommand* command = commands[action];
        return  command->execute(a, b);
    }
};


int main(double argc, char* argv[])
{
    RequestHundler* handler = new RequestHundler();
    double result = handler->HandleRequest(2, 4, 6);
    return 0;
}

I have access violation in command->execute(a, b); , because map contains only null pointer, after filling. What is right way to store and filling map? I think I should use factory for creating classes, but even in this case I must to fill map, and I not very want to use global variable for saving map. Maybe any good idea about this code?

Design pattern for calculating dynamic data

I am writing a project that calculates a variety of stock price indicators, such as Simple/Exponential Moving Averages etc. The data I am working with is real-time, and most of these indicators are iterative and use previous values to determine the current value.

Take the Exponential Moving Average, for instance. If I were to calculate an EMA based on 10 periods (EMA(10)):

Initial: SMA(10) = [Sum of previous 10 periods]/10
Multiplier: ( 2 / ( # Periods + 1 ) = ( 2 / 11 ) = 0.1818
EMA: ( Current Value - EMA(Previous) ) * Multiplier + EMA(Previous)

When the value for the current time period changes, the EMA must be recalculated with the new value. If the entire span of values is recalculated every single time, there will be a noticeable performance hit, so caching the past values and only recalculating the current value is important.

I am wondering if there is a certain design pattern that allows for this type of functionality. Ideally, I would like to have each indicator inherit from a base pattern class to keep everything uniform.

Storing a JSON of class with a reference to an object of the same class

I have something similar to this:

public class Person {
    public String name;
    public List<Person> family;
}
List<Person> people;

And I want to store people as a JSON string on disk. And I want to follow a good design pattern. Like doing it the right way.

I don't want to end up with

[{"name":"John Doe", "family": [{"name": "Mary", "family": [{"name": "Mary's mother", "family": [{.........

Also one could end up with Mary having John Doe as family too, making a endless recursion.

What I would like to end up is with something like this:

[{"name":"John Doe", "family": [(reference to Mary)]}, {"name": "Mary", "family": [(reference to Mary's Mother), (reference to John Doe)]}, ...]

I don't want to assume the name is unique.

Is adding an "ID" to Person a good implementation/pattern? Because in my class a Person with an ID doesn't make sense (they don't have/need one)

The idea I have in mind (which I think would be a good design pattern) is to have another "private" class

private class PersonWithId extends Person {
    private int id;
}

and store that PersonWithId in the JSON so when storing the family List, i can store the ID as the reference so there is no recursion.

What options do I have?

Thanks.

MVVM - WPF How do i bind my View to my Viewmodel?

I have my View called "FahrgemeinschaftenView.xaml" & my ViewModel "Fahrgemeinschaften.cs." So by default the View is bound to its own cs, which in this case would be "FahrgemeinschaftenView.xaml.cs". Im very new to MVVM, but it says the ModelViewlayer should contain all the logic. So i try to connect "FahrgemeinschaftenView.xaml" with "FahrgemeinschaftenViewModel.cs", but wasn`t able to figure out how do to that (Passing Data).

MVVM View to ViewModel Problem