mardi 31 janvier 2017

Is there a way to implement a wildcard method with the function "find"?

I'm very new to Python. I understand that the find function takes a string p and a substring s and returns the index at which s shows up in p. But if I had something like

p = 'abc'
text = 'aaaabbaac'
text.find(p)

Would it be possible to write a method that allows me to set the wildcard to b and still return the index at which a and c match, instead of returning -1?

I'm using this in a class that has two methods, the find method and a "setwildcard" method which takes a character and does what I described above.

Database Replication Pattern at Application level

I would like to get some views on a resilience pattern we are building.

we are building Spring Data containerised applications, with Docker on Mesosphere, and we are planning to build a library which would replace the need for Oracle Golden Gate (due to the cost).

The role of that Library, would be to replicate data across all the Oracle DB nodes (so it has to be node aware...not sure how yet), and it would do so according to a predefined node order. Which means always write to Node 1 and then to Node 2.

If a node fails, then a Circuit Breaker (also part of that Library) would

  1. Create a temporary commit log for the failed node
  2. Notify all other containers of the failure
  3. Write to the commit log for this node

A Reconciliation Container would, in the background, do the following

  1. regularly poll for the database to check if it is up
  2. Notify application containers when the node is back up
  3. apply inserts from the commit log to the recovered node

This pattern should also be configurable, such that if we move to the cloud and decide to use Cassandra, then we would rely in Cassandra's replication mechanism.

I was thinking of looking at the Spring Data code and make the changes there.

Is there somebody out there who has attempted something like this?

Any advice you could provide.

Cheers Kris

Protocol extension and generics in Swift 3. Is this even possible?

I'm reading Head First Design Patterns and I'm trying to replicate the Design Patterns in a Swift Playground. I'm trying to get the Observer pattern working as per the book. My current source is as follows:

protocol Subject {
    func register(observer: Observer)
    func remove(observer: Observer)
    func notifyObservers()
}

protocol Observer {
    func update(temperature: Double, humidity: Double, pressure: Double)
}

protocol DisplayElement {
    func display()
}

class WeatherData: Subject {

    var observers: [Observer]

    var temperature: Double!
    var humidity: Double!
    var pressure: Double!

    init() {
        observers = []
    }

    func register(observer: Observer) {
        observers.append(observer)
    }

    func remove(observer: Observer) {

    }

    func notifyObservers() {
        for obs: Observer in observers {
            obs.update(temperature: temperature, humidity: humidity, pressure: pressure)
        }
    }
}

What I need to do is to implement the removeObserver method. The snippet that I need to implement is something as:

func remove(observer: Observer) {
    let obs: Observer = observers.index(where: { (aObserver) -> Bool in
        return aObserver == observer
    })
}

However this is not allowing me to continue because of a compilation error:

Cannot convert value of type '(OptionalNilComparisonType) -> Bool' to expected argument type '() -> Bool'

Is it even possible to achieve this and what am I doing wrong?

Pattern match a variable using LUA

Evening all,

I'm looking for a way to pattern match a line of text in LUA and detect if the USERNAME variable is the same result or different

The text line is this:

Unathorised Change Profile Entries: (Audit trail entry) USERNAME - USERNAME

Any advice would be greatly appreciated.

Is a singleton with an Update method really a singleton

I normally work in c#, but I'm working in a vb.net net application currently. So feel free to respond with vb.Net or c#...

Essentially I have a singleton that does all of the heavy lifting of getting global settings which are stored in the database; but there is an interface (dialog form) that allows those settings to change.

So what I did was create a singleton which on the first instantiation (only) runs the public update method. If, however, a user opens the settings dialog, the singleton is instantiated and the update command is invoked separately just in case the user made changes to the settings in the settings dialog... its the only place where I run the Update method outside of the initial instantiation of the singleton object. Conceivably another errant developer could irresponsibly run the Update method over and over again, but it would not harm anything except slow down the application--and this is the main reason I wanted to use a singleton, because there are cases where with calls to the settings is made hundreds if not thousands of times in loops; which would really slow down the application, and also the settings are being called from many random locations depending on what the user does... why don't I use a simple DTO, well, that's described below.

The other crazy thing about this application is that multiple "environments" can be running in the same thread, each with completely different settings (long story). The way the prior developers handled this was by making a call to update a settings DTO every time there was a possible switch or change in the settings or "environment", or upon starting up the application. On a search there are around 40 locations... seems nuts to me. This is on top of the hundreds of calls were the DTO is accessed. I want this singleton to do the heavy lifting and verify which environment the app is in and retrieve the settings only once from the database--except on that one occasion with the settings dialog I mentioned above, where the Update method is invoked.

End result, one nutty singleton... Below is a simplified version of the code. Basically, I'm asking whether is this a reasonable pattern, or is there a better one for this? Thanks for the feedback.

   Public Class MySingleton

        Private Shared _Instance As MySingleton = Nothing

        Private _ExampleSetting As String

        Private _CurrentDatabase as DBDatabase

        Public Shared ReadOnly Property GetInstance() As MySingleton
            Get
                If _Instance Is Nothing Then
                      _Instance = New MySingleton()
                ElseIf _CurrentDatabase <> GetCurrentDataBase() Then 
                      _Instance = New MySingleton()
                End If

                Return _Instance
            End Get
        End Property

        Public ReadOnly Property ExampleSetting As String
            Get
                Return _ExampleSetting
            End Get
        End Property


        Private Sub New()

            Update()

        End Sub


        Public Sub Update()

            _CurrentDatabase  = GetCurrentDataBase()

            _ExampleSetting = _CurrentDatabase.GetSetting("exampleSetting")

        End Sub

    End Class

What design pattern should I use for writing a CacheManager?

I can only think about singleton pattern for this task.

But, Everyone seems to have negative opinions about Singleton Pattern.

If not singleton then what design pattern should I use for a CacheManager?

I am using Java + Spring though I don't want the CacheManager to be spring dependent.

Any pointers?

How to pass values from database to UI without using domain specific objects

recently I watched some of Robert C. Martins lectures, and in one he mentions that NO domain specific objects should be passed to UI, and that UI shouldnt have knowledge about domain specific objects and business logic. My question is how to pass all the data one domain object should have in its fields without passing domain object to UI? Should I use collecions or arrays or something else?

Thanks

Is having an ActiveResource model which is persisted on a local db a good practice?

Hello I have been using Rails for quite some time and am looking for a good design pattern for structuring my code.

How I am want to do it:

I have a resource which resides on an API and I need to persist it locally because of dependencies on the API from my models (business logic).

I was thinking of creating an ActiveResource model and having a "manager" type architecture which would persist my objects and create a different object model for interacting with those internal objects (cached resource objects essentially).

The API service has web hooks to notify me of any changes to the objects which I can then handle and update locally.

The way I am currently doing it

The way I have architected it is kind of the way I have been doing it and not sure if it is a poor design:

Currently I have a mongoid persisted object which has after_create and after_save hooks to make the api calls and create persist the object.

I currently prevent the object from being persisted if an invalid response is returned from the API. This way I avoid getting into an invalid state between the API and the local persisted object.

I am curious to hear opinions of what people have done, and what they think of this approach.

C++ Design Pattern Strategy - Save/Load

[1/2] Context

I'm using the Strategy Design Pattern to perform Save/Load within an application I've been coding since a couple of months...

Finally I come up with

  • a Model (sub-classed by Array and Graph among others)
  • two abstract I/O classes ModelReader and ModelWriter which are strategies that can be used to perform load/save.

Subsequently, I create several concrete strategies and thus were born ArrayXmlWriter and GraphXmlWriter which are dedicated to saving array and graph data to XML files. Now let's see the code snippets below and then I'll ask my questions.

// somewhere in ArrayXmlWriter

for(ArrayItem *item : array->items()) {
    // first write ModelItem attributes to a stream

    stream.writeAttribute("value",      item->value());
    stream.writeAttribute("brushColor", QVariant(item->brushColor()).toString());
    stream.writeAttribute("fontFamily", item->fontFamily());
    ...

    // then write ModelShapedItem attributes to a stream

    stream.writeAttribute("kind",    QVariant(item->shapeKind()).toString());
    stream.writeAttribute("rounded", QVariant(item->isRounded()).toString());
    ...

    // ArrayItem has no specific attributes
}

Indeed ArrayItem inherits from ModelShapedItem which inherits from ModelItem: ModelItem <-- ModelShapedItem <-- ArrayItem.

Now let's see the second snippet:

// somewhere in GraphXmlWriter

for(GraphVertex *vertex: graph->vertices()) {
    // first write ModelItem attributes to a stream

    same code as above

    // then write ModelShapedItem attributes to a stream

    same code as above

    // ModelNode has no specific attributes

    // then write GraphVertex attributes to a stream

    write successors to the stream
}

Here is the hierarchy involving the GraphVertex class: ModelItem <-- ModelShapedItem <-- ModelNode <-- GraphVertex.

Now here are my questions:

[2/2] Questions

Is there a way to avoid duplicating code (as shown above)? Indeed one way to achieve that will be to add a virtual function (taking the stream as parameter) to the ModelItem class. We could then override that function in sub-classes. That means if a GraphJsonWriter were to be created one day, the ModelItem class and its involved sub-classes would also be edited (since another virtual function should be added).

Now let's imagine the classes shown above but the concrete strategies are part of some library I'm dynamically linking to: that means I have no access to their code. How could one avoid code duplication without using dynamic_cast?

I'm not sure if I'm posting on the right forum. If I'm not, feel free to advise me by telling me which forum suits the most. I actually want to know if there is a way to achieve what I want to do.

Thanks and sorry if my english is not that good.

Should the concrete builders in the Builder Pattern expose the same methods?

I'm trying to implement the builder pattern but I encountered an issue. Here is the Class Diagram. Class Diagram

Let me briefly explain the context: I've this Assembler, which is the Director, who knows the structure of a circuit that needs to be done. The circuit can be composed of amplifiers, ports and filters. In order to create the whole structure, it's needed to create different instances of each component. The director exposes the method getCircuit() in which there are the necessary steps to create the structure.

If I'm not mistaken, I should pass to the builder the reference of the concrete builder that he needs. However, in all the examples I saw so far, there were no cases where the concrete builder is changed inside the method getCircuit() (usually called construct() ).

Finally, here is my question: Is it appropriate to make the director expose a method like setBuilder(...) which will be used by getCircuit() when it is necessary to change the concrete builder? Or is there a better approach?

Here is how I wrote the class Assembler. The implementation of getCircuit() is only an example of how I'd use setBuilder() that is changing the concrete builder.

public class Assembler {
    private Manufacturer portBuilder;
    private Manufacturer amplifierBuilder;
    private Manufacturer filterBuilder;
    private Manufacturer actualBuilder;

    public Assembler(Manufacturer port, Manufacturer filter, Manufacturer amplifier) {
        this.portBuilder=port;
        this.amplifierBuilder=amplifier;
        this.filterBuilder=filter;
    }

    public void setBuilder(Manufacturer manufacturer){
        actualManufacturer = manufacturer;
    }

    public Manufacturer getCircuit(){
        circuit = actualManufacturer.buildProduct();
        actualManufacturer = setBuilder(amplifierBuilder);
        setRelation(circuit, actualManufacturer.buildProduct() );
        return circuit;
    }

}

Is the revealing module pattern the most accurate technqiue of implementing object oriented features in javascript?

Unable to completely decipher scope and other factors, I would like to know how to structure my javascript code in the best possible (object oriented) way and also if the revealing prototype pattern is the most correct choice. Please mention if other patterns fit the bill.

lundi 30 janvier 2017

trying to make sense of abstract factory pattern in Python

I found this example of abstract factory pattern in Python. I'm trying to make sense of why there needs to be a DogFactory, wouldn't it be lesser code just call the Dog class, can someone explain as to how this pattern will be useful in a real world application

class Dog:

    def speak(self):
        return "Woof!"

    def __str__(self):
        return "Dog"


class DogFactory:

    def get_pet(self):
        return Dog()

    def get_food(self):
        return "Dog Food!"


class PetStore:

    def __init__(self, pet_factory=None):

        self._pet_factory = pet_factory


    def show_pet(self):

        pet = self._pet_factory.get_pet()
        pet_food = self._pet_factory.get_food()

        print("Our pet is '{}'!".format(pet))
        print("Our pet says hello by '{}'".format(pet.speak()))
        print("Its food is '{}'!".format(pet_food))

factory = DogFactory()

shop = PetStore(factory)

shop.show_pet()

How to properly pass data in Object Observer Pattern?

I'm working on refactoring my functional game into classical structure. I know JavaScript doesn't have explicit classes, I'm using the inverse prototype structure to create classes (typical in JS these days). I'm also using Require as the means for modularity. My game is built on the Famous JavaScript engine (v0.6 before they abandoned development) which uses the Object Observer pattern.

My main problem is that I can't conceptualize how to properly pass data between my different classes and their update functions.

Here is an example - Inside a class I've called Game which is my game view, I create my character object, a Node in the FamousEngine Scene. I attach to it a visual element DOMElement and I give it all my desired properties. I then create a new object, my custom component that will be the Observer. This component has 3 functions, onMount, onReceive, onUpdate. onMount handles the logic of attaching this component to a Node. onReceive handles the logic of receiving an event emitted by FamousEngine. onUpdate handles the logic of what should happen once the Engine has queued up and is ready to execute this component's update.

Code -

var boxNode = this.UI.gameUI.addChild();
boxNode.ratio = 0.8;
boxNode.setSizeMode('absolute', 'absolute').setAbsoluteSize(80 * boxNode.ratio, 120 * boxNode.ratio).setAlign(0.5, 0.5).setPosition(-36 * boxNode.ratio, -60 * boxNode.ratio, 10000).setOrigin(0.5, 0.5);
boxNode.size = { w: 80, h: 120 };
boxNode.DOMElement = new DOMElement(boxNode);
boxNode.DOMElement.setProperty('background-image', 'url(./images/astro_loop.png)').setProperty('background-size', '800% 300%').setProperty('z-index', '1000');

var boxNodeComponentID = boxNode.addComponent({
  id: null,
  node: null,
  onMount: function onMount(node) {
    this.id = node.addComponent(this);
    this.node = node;
  },
  onReceive: function onReceive(event, payload) {
    if (event == 'resetAstro') game.boxNode.setAlign(0.5, 0.7).setPosition(-20, -20, 1000);
  },
  onUpdate: function onUpdate(time) {
    if (this.game.started == true && game.boxSet != true) {
      boxNode.setAlign(0, 0);
      boxNode.box.setPosition(gameSize[0] / 2, gameSize[1] / 2, 0);
      game.boxSet = true;
    }
    var boxPosition = boxNode.box.getPosition();
    boxNode.setPosition(boxPosition.x - 10, boxPosition.y - 20, 10000);
    boxNode.requestUpdate(this.id);
  }
});
boxNode.requestUpdate(boxNodeComponentID);

Now my problem is that I can't seem to figure out how to properly reference anything inside my onUpdate. this.game.started throws a reference error because this references the current component. The way I'm working with with this currently is actually that this component references the node it's attached to this.node which references the FamousEngine in its whole under the private member _updater. So what I've done is attached my character to it's class Game and attached Game to FamousEngine. I get these long ugly references calls inside my onUpdate methods in order to change anything - this.node._updater.Game.BoxNode. this.node._updater

How can I pass my character object, and hopefully many others, properly to these update functions? I feel like these kind of references to private members are not good or proper. It gets more complicated than above when I try to reference an update from a different class. Basically in my example I can reference boxNode since it is declared above the component creation function, but if I pull in a class via require, I no longer have that reference.

I'm sorry if my issue is not clear, I will do what I can to clean up the question.

Javascript thundering herd loading external library from CDN

The first time pica() is used, it will load the external library. However, if pica() is used a second time before it finishes loading the external JS, it should not load the library a second time so alert() will run.

let picaStatus = 0;

function pica(...args) {
  if (picaStatus == 1) { // library previously loaded
    pica.resizeCanvas(...args);
  } else if (picaStatus == 0) { // library hasn't been loaded
    picaStatus = -1;
    $.getScript("//cdnjs.cloudflare.com/ajax/libs/pica/2.0.4/pica.min.js", () => {
      picaStatus = 1;
      pica.resizeCanvas(...args);
    });
  } else if (picaStatus == -1) { // library is currently being loaded by another call
    alert('loading collision');
  }
}

Instead of throwing an alert() and dropping the function call, how can I make the second function call wait until the library is loaded?

TPL DataFlow and architecture design

TPL DataFlow library very useful for my application. I have about 10 blocks and I think a count will increase.

When I prepared prototype of my application I was confused because I understood that I got functional design.

    void BIG_WORKFLOW_METHOD(){
    ...
    var block1 = new TransformBlock<string, string>(...);
    var block2 = new TransformBlock<string, string>(...);
    var block3 = new TransformManyBlock<string, string>(...);
    var broadCastBlock = new BroadcastBlock<EventObject>(ev => ev);
    ...
    var block9 = new ActionBlock<string>(...);
    var block10 = new ActionBlock<EventObject>(...);
    block1.LinkTo(block2);
    block2.LinkTo(block3);
    block3.LinkTo(block4);
    broadCastBlock.LinkTo(block5);
    broadCastBlock.LinkTo(block6);
    ...
    }

I need to transform my big-workflow-method to OOP-design. I want to be able to add or remove steps from my workflow in future easy. May be somebody solve that task?

I guess the most appropriate architecture for Workflow is State design pattern, but I think TPL DataFlow already use this pattern and that will be over-architect.

How to use a Factory with polymorphism and strategy?

Let's assume we have a simple payment feature on an online shop. We want to manage different transactions with different processors of transactions:

  • A transaction can be a payment or a refund.
  • A processor of transactions can be Paypal or Payplug.

So we have the following classes:

class PaymentTransaction implements Transaction {

}

class RefundTransaction implements Transaction {

}

class PaypalProcessor implements Processor {

}

class PayplugProcessor implements Processor {

}

As suggested in this answer, we could use the following class which uses Strategy and polymorphism.

class PaymentProcessor {
     private Processor processor;
     private Transaction transaction;

     public PaymentProcessor(Processor processor, Transaction transaction) {
          this.processor = processor;
          this.transaction = transaction;
     }

     public void processPayment() {
         processor.process(transaction);
     }
}

We assume the processor and the transaction to use are given from the database. I wonder how to create the PaymentProcessor object.

It seems that an abstract factory class with only one method is still a valid Abstract Factory pattern. So, in this case I wonder if using Abstract Factory would be relevant.

  • If yes, how to implement it?
  • If no, should we use Factory Method pattern with a PaymentProcessorFactory class to create PaymentProcessor with his two attributes according the details given from the database?

What is a best practice to use a Factory in this case?

Parent child design to easily identify child type

In our database design we have a couple of tables that describe different objects but which are of the same basic type. As describing the actual tables and what each column is doing would take a long time I'm going to try to simplify it by using a similar structured example based on a job database.

So say we have following tables:

enter image description here

These tables have no connections between each other but share identical columns. So the first step was to unify the identical columns and introduce a unique personId:

enter image description here

Now we have the "header" columns in person that are then linked to the more specific job tables using a 1 to 1 relation using the personId PK as the FK. In our use case a person can only ever have one job so the personId is also unique across the Taxi driver, Programmer and Construction worker tables.

While this structure works we now have the use case where in our application we get the personId and want to get the data of the respective job table. This gets us to the problem that we can't immediately know what kind of job the person with this personId is doing.

A few options we came up with to solve this issue:

Deal with it in the backend

This means just leaving the architecture as it is and look for the right table in the backend code. This could mean looking through every table present and/or construct a semi-complicated join select in which we have to sift through all columns to find the ones which are filled.

All in all: Possible but means a lot of unecessary selects. We also would like to keep such database oriented logic in the actual database.

Using a Type Field

This means adding a field column in the Person table filled for example with numbers to determine the correct child table like:

enter image description here

So you could add a 0 in Type if it's a taxi driver, a 1 if it's a programmer and so on...

While this greatly reduced the amount of backend logic we then have to make sure that the numbers we use in the Type field are known in the backend and don't ever change.

Use separate IDs for each table

That means every job gets its own ID (has to be nullable) in Person like:

enter image description here

Now it's easy to find out which job each person has due to the others having an empty ID.

So my question is: Which one of these designs is the best practice? Am i missing an obvious solution here?

Redux Store or react state concept Vs Sql request

I am wondering what is the best design approach between using a big state (store) and sql request in database. Let's say you have a Todo CRUD application. You can save the Todos list in store within Redux implementation. What is the best approach if you want to make complex statistics on those TODOs: Reducers or sql requests?

For example, you want to get all todos for the current month:

  1. Reducers/store approach
    You can get all the todos list from the store and filter todos by date to get all todos for the current month.
    • Pros:
      CRUD actions easy to manage, one state changes in the store (todos list)
      Low client/server traffics
    • Cons
      Business logic on client side
      client overhead for large data processing
  2. Sql request approach:
    Complex request in database to get those todos and save the state 'currentMonthTodos' in the store. In this case you get your current month Todos list from currentMonthTodos state
    • Pros:
      Business logic on server side
      Reducing page load time for large datas
    • Cons
      Poor state management for CRUD actions
      High network traffic
      Size of the store grows up

Where should intermediate data be stored in mvc?

Some application works with geometric primitives. They are circles, squares etc. User can change positions of such primitives, also he can copy/delete/select them. Where should intermediate data be stored in mvc? Some kind of intermediate data in such case are (for example) selected primitives. As I understand it is not model data. They are data which represent state of View. But what about notifications about changing selection? I suppose that Controller should keep this data and notify listeners about appropiate changes of selection. But in my understanding of mvc, Controller should not know about view

html5 regex for a capitalized first letter

Is it possible to use HMTL5 patterns to verify that the first letter of a string is capitalized? I looked on http://ift.tt/iAgPUp and on Stack Overflow but couldn't find anything. I also am not familiar enough with REGEXs to try to create my own. Thanks so much!

Proposal for Improved Active Record Pattern

I wanted to propose a design pattern I've come up with. I haven't seen it used before which is surprising since it fixes a common problem, so I was wondering if I just haven't found it, or whether my solution is undesirable or breaks any major design principles. If anyone could provide me with any links to where it's been described, or provide opinion or critique. If you have none then feel free to use =)

I often use the Active Record Pattern due to it's simplicity, fully aware of the undesirable coupling it creates on the database, and litters domain objects with ugly SQL code. So my proposition is the following:

class User{

   id:string;
   firstName:string;
   lastName:string;

   constructor(id:string, firstName:string, lastName:string){
      this.id=id;
      this.setFirstName(firstName);
      this.setLastName(lastName);
   }

   function getFirstName(){
      return this.firstName;
   }

   function getLastName(){
      return this.lastName;
   }

   function setFirstName(firstName:string){
      this.firstName=firstName;
   }

   function setLastName(lastName:string){
      this.lastName=lastName;
   }

}


class UserDB extends User{
   user:User;

   constructror(user:User){
      this.user=user;
   }

   function getFirstName(){
      return this.user.getFirstName();
   }

   function getLastName(){
      return this.user.getLastName();
   }

   function setFirstName(firstName:string){
      this.this.setFirstName(firstName);

      this.update();
   }

   function setLastName(lastName:string){
      this.setLastName(lastName);

      this.update();
   }

   function update(){
      // sql execution script
      // update user set first_name=getFirstName(), last_name=getLastName() where id=this.user
   }
}

An then in code which creates instances, whether it be a factory or repo of User would then do this:

function getUser(id:string):User{
   // select first_name, last_name from user where id=id;

   var user=new User(id, firstName, lastName);
   var userdb=new UserDB(user);

   return user
}

This is perhaps a bad example since typically a User doesn't change their first or last name but it was the simplest example I could come up with!

I am essentially using the GoF Decorator pattern, but have never seen it used this way for data access.

It still has the undesirable effect of performing a db access per property update, just as the active record pattern does, but doesn't it at least remove the coupling from the User class to the database and removes the ugly SQL code. The UserDB implementation could go in the same package as other data access classes. Does the solution unbreak the SRP principle from the Active Record Pattern. I know that Active Record Pattern is considered by some to be an anti-pattern, but it is easy to use on simple applications, so point is just the following, if you ARE going to use it, wouldn't this is a better implementation for it?

dimanche 29 janvier 2017

Which design pattern Django follows and which design pattern we should follow while development using Django?

I eager to know that which design pattern Django follows and if Django is not using any design pattern then which one we should use?

I searched it thoroughly and didn't get any suitable answer for same so can anyone please clear it?

Thanks in advance.

Writing a Python program for string pattern matching

I want to create a class in Python called Pattern that will take two methods, matches and setwildcard (info here). I've tried setting up the class but I'm not sure where to go from there. Any help would be great.

Getting string characters inside, and outside a set of brackets with string patterns in Lua?

I'm trying to create a string pattern that will match both non-space characters, and all characters inside a set of brackets. For example, a sequence such as this:

local str = [[
    This [pattern] should [return both] non-space 
    characters and [everything inside] brackets
]]

Would print out This, [pattern], should, [return both], non-space ... etc. I've been going at this for a while, and came up with a very close solution that I know the problem to, but cannot seem to solve. Here's my attempt:

local str = [[
    This [pattern] should [return both] non-space 
    characters and [everything inside] brackets
]]

for s in string.gmatch(str, "%S+%[?.-%]?") do
    print(s)
end

The issue is that spaces should be allowed inside the brackets, but not outside. This would print something like: This, [pattern], should, [return, both], non-space ... etc

Notice that [return and both] are two different captures, opposed to returning [return both]. I'm still sort of new to string patterns, so I feel like there's a few options I could be overlooking. Anyway, if anyone is experienced with this sort of thing, I sure would appreciate some insight.

While using an object adapter design pattern why is it required to subclass Adaptee to override Adaptee behavior

For an Object Adapter design, GoF states :

makes it harder to override Adaptee behavior. It will require subclassing Adaptee and making Adapter refer to the subclass rather than the Adaptee itself

My question is that why is this subclassing required when we are creating the clases as follows :

class Target {
    public :
    virtual void op() = 0 ;
} ;

class Adaptee {
    public :
    void adapteeOp() {cout<<"adaptee op\n" ;}
} ;

class Adapter : public Target {
    Adaptee *adaptee ;
    public :
    Adapter(Adaptee *a) : adaptee(a) {}
    void op() {
        // added behavior
        cout<<"added behavior\n" ;
        adaptee->adapteeOp() ;
        // more added behavior
        cout<<"more added behavior\n" ;
    }
} ;

main() { //client
    Adapter adapter(new Adaptee) ;
    adapter.op() ;
}

I have not been able to appreciate the requirement for subclassing as mentioned by GoF when I am able to override the behavior here also.

Please explain what is the point that I am missing out.

Android design pattern Tutorial

I'm developing android apps for a while, all these time I'm following the MVC design pattern, with some changes overtime. But as I read(see) design patterns like MVP, MVVM have some serious advantages than MVC. I've searched for some good tutorials, articles but have not found one that explains these design patterns with a complete example and some details explanation to understand these design patterns.

So here, I like to know, if anybody knows any good tutorials(video) on MVP, MVVM. And is there any other better design pattern than these two?

scala pattern matching with variable in case clause

I want to do a pattern matching with scala but I have the problem that I want to know if the object is the same type as a variable.

I have this:

user.role match {
  case this.role.getClass => true //here says stable identifier required, but this.role.getClass found
  case _: Role_Admin => true
  case _ => false
}

I understand the problem here, but I need to match it with the variable stored in the instance. Is there any way to do that? Or does anyone know any other good way to do that?

Thank you!

Expose a Singleton to other classes using an interface

I'm making a game in Unity C# using a Singleton GameManager and I was warned that using references of the class in other scripts like GameManager.instance.someVar makes the code fragile and difficult for later edit. So I looked for how to access a singleton with interfaces but haven't found what I was after. As I wish to code properly, I would like someone to point me to a decent source that tells me how to do so, or have him/her tell me in brief.

Using business software development concepts in game development?

Over the past few years I had the chance to develop “business” software applications including mobile apps, backend systems and frontend applications for which many different principles and concepts were used such as object-relational mapping, reactive programming, dependency injection, Model-View-Controller-Pattern and many more.

While getting started with some game programming I wonder how some of those concepts can be used for developing games. For example when programming a world builder game like Anno 1602 (1602 A.D.) I can imagine implementing production buildings as microservices.

My question is about thinking outside of the box; it is not important whether using some concept could have a serious performance impact for the game or not.

What concepts used in non-game application programming could be used for game development and in which way?

What is a good resource for learning design patterns for OOP in Python? [on hold]

Background: I am a humanist researcher in the field of Digital Humanities who "learned" programming along the way. I do a bit of XML technologies here, a bit of JavaScript there, but most things I do in Python (sklearn, numpy stuff mostly). I even got a little bit into Haskell for some time just because it is fun and I am fascianted by FP concepts. However, in all of these areas my knowledge consist of unreasonable fragments. This became a problem, now that I am working on privat bigger software project in Python.

Need: What I was looking for for a long time now is a resource which enables me to find good OOP design patterns for the design of classes and the communication between classes in this and future software projects. It is not that I do not know the basic concepts of OOP and how I use them in Python. It is more that now when the project is becoming bigger the whole architecture begins to feel inconsistent and scrappy.

Obstacle: There are many resources about OOP in Python on the web and also many Python books. However, I feel in between what exists. There is one part of resources which does the basics again and again and there is another part which does not talk about language features and how they work at all anymore focusing on purely theoretical stuff. What I am looking for is a resource which begins medium level Python, focusing on medium level OOP design patterns but not completely refraining from showing how to implement this in Python.

I am grateful for any suggestion (Book, Tutorial, etc.)

samedi 28 janvier 2017

How to meet this requirement?

I am not sure if the question right fits here.(Sorry!!)

I am in need to write WebApi controllers. The task is to migrate from exisitng normal mvc controller to WebApi controllers.

In this projects, almost all the beauty of the programming is used like:-

  • Design Patterns - Repository + UOW, Factory + nUnit
  • Dependency Injection
  • SOLID

This is my model in the MyApp.Domain layer

public class Customer
{
   //please note that we are using Repository pattern & so no Data Annotations like Required, Key are not used here. 
   public int CustomerID { get; set;}

   public string CustomerName { get; set;}

   public string EmailAddress { get; set;}
   // & so on
}

In the MyApp.UI layer, exists ViewModel for validation & then passing the model to Service layer that. So this is how my MVC controllers looks like

  public class CustomerVM
  {
     [Required]
     public int CustomerID { get; set;}  // & so on the other properties.

  }


  public ActionResult Registration(Customer VM)
  {
         if(Modelstate.IsValid)
         {
            //call service layer 
         }
         else
         {

         }
  }

Now my immediate task is to migrate this controller to WebApi controller. Henceforth, I created a separate project as MyApp.WebApi

Now my doubt is how should I pass the model to this WebApi controller.

I am thinking to detach the ViewModel from UI layer to separate project as MyApp.ViewModels and put all the viewmodels in this layer & reference the dll in UI layer & WebApi layer.

 public string POST([FromBody]CustomerVM customer)
 {
    if(Modelstate.IsValid)
    {
        //call the other service layer which will take care of DB handling
       return "Success";
    }
    else
    {
       return "Error";
    }   
 }

Is this the right way to do & any other right way to do this??

What kind of construct / pattern is that?

I've seen in a library something like that (Number is augmented by the function integer):

Number.prototype.integer = function () {
    return Math[this < 0 ? 'ceil' : 'floor'](this);
}

console.log ((-10/3).integer());

What is going on here? What kind of pattern is that:

Math['ceil'](this)

A pure Bash Cuting script that do not provide efficient work

Already posted solution of using awk or sed are quite standard and help in case something did not work correctly.

like for a :

StringStr="ValueA:ValueB,ValueC:ValueC" ; 

echo ${StringStr} | gawk -F',' 'BEGIN{}{for(intx=1;intx<=NF;intx++){printf("%s\n",$(intx))}}END{}'

do produce the same result, but a restricted user that can log into it's account and have fewer option like not allowed to used awk or gawk for a specific reason does have to produce something that have to work every-time.

For efficient reason I do develop my own Bash Function Library on github.com and fall on a technique that do not work as supposed and here a working example:

This technique use the Bash 'Remove matching prefix pattern' and 'Remove matching suffix pattern'. The goal is to get a string of chained information to use a simple as possible the bash-shell element to extract-out inserted element.

By the present I do have first statement to obtain a String out of a specific format: Ex:

StringPattern="__VALUE1__:__VALUE2__,"

The format suppose adding in chain, many Pattern of type StringPattern. The remain ',' will be used to split and separate the string back in VALUE1:VALUE2 form .

like StringStorage will hold many times, parsed StringPattern, here 2 examples: 1 - sample 1

StringPattern="VariableA:InformationA,"
StringStorage="${StringStorage}${StringPattern}" ;

2 - sample 2

StringPattern="VariableB:InformationB,"
StringStorage="${StringStorage}${StringPattern}" ;

At this moment, StringStorage hold properly this information:

StringStorage="VariableA:InformationA,VariableB:InformationB,"

Now with StringStorage, the bash algorithm made out of a mix of 'Remove matching prefix pattern' and 'Remove matching suffix pattern' does work for this case :

### Description of IntCsvCount
### does remove all chosed Comma Separated value ',' from StringStorage
### and subtract from the original length the removed result from this 
### subtraction. This produce IntCsvCount == 2
IntCsvCount=$( cstr=${StringStorage//,/} ; echo $(( ${#StringStorage} - ${#cstr} )) ) ;

### Description of 
### Will be re Variable used to put the Extracted sequence.
bstr="" ;

### Description of for
### Received information from IntCsvCount it should count
### from 0 to Last element . This case it's ${IntCsvCount}-1 or 1 in 
### my example.

for (( intx=0 ; intx <= ${IntCsvCount}-1 ; intx++ )) ; do
  ### This extracting First Segment based on 
  ### Remove  matching suffix pattern ${parameter%word} where 
  ### work is ${astr#*,} ( Remove matching prefix pattern ) of 
  ### everything in $astr until find a ',' .
  bstr=${astr%*${astr#*,}} ;
  ### Destroying the $bstr part in by starting the astr to position of
  ### the end of size equivalent of bstr size (${#bstr}), end position is
  ### equal to [ Highest-String size ] - [ Shortest-String size ] 
  astr=${astr:${#bstr}:$(( ${#astr} - ${#bstr}))} ;
  echo -ne "Element: ${bstr}\n" ;
done

This should produce the following answer.

Element: VariableA:InformationA,
Element: VariableB:InformationB,

Putting this into a function will require only to change the CSV by ':' and let extract the 'VariableA' and 'InformationA'.

The problem start using a String with non uniform. As observed on this board, example of a sentence and cutting a part should work on non-uniform string, but here a sample that do not work. And I do have more than one advise in hand from using gawk, sed, even cut but from this algorithm it does not work with this sample :

astr="master|ZenityShellEval|Variable declaration|Added Zenity font support to allow choosing both font-name and size and parsing the zenition option, notice --font option require a space between font and size.|20170127|"

comming from

astr=$( zenity --width=640 --height=600 --forms --show-header --text="Commit Message" --add-entry="Branch name" --add-entry="function" --add-entry="section" --add-entry="commit Message" --add-calendar="Commit Date" --forms-date-format="%Y%m%d" --separator='|' ) ;

I am also enforcing the output to look like what StringPattern should look like: astr="${astr}|" ;

The same code except CSV (Comma Separated Value) was changed from ',' to '|'

IntCsvCount=$( cstr=${astr//|/} ; echo $(( ${#astr} - ${#cstr} )) ) ;
bstr="" ;
for (( intx=0 ; intx <= ${IntCsvCount}-1 ; intx++ )) ; do
  bstr=${astr%*${astr#*|}} ;
  astr=${astr:${#bstr}:$(( ${#astr} - ${#bstr}))} ;
  echo -ne "Element: ${bstr}\n" ;
done

Where this time output generate following output:

Element:master|ZenityShellEval|Variable declaration|Added Zenity font support to allow choosing both font-name and size and parsing the zenition option, notice --font option require a space between font and size.|20170127|
Element:
Element:
Element:

Is there some reason why it should not work every time ?

Submit form to another controller in Symfony

I have a page index.html.twig which contains a Form this form when submitted, get validated and the result is shown in a page success.html.twig. Now I have a new requirement where the page success.html.twig itself contains a Form which should contain the values which were passed by the form from index.html.twig and if the user wants the new form should also allow the user to do search directly from success.twig.html. The requirement is inspired by hostel world.

Questions:

  1. Is there a design pattern which I could use to implement a solution
  2. My current thinking is to create a new Action for success.html.twig and submit the form to thatAction instead of rendering success.html.twig from index.html.twig's Action. Is it correct? How can I implement it?

Code (Partial):

 /**
 * @Route("/", name="homepage")
 */
public function indexAction(Request $request)
{
    $event = new Event();
    $form = $this->createForm(MyForm::class, $event);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()) {
        $event->setPlace($form["place"]->getData());


        $event->setDate($form["date"]->getData()->modify('+12 hours'));
        return $this->render('default/frontend/success.html.twig',
            array('events' => $events, 'cityName' => $cityName, 'cityImage' => $cityImage)
        );
    }

    return $this->render('default/frontend/index.html.twig', array('form' => $form->createView()));
}

PHP abstract classes and protected methods

Like title say I have a problem with this code:

abstract class AClass {
    abstract protected function a1();
    abstract protected function a2();

    public function show() {
        return $this->a1() . "<br>" . $this->a2();
    }
}


class A1 extends AClass {

    protected function a1() {
        return 'A1a1';
    }

    protected function a2() {
        return 'A1a2';
    }
}

class A2 extends AClass {

    protected function a1() {
        return 'A2a1';
    }

    protected function a2() {
        return 'A2a2';
    }
}

class AA {

    public function __construct() {
        $a11 = new A1();

        $a22 = new A2();

        $this->inter($a11);
        $this->inter($a22);
    }

    private function inter(AClass $class)  {
        echo $class->show();
    }
}

$aa = new AA();

It is throwing:

Fatal error: Call to protected A1::a1() from context 'AA' in C:\xampp\htdocs\Learning\index.php on line 38

Line 38 is this:

$a11 = new A1();

I do not understand why it is throwing that error if I'm not calling a1() at that line.

Thanks and regards

Javier

use java.util.function.Function to implement Factory Design Pattern

Is it correct to use java.util.function.Function to implement Factory Design Pattern

In the following example, I've used Function reference to instantiated a Person type object.

import java.util.function.Function;

public class Main {
    public static void main(String[] args) {
        Function<String , Person> myFunc = (String s) -> new Person(s);
        Person p = myFunc.apply("Shan");
        System.out.println(p.getName());
    }
}

class Person{
    private String name;

    public Person(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }


}

Interface and implementation design structure?

I'm quite new to designing large programs in C++. I'm writing series of operations, each of which have their own class, which will be invoked by the ProcessMgr class.

I'm using ProcessMgr as an interface class, from which each operation can be invoked:

class ProcessMgr
{
 private:
   class OperationOne;
   class OperationTwo;
   class OperationThree;
}

class ProcessMgr::OperationOne 
{
 private:
   ...
};
class ProcessMgr::OperationTwo
{
 private:
  ...
};
class ProcessMgr::OperationThree
{
 private:
  ...
};

This enables me to control the types of access to the Operation classes, therefore not exposing much of their underlying code.

My questions:

1) Is this a good approach to designing large programs? Are most libraries, such as CURL, structured in this way?

2) Are there better/more efficient methods of separating interface and implementation?

singleton pattern performance drawbacks

I implemented the Singleton pattern in my game to access instance functions and variables like they were static. All well and good, I can use it conveniently. However, from my understanding, everything has a cost and this ease of use must have some kind of drawback. Question is, is it a lot of expense to frequently use GameManager.instance.someOtherClass.someVariable for example? In general, how performance friendly the Singleton is?

vendredi 27 janvier 2017

Builder Pattern in R

I'd like to generate a JSON request. However, there are a TON of variations on the parameters that could be easily written using the builder pattern. However, I cannot figure out for the life of me a good way to do it.

I'm currently using the jsonlite package to generate my JSON requests. It handily converts lists into JSON. I was thinking that one way to do this would be to return a partially configured list for each function call, but this doesn't really allow the chaining that makes the builder pattern so useful.

Is there a good way to handle this? I'm pretty new to working with R as more than just a statistical language so I'd really appreciate an experienced person helping me.

Thank you!

What is the best pattern to use for accessing multiple external API endpoints from within my app

I am trying to determine the best pattern to use to improve our use of a client's custom API endpoints. Using their endpoints can be a little screwy as they can use slightly different types of authentication (token vs api key often) depending on functionality and login state.

Right now we have a single function we call that resolves all of this and spits back an array containing details and an object from the endpoint. But the calling code must know the api path ahead of time (such as "customer/order-list" or "order/rates") before calling the function and then the functions have to deal with inconsistent data sets.

My thought process is to extend a base class with the core calling functionality and then each class that extends that will contain the various endpoint paths and how to work with them. I also want to hydrate consistent objects with the data returned so that the data I use throughout the system and pass to the front-end is consistent and functional. And I want to make that data exchange bi-directional.

I want this as extensible as possible as we add on new API endpoints that they are building for new functionality. We are pushing for more consistency on their end, but we still have to deal with legacy endpoints built in an ad-hoc way.

I looked at the Gateway pattern, but I don't think it quite fits the bill for what I need.

Does anyone have any suggestions for programming design patterns that might make this easier and more manageable for me and my team?

We are also building this in PHP (I know, other devs roll their eyes at the language, but I do not have a choice in the matter). So something that can be implemented with PHP 7's limitations would be preferred.

Thanks!

Mixing Builders and Factory pattern is it a good idea?

I have an object Carconstructed using builder pattern. Issue was a lot of code redundancy.

    Car.Builder builder = new Car().Builder("Mercedes");
    builder.numDoors(carConfig.getNumDoors()
    builder.engineType(carConfig.getEngineType())
    builder.isManual(isManual)
    builder.build())

    Car.Builder builder = new Car().Builder("BMW");
    builder.numDoors(carConfig.getNumDoors()
    builder.engineType(carConfig.getEngineType())
    builder.isManual(isManual)
    builder.build())

    Car.Builder builder = new Car().Builder("FlyingCar");
    builder.numDoors(carConfig.getNumDoors()
    builder.engineType(carConfig.getEngineType())
    builder.wing(TypeName)
    builder.build())

So thought of an idea to reduce code clutter using factory pattern. Using the factory below, I can create Car easily.

Car mercedes = CarFactory.createNonFlyingCar("Mercedes");

Car bmw = CarFactory.createNonFlyingCar("BMW");

Car flyCar = CarFactory.createFlyingCar("FlyingCarBrand");

public class CarFactory {

    // brand can be BMW or Mercedes or Audi etc.
    public static Car createNonFlyingCar(String brand, CarConfiguration carConfig, Engine engine) {
        Car.Builder builder = new Car().Builder(brand);
        append(builder, carConfig.getNumDoors(), carConfig.getEngineType(), engine.isManual()).build();
    }

    public static Car createFlyingCar(CarConfiguration carConfig, Wings wings) {
        Car.Builder builder = new Car().Builder("NewFlyingCar");
        append(builder, carConfig.getNumDoors(), carConfig.getEngineType()).wings(wing.getType()).build(); // added extra 'wings' method here.
    }

    // overload append.
    private static void append(
        Car.Builder builder,
        int numDoors,
        Sting engineType,
        boolean isManual;
    )
    {
        return append(builder, numDoors, engineType).isManual(isManual);

    }

    private static void append(
        Car.Builder builder,
        int numdoors,
        String engineTye
    )
    {
        return builder.numdoors(numdoors).engineType(engineTyoe);
    }

}

  1. One thing which I did in the factory was overloading append method. When common fields were involved, used them. Eg: numdoors and enginetype was shared between flying and nonflying cars. so I created an append(numdoors, engineType) which was called by append with more param.

  2. Next thing is the wing which was unique to flying car was left out of append.

Is this a known pattern ? Good ? Bad ? And Why ?

Abstracting Spark API

I would like to understand if anyone in the community has built services that effectively perform calculations on an underlying distributed datastore (Hadoop/Parquet files) using Spark but at the same time been able abstract out the Spark API functionality. This may not seem counter intuitive given the compute paradigm employed in spark i.e send the compute to the data but our architecture and management teams are keen on building vendor/technology independence upfront. Are there any design patterns that can help with this abractions? The typical presentation, service, DAO tier found in many applications to separate your business logic doesn't seem relevant here I suspect.

I would we very interested if anyone else has done this or even been given the same challenge.

Thanks

Javascript TDD - frameworks and design patterns

I am trying to setup a methodology for Javascript test driven development for my team.

We will develop Javascript code which we will use in a CRM app and we also want to have everything in sync with a Git Repository.

We will use Test driven development and I am currently deciding on which frameworks to use and what module pattern to use.

For testing I am inclined to use:

- Development environment: Visual Studio Code
- Testing framework: Mocha
- Assertion library: Chai
- Mocking : Sinon.js
- Test runner : Karma
- Module pattern : CommonJS
- Module bundler : Browserify

I am not sure what module pattern and bundler we should use and also I need some help deciding on what tool to use for keeping everything in sync in a GIT repo.

May I receive some advices/input on this ?

Thank you.

What design patter / general approach should I use?

I've wrote a JavaScript (Node.JS) crawler, however although it does work, it does not satisfies me. The code I produced is not what I could qualify as elegant, scalable or really read-able.

I would like to rewrite it using a design pattern and a more elegant approach (with OOP), however I am quite new to this aspect of programming and does not know what should I chose.

Basically my application is designed like this:

  • A home page which displays the crawler results according to filters chosen by the user
  • A crawling page where you can refresh the results (only each x hours to avoid overloading the server)

So far I implemented a very basic architecture using an app.js, my_route.js and views/*.pug ; my_route being either home or crawl.

What would be the best approach to this? I would like to chose a DP and a few ideas on how should I implement OOP (what classes should do what etc).

Thanks,

Overusing code behind in my WPF application?

I'm creating a simple WPF application for practice purposes only, but I have little experience in WPF. Using WPF XAML seems troublesome to me, as I have a lot more experience with C# Console and especially with the videogame engine Unity, where devs have access to an Editor (analogues to the Design Window in WPF) and the code behind, with no XAML whatsoever. This is why I tend to use less XAML and much code behind.

For example here, I modify the Margin property of a button, while I set its Opacity to 1; this all happens upon a click event to the grid, which calls the function (exactly the way it's done in Unity):

public  void Grid_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            RandomButton.Margin = new Thickness(0, 0, 0, 0);
            RandomButton.Opacity = 1;

        }

If I'm not mistaken, this can be achieved through Data Binding in XAML as well, although it seems to be a lot more complicated method seemingly producing the same result.

So my questions are: is there a difference between the two ways, say, performance-wise or in terms of expandability (which one would be easier to expand/modify later)? Which one is used in the industry?

Passing model with dependencies to rest api service

What's the "good practice" for RESTful api service when I want to pass model which has references to another model? Like:

class SomeClass
{
int Id
int Number
List<Student> Students
}

class Student
{
int Id
string Name
string Surname
SomeClass someClass
}

and while creating new student: POST .../api/students/ should I pass in student object entire SomeClass model or only class Id?

How to use an Interface to access classes that implemented it?

I'm trying to understand advanced use of interface. Lets say I have an inter face like bellow:

public interface IMyInterface
{

}

I have two class which implement the above interface like bellow.

public class A:IMyInterface
{
    public string AName { get; set; }
}

public class B : IMyInterface
{
    public string BName { get; set; }
}

Now I have four methods like below:

public IMyInterface CreateRawResponse()
    {
        if (condition)
        {
            return new A
            {
                AName = "A"
            };
        }
        else
        {
            return new B
            {
                BName = "B"
            };
        }
    }

    public string CreateResponse(IMyInterface myInterface)
    {
        return myInterface. // I would like to access the properties of the     parameter, since its actually a class
    }
    public string CreateResponseForA(A a)
    {
        return a.AName;
    }

    public string CreateResponseForB(B b)
    {
        return b.BName;
    }

Finally I'm trying to call the mehtods like this:

var obj = new Program();
        var KnownResponse = obj.CreateRawResponse(); // Lets say I know I will get type A
        var test1 = obj.CreateResponseForA(KnownResponse); //But I can't call like this, because CreateResponseForA() is expecting IMyInterface as parameter type.

        var UknownResponse = obj.CreateRawResponse(); // Lets say I don't know the response type, all I know is it implemented IMyInterface

        var test2 = obj.CreateResponse(UknownResponse); // I can call the method but can access the properties of the calling type in CreateResponse() mehtod.

How to handle this kind of situation? I believe there might some design pattern to solve this, but I'm not used to design patterns. Any advice would be really helpful.

Is it right usage of interfaces?

I think about such usage of interfaces in c#. Is it right usage of interfaces?

public interface IAnimal
{
    int LegsCount { get; }
}

public interface ICat : IAnimal
{
    string Voice { get; }
}

public abstract class FourLegsAnimal : IAnimal
{
    public int LegsCount => 4;
}

public class DummyCat : FourLegsAnimal, ICat
{
    public string Voice => "I am dummy cat";
}

This code works, but I don't know, whether I should use this technique.

jeudi 26 janvier 2017

Workflow Design pattern combined with Task Pattern?

I'm currently working on an enterprise application that's performing a long non-linear tasks.

An abstraction of the workflow:

  1. Gather neccessary information (can take minutes, but not always necessary)
  2. Process data (always takes very long)
  3. Notify several worker who post-process the result (in new tasks)

Now, I have created 2 services, that can solve step 1 and 2. As the services shouldn't know of each other, I want to have a higher order Component that coordinates the 3 steps of an task. Think of it as an Callable which sends the task to service one, wakes up again when service 1 returnes an result, sends it to service 2, ..., sends final result to all post-processors and ends task. But as it is likely to have 100'000s of queued tasks, I don't want to start 100'000s threads with task-control callables which even if being idle like 99.9% of the time still would be an massive overhead.

So got anybody an idea of controling this producer consumer queue-like pattern encapsulated in a task-object or somebody knows of an framework simplifying my concern?

Looking for design pattern - one type of object with different sources

With CsvReader:

class CsvReader {
  public static function createFromString($csvString){
    /.../
    return new static($something)
  }
}

I'm planning to operate with csvString coming from different sources: reading file, from body of http response, etc. So im looking for design pattern for easy creation of this csvReaders objects. For now, i have ended with something like this:

use SplFileInfo as UploadedFile;
use CsvReader as Reader;
use GuzzleHttp\Client as HttpClient;

class CsvFactory {
  public function createFromUploadedFile(UploadedFile $uploadedFile){
    return Reader::createFromString($uploadedFile->toString());
  }

  public function createFromHttpEndpoint(HttpClient $client, $url, $options = array()){
    $response = $client->request('GET', $url, $options);

    if($response->getStatusCode() != 200){
       throw new Exception('Http Code Not Ok', $response->getStatusCode());
    }

   return Reader::createFromString($response->getBody());
 }
}

I feel that it could be accomplished in the better way. But how?

Can a responsibility be detached from a decorator implemented in C++

For Decorator design pattern, GoF clearly states that :

With decorators, responsibilities can be added and removed at run-time simply by attaching and detaching them.

I am trying to build a skeleton code in C++ where I can easily see how this pattern can add responsibilities to an undecorated object.

My question is how can I remove a particular responsibility. Removing the last wrapped responsibility can be done easily. But can I also remove a responsility added in between.

Here is my sample code :

class Icecream { //Component
    public :
    virtual void addToppings() = 0 ;
    virtual Icecream *getUndecorated() = 0 ;
} ;
class PlainIcecream : public Icecream { //Concrete Component
    public :
    void addToppings() { cout<<"I am just plain icecream, you may add more flavors\n" ; }
    Icecream * getUndecorated() {return this ; }
} ;
class Topping : public Icecream { //Decorator
    protected :
    Icecream *icecream ;
    public :
    Topping(Icecream *i) : icecream(i) {}
    void addToppings() { icecream->addToppings() ; }
} ; 
class PeanutToppings : public Topping { //Concrete Component A
    public :
    PeanutToppings(Icecream *i) : Topping(i) {}
    void addToppings() {
        Topping::addToppings() ;
        cout<<"Adding peanut toppings for great taste\n" ; 
    }
    Icecream * getUndecorated() {return icecream ; }
} ;
class CandyToppings : public Topping { //Concrete Component A
    public :
    CandyToppings(Icecream *i) : Topping(i) {}
    void addToppings() {
        Topping::addToppings() ;
        cout<<"Adding candy toppings for yummy flavour\n" ;
    }
    Icecream * getUndecorated() {return icecream ; }
} ;
main() {
    Icecream *icecream_with_candy_and_peanuts = new CandyToppings(new PeanutToppings(new PlainIcecream)) ;
    icecream_with_candy_and_peanuts->addToppings() ;
    cout<<"_________________________________________________\n" ;
    Icecream *icecream_with_only_peanuts = icecream_with_candy_and_peanuts->getUndecorated() ;
    icecream_with_only_peanuts->addToppings() ;
    cout<<"_________________________________________________\n" ;
    Icecream *icecream_plain = icecream_with_only_peanuts->getUndecorated() ;
    icecream_plain->addToppings() ;
}

Now I want to know if it is possible to have an icecream with only candy topping from icecream_with_candy_and_peanuts. Please do not consider why do I want to do so. I am just trying to understand the term

detaching responsibilities

as mentioned in GoF.

How are separate responsibilities created in symfony?

This question is a bit hard to explain, but I'll try my best.

Say, I am creating an job add aggregator site. For this, I have 10 job sites I will crawl through, parse the HTML and get all the juices.

Now, since each sites template, url and the amount of information they contain is unique, something tells me the crawling part should be organized separately.

Normally, I could put it all together in

class CrawlerController extends Controller {

    public function fooDotComAction(){

    }

    public function barDotNetAction(){

    }
}

You can see the above is still better than dumping all my crawler logic inside the DefaultController, but even my example doesn't seem efficient, or modular.

It seems like a bad practice, I am wandering if there is some sort of feature in Symfony that provides an implementation or guide for such problems.

Decouple dependency using design pattern

I am trying to decouple dependency using design pattern.Can someone please point me best design pattern to decouple BookStorage dependency from Book Class? I tried doing factory pattern and factory method but got confused what to use?

namespace DesignPatterns
    {
        public interface IBook
        {
            string Execute(Guid bookId);
        }
    }

namespace DesignPatterns
{
    public class Book : IBook
    {
        public string Execute(Guid bookId)
        {
            var Id = 2;
            var storage = new BookStorage(Id);// Decouple this dependency? 

            // Get data
            var response = storage.GetBookData("GOF");
            return response;
        }
    }
}

namespace DesignPatterns
{
    public interface IBookStorage
    {
        string GetBookData(string name);
    }
}

namespace DesignPatterns
{
    public class BookStorage : IBookStorage
    {
        public BookStorage(int id)
        {

        }
        public string GetBookData(string bookName)
        {
            throw new NotImplementedException();
        }
    }
}

Business delegate pattern in javascript

Can anyone explain the usefulness of the business delegate pattern and give some examples of implementations or use cases in javascript?

Circular dependency in Spring injection - Is this bad design?

I am stuck with following issue :

I am trying to create beans as follows:

@Bean
public abc createABC() {
    return new ABC(--, def(),--);
}

`

@Bean
public DEF def() {
    return new DEF(--, createABC(),--
}

Any suggestions to get around this problem without chaging to setter based injection. Is it the indicative of bad design? In my situation this dependency is must. Please provide your viewpoints on this

mercredi 25 janvier 2017

Angular2 - Project Structure

I will start to a new Angular2 project and I am trying to understand the best structure for an Angular2 application. Let I have pages as home, auto-galleries, nearest-galleries, brands, cars and selected-car. And the navigation order is

home -> auto-galleries -> nearest-galleries

or

home -> brands -> cars -> selected-car

For the best approach, should I use components or modules for each page? If modules are a better approach, should I use hierarchical modules or all at same level under the root module?

For example, how good is the structure below:

app
├--- app.module.ts
├--- app.component.ts
├--- home.html
├--- brands
|    ├--- brands.module.ts
|    ├--- brands.component.ts
|    ├--- brands.html
|    ├--- cars
|         ├--- cars.module.ts
|         ├--- cars.component.ts
|         ├--- cars.html
|         ├--- selected-car
|              ├--- selected-car.module.ts
|              ├--- selected-car.component.ts
|              ├--- selected-car.html
|
├--- auto-galleries
     ├--- auto-galleries.module.ts
     ├--- auto-galleries.component.ts
     ├--- auto-galleries.html
     ├--- nearest-galleries
          ├--- nearest-galleries.module.ts
          ├--- nearest-galleries.component.ts
          ├--- nearest-galleries.html

Or is this structure better:

app
├--- app.module.ts
├--- app.component.ts
├--- home.html
├--- brands
|    ├--- brands.module.ts
|    ├--- brands.component.ts
|    ├--- brands.html
|
├--- cars
|    ├--- cars.module.ts
|    ├--- cars.component.ts
|    ├--- cars.html
|
├--- selected-car
|    ├--- selected-car.module.ts
|    ├--- selected-car.component.ts
|    ├--- selected-car.html
|
├--- auto-galleries
|    ├--- auto-galleries.module.ts
|    ├--- auto-galleries.component.ts
|    ├--- auto-galleries.html
|
├--- nearest-galleries
     ├--- nearest-galleries.module.ts
     ├--- nearest-galleries.component.ts
     ├--- nearest-galleries.html

Note: This is just a simple example, my application better fits a modular structure :)

DAO calling another DAO for nested objects

I'll explain it with an example. Assume, I've two tables:

Department(deptId, deptName)

Employee(empId, empName, deptId)

And a DAO for each of them. Employee has Many to One relationship to Department. In my domain model Employee refers Department object.

  1. Now when I call finder on EmployeeDAO, should I make a call to DepartmentDAO from inside EmployeeDAO, to return a completely formed Employee Object(with Department). Below post suggests against it:

Can a DAO call DAO?

  1. I also wanted to add Lazy loading for the Department, in which case it would seem that Employee Object should have a reference to DepartmentDAO, to call it when Employee#getDepartment() method is called, or is there any other way to do it.

    Note : Domain objects are just for the sake of discussion, so please don't suggest to remodel them.

How to design a system which sends records and retry them if acknowledgement is not receieved?

I am working on a project where I need to consume lot of records and then I am sending these records to some other system. Here is the flow:

  • Store all the records in a CHM from multiple threads. Records will come at very high speed.
  • From a background thread which runs every 1 minute send these records from CHM to some database.
  • After sending each record to database, add them to retry bucket as well so that it can be retried after a particular time if acknowledgment is not receieved for this record.
  • We also have a poller runnable thread which receives acknowledgment from database that tells these records have been receieved so once I get an acknowledgment back, I delete that record from retry bucket so that it doesn't get retried.
  • Even if some records are sent twice it's ok but its good to minimize this.

Below is my Processor class in which add method will be called by multiple threads to populate dataHolderByPartitionReference CHM. And then in the constructor of Processor class, I start the background thread which runs every 1 minute to push records from CHM to a particular database.

In the same constructor, I start the ResponsePoller thread which receives acknowledgment from database that tells these records have been receieved and if it is received, I will delete those record from the retry bucket so that it doesn't get retried otherwise I will retry again.

sendToDatabase method is where I send the records to database and in the same method, I add those records to retry bucket as well which will get retried from a different thread depending on acknowledgement.

public class Processor {
  private final ScheduledExecutorService executorServicePoller = Executors
      .newSingleThreadScheduledExecutor();
  private final ScheduledExecutorService executorService = Executors
      .newSingleThreadScheduledExecutor();
  // creating a ListeningExecutorService (Guava) by wrapping a normal ExecutorService (Java)
  private final ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors
      .newCachedThreadPool());
  private final AtomicReference<ConcurrentHashMap<Integer, ConcurrentLinkedQueue<DataHolder>>> dataHolderByPartitionReference =
      new AtomicReference<>(new ConcurrentHashMap<Integer, ConcurrentLinkedQueue<DataHolder>>());

  private static class Holder {
    private static final Processor INSTANCE = new Processor();
  }

  public static Processor getInstance() {
    return Holder.INSTANCE;
  }

  private Processor() {
    executorServicePoller.submit(new ResponsePoller());
    executorService.scheduleAtFixedRate(new Runnable() {
      @Override
      public void run() {
        validateAndSendAllPartitions(dataHolderByPartitionReference
            .getAndSet(new ConcurrentHashMap<Integer, ConcurrentLinkedQueue<DataHolder>>()));
      }
    }, 0, 1, TimeUnit.MINUTES);
  }

  // calling validateAndSend in parallel for each partition
  // generally there will be only 5-6 unique partitions max
  private void validateAndSendAllPartitions(
      ConcurrentHashMap<Integer, ConcurrentLinkedQueue<DataHolder>> dataHolderByPartition) {
    List<ListenableFuture<Void>> list = new ArrayList<ListenableFuture<Void>>();
    // For each partition, create an independent thread that will
    // validate the eventpackets and send it to the database
    for (Entry<Integer, ConcurrentLinkedQueue<DataHolder>> entry : dataHolderByPartition
        .entrySet()) {
     final int partition = entry.getKey();
      final ConcurrentLinkedQueue<DataHolder> dataHolders = entry.getValue();
      ListenableFuture<Void> future = executor.submit(new Callable<Void>() {
        public Void call() throws Exception {
          validateAndSend(partition, dataHolders);
          return null;
        }
      });
      // Add the future to the list
      list.add(future);
    }
    // We want to know when ALL the threads have completed,
    // so we use a Guava function to turn a list of ListenableFutures
    // into a single ListenableFuture
    ListenableFuture<List<Void>> combinedFutures = Futures.allAsList(list);

    // The get on the combined ListenableFuture will now block until
    // ALL the individual threads have completed work.
    try {
      List<Void> allPartitionEventPackets = combinedFutures.get();
    } catch (InterruptedException ex) {
      Thread.currentThread().interrupt();
      // log error
    } catch (ExecutionException ex) {
      // log error
    }
  }

  private void validateAndSend(final int partition,
      final ConcurrentLinkedQueue<DataHolder> dataHolders) {
    Map<byte[], byte[]> clientKeyBytesAndProcessBytesHolder = new HashMap<>();
    int totalSize = 0;
    while (!dataHolders.isEmpty()) {
      DataHolder dataHolder = dataHolders.poll();
      byte[] clientKeyBytes = dataHolder.getClientKey().getBytes(StandardCharsets.UTF_8);
      if (clientKeyBytes.length > 255)
        continue;
      byte[] processBytes = dataHolder.getProcessBytes();
      int clientKeyLength = clientKeyBytes.length;
      int processBytesLength = processBytes.length;

      int additionalLength = clientKeyLength + processBytesLength;
      if (totalSize + additionalLength > 64000) {
        sendToDatabase(partition, clientKeyBytesAndProcessBytesHolder);
        clientKeyBytesAndProcessBytesHolder.clear(); // watch out for gc
        totalSize = 0;
      }
      clientKeyBytesAndProcessBytesHolder.put(clientKeyBytes, processBytes);
      totalSize += additionalLength;
    }
    // calling again with remaining values
    sendToDatabase(partition, clientKeyBytesAndProcessBytesHolder);
  }

  // in this method, I am sending to database
  // and also adding it to retry bucket
  private void sendToDatabase(final int partition, final Map<byte[], byte[]> clientKeyBytesAndProcessBytesHolder) {
    if (clientKeyBytesAndProcessBytesHolder.isEmpty()) {
      return;
    }
    // this address will be unique always
    long address = getUniqueAddress(....);
    Frame frame = new Frame(.......);
    byte[] packedByteArray = frame.serialize();
    ZMsg msg = new ZMsg();
    msg.add(packedByteArray);

    ZMQObj zmqObj = PoolManager.getInstance().getNextSocket();
    Socket socket = zmqObj.getSocket();
    msg.send(socket);
    msg.destroy();

    // after sending, add to retry bucket
    RetryTask.getInstance().addToRetryQueue(address, packedByteArray);
  }

  // called by multiple threads to populate dataHolderByPartitionReference CHM
  public void add(final int partition, final DataHolder holder) {
    ConcurrentMap<Integer, ConcurrentLinkedQueue<DataHolder>> dataHolderByPartition =
        dataHolderByPartitionReference.get();
    ConcurrentLinkedQueue<DataHolder> dataHolder =
        dataHolderByPartition.get(partition);
    if (dataHolder == null) {
      dataHolder = Queues.newConcurrentLinkedQueue();
      ConcurrentLinkedQueue<DataHolder> currentDataHolder =
          dataHolderByPartition.putIfAbsent(partition, dataHolder);
      if (currentDataHolder != null)
        dataHolder = currentDataHolder;
    }
    dataHolder.add(holder);
  }
}

And below is my RetryTask class:

public class RetryTask {
  private final ScheduledExecutorService executorService = Executors
      .newSingleThreadScheduledExecutor();
  private final AtomicReference<ConcurrentHashMap<Long, byte[]>> retry_bucket =
       new AtomicReference<>(new ConcurrentHashMap<Long, byte[]>());

  private static class Holder {
    private static final RetryTask INSTANCE = new RetryTask();
  }

  public static RetryTask getInstance() {
    return Holder.INSTANCE;
  }

  private RetryTask() {
    executorService.scheduleAtFixedRate(new Runnable() {
      public void run() {
        retryEvents(retry_bucket
            .getAndSet(new ConcurrentHashMap<Long, byte[]>()));
      }
    }, 0, 2, TimeUnit.MINUTES);
  }

  public void addToRetryQueue(final long address, final byte[] encodedRecord) {
    retry_bucket.get().put(address, encodedRecord);
  }

  public void removeFromRetryQueue(final long address) {
    retry_bucket.get().remove(address);
  }

  // retrying the events here
  private void retryEvents(final ConcurrentMap<Long, byte[]> bucket) {
    ZMQObj zmqObj = PoolManager.getInstance().getNextSocket();
    Socket socket = zmqObj.getSocket();

    for (Map.Entry<Long, byte[]> entry : bucket.entrySet()) {
      long address = entry.getKey();
      byte[] serializeEvent = entry.getValue();
      ZMsg msg = new ZMsg();
      msg.add(serializeEvent);
      msg.send(socket);
      msg.destroy();
    }
  }
}

And here is my ResponsePoller class which waits for the acknowledgment for all those records already sent by the other background thread. If acknowledgement is received, then delete it from the retry bucket so that it doesn't get retried.

public class ResponsePoller implements Runnable {
  private static final Random random = new Random();
  private static final int listenerPort = 8084;

  @Override
  public void run() {
    ZContext ctx = new ZContext();
    Socket client = ctx.createSocket(ZMQ.PULL);

    // Set random identity to make tracing easier
    String identity = String.format("%04X-%04X", random.nextInt(), random.nextInt());
    client.setIdentity(identity.getBytes(ZMQ.CHARSET));
    client.bind("tcp://" + TestUtils.getIPAddress() + ":" + listenerPort);

    PollItem[] items = new PollItem[] {new PollItem(client, Poller.POLLIN)};

    while (!Thread.currentThread().isInterrupted()) {
      // Tick once per second, pulling in arriving messages
      for (int centitick = 0; centitick < 100; centitick++) {
        ZMQ.poll(items, 10);
        if (items[0].isReadable()) {
          ZMsg msg = ZMsg.recvMsg(client);
          Iterator<ZFrame> it = msg.iterator();
          while (it.hasNext()) {
            ZFrame frame = it.next();
            try {
              long address = TestUtils.getLocation(frame.getData());
              // remove from retry bucket since we got the acknowledgment for this record
              RetryTask.getInstance().removeFromRetryQueue(address);
            } catch (Exception ex) {
              // log error
            } finally {
              frame.destroy();
            }
          }
          msg.destroy();
        }
      }
    }
    ctx.destroy();
  }
}

Code which sends data to database is only these below lines:

ZMsg msg = new ZMsg();
msg.add(packedByteArray);

ZMQObj zmqObj = PoolManager.getInstance().getNextSocket();
Socket socket = zmqObj.getSocket();
msg.send(socket);
msg.destroy();

Question:

I am trying to see from the design perspective what is the best way to design this problem so that all my logic works seamlessly? I am pretty sure there is a better way to design this problem as compared to what I have?

C++ How to turn a factory pattern into a Policy-based design

I am programming in C++ & new to the design concepts. I've been reading a lot of around how compile time type deduction can improve performance at run time. Also trying get a hold of templates programming which is a difficult part of C++ as I see.

I have the following code which is a Factory pattern.

/*The abstract class*/
Class Vehicle {
  virtual void Drive() = 0;
  virtual void Break() = 0;
  virtual void StartEngine() {
    //some default logic;
  }

  static std::unique_ptr<Vehicle> Factory(enum which_vehicle) {
    switch (which_vehicle) {
    case car:
      std::make_unique<Car>(which_vehicle);
      break;
    case bus:
      std::make_unique<Bus>(which_vehicle);
      break;
    }
  }
}

    --Car.hpp--
/*The derived class Car*/
Class Car : public Vehicle {
  void Drive(){
    //drive car;
  }
  void Brake(){
    //apply car brakes;
  }
  void StartEngine() {
    //Start car engine;
  }
}

    --Bus.hpp--
/*The derived class Bus*/
Class Bus : public Vehicle {
  void Drive(){
    //drive bus;
  }
  void Brake(){
    //apply bus brakes;
  }
  void StartEngine() {
    //Start bus engine;
  }
}

#include "Vehicle.hpp"
main() {
  //Get the required object
  std::unique_ptr<Vehicle> vehicle = Vehicle::Factory(enum::car);
}

As you can see in main method, enum type sent into Vehicle::Factory determines which object I create. Can I achieve the same design with templates based? Or can I make it a policy based design ?

I looked at some related discussions like here & here which looks pretty old style code. hence did not help. I need the exact code since I am new to C++ templates.

How to design a nested polymorphism in OOP?

Let's assume we have a simple payment feature on an online shop. We want to manage different transactions with different processors of transactions:

  • A transaction can be a payment or a refund.
  • A processor of transactions can be Paypal or Payplug.

So we have the following classes:

class PaymentTransaction implements Transaction {

}

class RefundTransaction implements Transaction {

}

class PaypalProcessor implements Processor {

}

class PayplugProcessor implements Processor {

}

What should be a good understanding of OOP?

  1. Processor.process(transaction); or
  2. Transaction.process(processor);

For example, if we take the example 1, how to avoid the following switch statement?

class PaypalProcessor {

    function process(Transaction transaction) {
        switch(transaction.getType()) {
            case payment:
            //..
                break;
            case refund:
            //..
  }
}

In all cases, how to manage a "nested" polymorphism, a strategy or something else to be able to manage the different transactions with the different processors?

PS: if the title is not appropriate, tell me I will edit it.

How to create a common AsyncTask class for webservice call in an android app?

I am trying to write a common webservice class where in any of the activities within my application has to point to this common class for webservice stuff. Currently I got stuck in between i.e; to pass the success/failure message to the calling class, My current implementation is like below, I have an interface class where in I have 2 methods,

 public void webServiceReqExecutedSuccessfully();
 public void webSerReqFailed();

and each webservice calling class implements these methods as per their requirements. And my common webservice class is like below,

    public class WebServiceRequest extends AsyncTask < String, Void, Boolean> 
    {
            
        private static final MediaType FORM_DATA_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
            
            public enum HTTPServiceTags {
            
          POST_IT,
          GET_ALL_ITEMS
         }

         HTTPServiceTags requestTag;
         public ATWebServiceRequest(HTTPServiceTags reqTag, Callable < Void > _ServiceResponseSuccess, Callable < Void > _ServiceResponseFailure) {
          this.requestTag = reqTag;
         }

         @Override
         protected Boolean doInBackground(String...postDataSet) {
          Boolean result = true;
          String requestURL = postDataSet[0];
          String postBody = getPostBody(postDataSet);
          Log.d(requestURL, postBody);
          try {
           OkHttpClient client = new OkHttpClient();
           RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
           Request request = new Request.Builder().url(requestURL).post(body).build();
           Response response = client.newCall(request).execute();
          } catch (IOException exception) {
           result = false;
          }
          return result;
         }

         @Override
         protected void onPostExecute(Boolean result) {
          if (result) {
           switch (requestTag) {
            case POST_IT:
//HOW CAN I NOTIFY/INVOKE webServiceReqExecutedSuccessfully METHOD OF THE CALLING CLASS HERE??? 
             break;
            case GET_ALL_ITEMS:
             break;
            default:
             break;
           }
          }
         }
        }

My question here is after the service call response how can I notify/invoke the calling class interface methods(webServiceReqExecutedSuccessfully() / webSerReqFailed()) from which object reference? Any help is appreciated in advance. Thanks

Call method in foreach with clean code

I'm using DomDocument to access a HTML page and convert into a Object but every time I need to search nodes with some different tag. I want a method with the logic name as parameter, but each logic have different number of parameters.

public function foo(){
    $this->findTag('bar', $parameters);
}
public function findTag($logic, $parameters){
    foreach ($this->dom->getElementsByTagName($this->tag) as $node) {
        $this->$logic($node, $parameters);
    }
}
public function logic1($node, $foo, $bar){
    //something with $foo and $bar
}
public function logic2($node, $fooBar){
    //something with $fooBar
}

This is a bad approach? How can I make this foreach a unique function always called when needed some info from the DomObject, using a different tag.

Design pattern for surrounding code in start, complete and fail methods

Suppose I have various arbitrary sections of code to run, but before each section, I have to run a Start() method and then after each section I need to run a Complete() method. However, if an exception is thrown in the code section, I want to run a Fail(string message) method instead of Complete(). Is there a design pattern that elegantly encapsulates this to make it neat and easily repeatable?

For example, let's say I have a type called Thing that contains a Start() method that adds a row to a logging db table to reflect that a task is in progress, a Complete() method that changes that row to reflect that the task finished and a Fail(string message) method that changes the row to reflect that the task failed. These are just examples though, they could be doing any set-up and tidy up type tasks.

The naive implementation might be simply to call those methods manually:

public void DoStuff()
{
    var thing = new Thing();
    thing.Start();
    try
    {
        DoImportantStuff();
        thing.Complete();
    }
    catch (Exception e)
    {
        thing.Fail(e.Message);
    }
}

But if I'm going to have to repeat this in a lot of different places, it ends up creating quite a lot of duplication and it might be easy to forget to call Complete or mess this up in some subtle way.

In C#, there's the using pattern, which provides a good way of encapsulating most of this. For example, if my Thing type looked like this:

public class Thing : IDisposable
{
    public Thing(){
        Start();
    }

    private void Start() { /* start */ }
    private void Complete() { /* complete */ }

    public void Dispose()
    {
        Complete();
    }
}

My DoStuff() method could now be simplified to this:

public void DoStuff()
{
    using(new Thing())
    {
        DoImportantStuff();
    }
}

Which is much nicer. But it doesn't allow me to call Fail instead of Complete if an exception is thrown because (I think!) the Dispose method is essentially called in a Finally block.

I have thought of having a try/catch inside the using block and then setting a thing.HasFailed flag inside the catch block and then using that in the Dispose method to decide whether to Complete or Fail. But that seems a bit fiddly and I'd like the consumer of Thing to have to do as little as possible to make it work correctly.

So is there a design pattern that encapsulates what I want to do and avoids the need to manually write a try\catch each time?

In which direction to make the association in domain model

Is there some rule of thumb, in which direction to make the association when designing domain model?

For example, we have products in the stock. Stock status of a product is a rather complex data structure, containing enumerations of multiple variations of the product either being in the stock, being out of stock or being bookable. Thus we make a seperate object of the stock status associated with the product. Now the question is, if product object should have a reference to it's stock status, or stock status have a reference to a particular product.

First solution feels like, it's not the real concern of product knowing it's stock state. Product is just a product, and maybe we should manipulate them in different context, where stocking is not a concern. In the other hand, stock status being a root feels awkward, as when thinking about stock, first we think about a product being in the stock.

How to decide, which entity acts as a root for the association?

mardi 24 janvier 2017

Comparing two csv files and outputting matches using Java

I have two csv files

One csv file with one column: user agent strings (10,000 count)

Another csv file with 3 columns: regex pattern, rank, and type (86 count)

I was told to create a program that would test all the user agent strings with the regex patterns and have a file that outputted two columns:

User Agents and their type based on the tests.

Is there any way to do this? I've been working at this for a week with no solution in sight.

Modular promises and Promise.all()

I have a bunch of functions that return promises that I want to make generalized, and so I write them like this:

function prf1(data){
    var promise = new Promise(function(resolve,reject){
        //some stuff here
        data.new_variable1 = 1;
        resolve(data);
    });
    return promise;
)};

function prf2(data){
    var promise = new Promise(function(resolve,reject){
        //some stuff here involving data.new_variable1 or something else
        data.new_variable2 = 2;
        resolve(data);
    });
    return promise;
)};

function prf3(data){
    var promise = new Promise(function(resolve,reject){
        //some stuff here involving data.new_variable2 or data.new_variable1 or something else
        data.new_variable3 = 3;
        resolve(data);
    });
    return promise;
)};

I resolve data in each function because I plan to have a lot of these types of functions, and I don't know the order they'll be called in while chaining:

prf1(somedata)
.then(prf3)
.then(prf5)
.then(prf2)
//etc

This works fine until I have to do Promise.all:

 Promise.all([
    prf1(somedata),
    prf2(somedata)
 ])
.then(prf3)
//etc

This gives me errors, because the new promise returned by Promise.all() is an object that contains both resolutions from prf1 and prf2. Essentially, in prf3, I can't access data.new_variable1 or data.new_variable2 because the resulting promise is [somedata, somedata].

Is there a pattern I can follow to help me achieve what I need to do? I need to make the promises modular providing them with as much data as possible.

Adding and abstract subclass in PHP without modifying all the inheriting children classes

I have a similar class hierarchy

interface ISomething
{
    public function foo();
    ...
}

abstract class TopAbstract implements ISomething
{
    ...
}

abstract class HighAbstract extends TopAbstract 
{
    public function foo()
    {
        ...
    }
}

and 46(!) classes that inherit from HighAbstract 

class One extends HighAbstract
{
}

...

class FortySix extends HighAbstract
{
}

Now I have to add functionnality and that requires having an alternate HighAbstract::foo() (amongst other things). What would be the best way to achieve that?

  • I could just modify HighAbstract but I'd like to keep that new functionality separate (separation of concern)

  • I could add a subclass to HighAbstract but then I would have to edit the 46 subclasses to change their parent.

  • I could add a trait to HighAbstract but that still implies modifying it (HighAbstract) with branching and using the trait in HighAbstract::foo()

  • Any other ideas?

I think using the trait with minimal edits in HighAbstract may be the least bad solution, that way the code is somewhat separated and if the new functionality is ever dropped, it could be done with minimal changes.

What do you think?

Thanks