samedi 30 avril 2016

Rake tasks sequentially calling multiple class methods - Rails 4, Design

I have a rake task called pull_orders which calls methods of a RemoteDbConnector class to do things like establish a connection to an external db, generate raw SQL queries, execute queries and store records in local db.

While trying to test it, I stumbled upon this answer which got me thinking whether my design is flawed.

Should rake tasks really be one liners? If so, where should put all these method calls, given that they need to be called in a particular sequence?

My task looks like this:

namespace :db do
  desc 'finds and populates data from remote db'
  task pull_orders: :environment do
    ...
    columns = ...
    table = ...
    options = ...
    column_mappings = ...
    RemoteDbConnector.generate_query(...)
    RemoteDbConnector.execute_query(...)
    RemoteDbConnector.map_column_names(...)
    Order.create(...) #creates records based on hash generated by RemoteDbConnector
    ...

  end
end

String Compress

I am doing a data analysis in which I have the event sequence as string. EventA - Event B - Event B - Event B - Event C - Event A. I want to find the pattern as Event A - Event -B -Event A.

It becomes complex when the data is Event A - Event B - Event C - Event B - Event C - Event D needs to reported as Event A - Event B - Event C - Event D.

Could you help me solving this.

"Invisible" content is floating and repeat behave weird

right now i'm sitting on my very first website and encounter my first major problem which i don't know how to solve.

My problem is that the content is scrolling way more to the left then it should and when i zoom out the "Zig zag" pattern behave weirdly but i'm not sure why.

I have here a jsfiddle link:

http://ift.tt/1pTxelg

<!DOCTYPE HTML>
<body>
    <div id="header">
        <div id="contenth">
            <div id="logo">
                <a href="index.html"><img src="http://ift.tt/1NbXov3" alt="logo" width="256px" height="100px"/></a>
            </div>
            <div id="sm">
                <a class="sm1a" href="http://google.de/rss" target="blank"><img class="smh1" src="http://ift.tt/1pTxeli" alt="RSS"></a>
                <a href="https://twitter.com/Katja_Krasavice" target="blank"><img class="smh2" src="http://ift.tt/1NbXmDn" alt="Twitter"></a>
                <a href="http://ift.tt/g8FRpY" target="blank"><img class="smh3" src="http://ift.tt/1pTxbWx" alt="facebook"></a>


            </div>
            <div id="suchfeld">
                <form>
                    <label>
                        <input id="suche" name"Suchbegriff" placeholder="Search..."/>
                    </label>
                </form>
            </div>
            <div id="shadow">
                <img src="http://ift.tt/1NbXmDp" alt="schatten"/>
            </div>
            <nav>
                    <a href="#"><img src="http://ift.tt/1pTxelk" alt="home"/></a>
                    <a href="#"><img src="http://ift.tt/1NbXmDs" alt="referenzen"/></a>
                    <a href="#"><img src="http://ift.tt/1pTxelm" alt="kontakt"/></a>
                    <a href="#"><img src="http://ift.tt/1NbXpyQ" alt="Über mich"/></a>
            </nav>
            </div>
        <div id="zig">

        </div>

        <div id="content">

        </div>
    </div>
</body>

i can't post CS

java concurrency - singleton design with a monitor thread

I have a singleton class thus

public final class HandlerCache {
    //the cache maintains a handler per thread 
    private final Map<Thread, Handler> cache = new ConcurrentHashMap<>();

    private final Thread monitor;

    private static final HandlerCache INSTANCE = new HandlerCache();

    private HandlerCache() {
        monitor = new Thread() {
        //periodically monitor cache and close handlers when a thread has died
        }
        monitor.start()
    }

    public static HandlerCache getInstance() {
        return INSTANCE;
    }

    public Handler getHandler() throws Exception {
        final Thread thread = Thread.currentThread();
        Handler handler = cache.get(thread);

        if (!(handler == null))
            return handler;

        handler = HandlerFactory.get(getHandlerFromName(thread.getName()));
        cache.put(thread, handler);
        return handler;
    }

}

I am leaking the singleton instance to the monitor thread before the constructor is finished, what is the better way ?

Will making cache volatile will fix the issue ?

which method should be synchronized in delegation pattern in Java

In delegation pattern, if I have a concrete class and a wrapper class:

class Wrapper {
    Concrete concrete = new Concrete();
    void fn() {
        concrete.fn();
    }
}

class Concrete {
    void fn() {
        ...
    }
}

If the method fn() should be synchronized, then where should I put the synchronized keyword? If we assume Concrete::fn() will only be called by Wrapper::fn(), is it true that either place is fine?

Thanks!

Validation Design Pattern in PHP's Laravel (Ruby on Rails)

I have serious problem with choosing validation design pattern form my mid-large level project. I know two that they are quite nice, but I don't feel about which to choose:

1 Validation inside model.

In L4.2 there was a bundle named: Ardent. He has few nice solutions. One of then was validation handle on before saving event. It was wery helpful especially for smaller project. Minus was that that validation logic was kept directly in model.

2 Validation from service,

Another good practice that I know i validation from service. It means that we create servic for models that is responsible for write acions (mainly also for some of the reads). We can mange here validating on before any save (create, update etc.). In my opinion is better then my first propositon. The minus is - we have to remeber to put all model's input data through the service. Otherwise we won't get validation and other things directly from service.

Which of these two? Or maybe someone have something better, more clever? :)

Repeat Pattern to 100% of the viewport

in CSS i made that code:

   body {
    background-color:#f3f3f3;
    max-width:1920px;
    min-width:1024px;
    margin:0 auto;

but to seperate the header from the content i would like to have a "bar" between them.

so i made:

#zig {
max-width:100%;
background-image:url(../img/zig.png);
background-repeat:repeat-x;
height:25px;

but the Bar doesn't go "unlimited" it just repeat till it reaches "1920px" can i somehow change that? to put

min-width:100%

didn't work

Distant work for designer


I have django project with some additional libs (like geo and etc.) on my pc, and git. And I've a friend, who don't know nothing about programming and development.
And my question is: How can she make design for my project on distant?
She will be a distant designer, and I don't know how to manage her work.

Switcher implementation in Javascript

I am working on a mid-size application in Javascript. I would like to create a switcher, similar to the OS window switcher. When a UI part becomes active, it should mute all event listeners from other UI parts and give the active UI an exclusive access to the keyboard and mouse input. For example ctrl+c on an active panel would copy panel data, while ctrl+c on an active canvas would copy a selected shape. Both panel and canvas are contained within a single view.

One way to implement it is to utilize observer pattern giving one observer an exclusive access to mute other observers (the switcher), this would prevent unwanted observers from interfering with the keyboard and mouse input.

This is however an experimental solution, what are the current ways to implement this functionality?

Which S.O.L.I.D. principles do design patterns implement?

I'm trying to connect each SOLID principle to design patterns. In this moment I have:

  • Singleton: None
  • Observer: SOID
  • Strategy: SOLID

And left me:

Builder, Factory, Abstract Factory, Prototype, Adapter, Composite, Decorator, Facade, Flyweight, Proxy, Command, Memento, Chain of Responsibility, Bridge, Filter, Interpreter, Mediator.

Does someone know what SOLID principles are implemented in those design patterns?

How to design a ViewController with complex TableView

Imagine this scenario:

  • I've 10 different and custom UITableViewCell: one with a textfield, one with a button, one with some labels, one with a textview, one with an imageView and so on.
  • I've a ViewController with a tableView where I wanna display these cells.
  • The number of cell displayed can vary based on some conditions (and also the height, the background color and other parameters)
  • The user can interact with these cells


What is the best way to design this in respect of the MVC and maintain the ViewController lightweight and maintainable as possible?
How to take advantage of Swift language in doing this?
Is there any famous and consolidate design pattern to apply?

Java regex pattern not working as intended

I am new to patterns and regex and have encountered a problem which I can't solve. This is my code:

public static void main(String[] args) {

    Pattern pattern = Pattern.compile("(!?)(fw|ri|le|cl|rs)[\\s,]*(\\d*\\.*\\d*|\"\\w*\")?[\\s,]*(\\d*\\.*\\d*|\"\\w*\")?[\\s,]*(\\d*\\.*\\d*|\"\\w*\")?");
    Matcher matcher = pattern.matcher("!fw 90.0 \"hello\" 70.0");

    matcher.find();
    for(int i = 0; i < matcher.groupCount()+1; i++) {
        System.out.println("Group "+i+") " + matcher.group(i));
    }
}

So, i've used regexr.com to create the regex, and on the website it works as planned. It should find 3 arguments which can be either a number or a String, where the String is enclosed in quotation mark. As I said, on regexr.com it works, however in java it does only, when there are no Strings. What am I doing wrong? (The regex without the extra backslashes is (!?)(fw|ri|le|cl|rs)[\s,]*(\d*\.*\d*|"\w*")?[\s,]*(\d*\.*\d*|"\w*")?[\s,]*(\d*\.*\d*|"\w*")? )

Thanks in advance.

Edit: Some examples of what does happen and what doesn't:

Working as intended:

Input: !fw 1.0 2.0 3.0

Ouput: Group 0) !fw 1.0 2.0 3.0 Group 1) ! Group 2) fw Group 3) 1.0 Group 4) 2.0 Group 5) 3.0

Not working as intended:

Input: !fw 1.0 \"hello\" 3.0

Output: Group 0) !fw 1.0 Group 1) ! Group 2) fw Group 3) 1.0 Group 4) Group 5)

Intended Output: Group 0) !fw 1.0 "hello" 3.0 Group 1) ! Group 2) fw Group 3) 1.0 Group 4) "hello" Group 5) 3.0

Eventually load member variable value in a non blocking thread safe manner

I have a class that has a getter method (among others):

public class Employee {  

  public EmployeeAccount getAccount() {  
     return this.empAccount;  
  }  
}  

The problem is that the empAccount is initialized by an async call which might return null but eventually would return the actual account.
The reason is that the async call method depends on many things and sometimes might return null as it is not ready to give the account yet. Please note that I have no control over this API.
So I was thinking of doing something like:

public class Employee {  
   public EmployeeAccount getAccount() {  
      if(this.empAccount != null) {   
         retrieveAccount(); 
      }
       return this.empAccount; 
   }
   private void retrieveAccount() {  
      Thread t = new Thread(new Runnable() {  
          @Override   
          public void run() {  
             this.empAccount = getAccountFromRemoteSystem(); // <--- this is a blocking call   
          }  
      };  
     t.start();  
}  

The reason I was aiming towards this is because getAccount() is expected to be non-blocking as it is called from a UI thread.
How can I design/structure my code so that it is thread safe? Are there better constructs I can use or some other design pattern?

C pattern does any one know logic of this program asked to me in interview

if n=4 then o/p is 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7

if n=5

1 2 3 4 5 16 17 18 19 6 15 24 25 20 7 14 23 22 21 8 13 12 11 10 9

there is no space between numbers (just for clarification i had taken).

vendredi 29 avril 2016

How to use fields from an object after an exception is thrown and the object can't be fully created

The issue that I have is that I need information from an object that a method returns when it throws an exception. It is a little hard to describe so I have this java pseudo code example. I have a solution, but I don't like it (problems listed below), and was wondering if there was a better one:

public class OuterClass {

  InnerClass innerClass = new InnerClass();

  public void doOuterClass() {
    try {
      // class Container is a POJO with Strings s1, s2, and s3
      Container container = innerClass.createContainer();

      // more processing on the container that takes arg container
    } catch (Exception e) {
      // *Issue is here*: If s2 was calculated, it implies that an RPC was made,
      // which changed the state of a certain server. I need make a call using s1
      // to revert the state of that server. FYI, it is not easy to recalculate s1.
    }
  }
}

public class InnerClass {

  InnerInnerClass innerInnerClass = new InnerInnerClass();

  public Container createContainer() throws Exception {
    Container container = innerInnerClass.createContainer();

    // complex calls to various services that might throw Exception
    ...

    return container;
  }
}

public class InnerInnerClass {

  public Container createContainer() throws Exception {
    // complex calls to various services that might throw Exception
    String s1 = ...;

    // complex calls to various services that might throw Exception
    String s2 = ...;

    // complex calls to various services that might throw Exception
    String s3 = ...;

    return new Container(s1, s2, s3);
  }
}

What I tried to do is add Exception as a field in Container and made it mutable. As s1, s2, and s3 are calculated, it sets the values in the Container. There are a few problems with this though (non-exhaustive list):

  1. I have to surround each create method with a big try catch and set the exception on the Container when an exception is thrown. This makes it tricky for others adding new code.
  2. Container is now mutable.
  3. Container fields are marked as @Nullable, which means all code after innerClass.createContainer() should technically check for null since the object could technically be partially constructed. (however, if there is no exception we can assume that all items are not null, but this is again an assumption that has to be remembered.
  4. There are actually more exceptions thrown than just Exception, so to handle them I either have to rethrow the exception after innerClass.createContainer(), or use instanceof on the Exception, which is ugly.

In summary the solution that I tried is not maintainable and hard to follow. What do you think? Is there a better solution?

pattern for objects with and without context

I'm working on a system that is composed generically of questions and answers. Users of the system can use the ideas of questions and answers to design questionnaires.

When authoring questionnaires there is one type of question. Once a question is created, different types of answers can be added to it. For example, boolean answers, text answers, etc..

When executing & displaying questionnaires, the types of answers that have been added to the question are relevant in the context of the question when displaying it. So when drawing a question on the screen, I need to know what kind of answers it has, to know how to mark it up/draw it on the screen.

So there is tension between the domain ideas when considering them in either context.

The type of questions are in some ways defined by the types of answers, but I'm also not sure it's right to have multiple types of questions, one for each possible type of answer combination during authoring.

That being said, I don't feel like it's right to have to inspect the children of (answers within) the question - each time I need to figure out how to display it.

I'm confident that this kind of problem can be addressed with existing patterns, and that I just don't have the language to articulate it.

If anyone can help me re-frame this with a pattern I'd appreciate it.

What javascript design pattern or patterns should I use?

I'm a beginner developer and I am developing medium-large web application, at least to my level, using Yii2 and lot of javascript.

Initially started writting namespace on separate file like:

var NAMESPACE = NAMESPACE || {};

NAMESPACE.components = {
   menu: {
          ...
   },
   forms: {
           .....,
           .....
   }
};

NAMESPACE.prototype = {
    environment: {
       function1: function(){
       },
       function2: .....
    },
    user: {
       function1: function(){
       },
       function2: .....
    },
    actions: {
       function1: function(){
       },
       function2: .....
    }
};

I too have main script file where I created multiple pointers to different parts of the namespace with which I access the components and I make calls to functions. Everything works correctly but the size of the namespace (which already exceeds the 3000 lines) begins to have a tedious growth.

I have read a lot about javascript pattern as modules, prototypes, observers and singletons , but I'm really confused about how I should restructure my code , the type of pattern or patterns that should use.

I wish someone could guide me on this and give me some practical advice. Sorry my poor English. Thanks in advance.

A greeting.

is this a new javascript factory pattern?

Fair warning - a long time ago I wrote a lot of C++ and can't help the temptation to coerce javascript into design patterns I was familiar with back then. It's ok to accuse me of atavism in any replies ;-)

In my current project, I want to create objects by name, which indicates the factory pattern. So I read the top page of google hits for 'javascript factory pattern'. They all have this ugly thing in common:

if (name === 'FactoryPartA') {
    parentClass = PartA;
} else if (name === 'FactoryPartB') {
    parentClass = PartB;
} else if ...
    parentClass = PartZ;
}

return new parentClass();

Which has 2 problems:

  1. Every time I create a new part for the factory to make, I have to edit the factory's implementation and I'd prefer to avoid both the work & the bug-insertion opportunity.
  2. It's a hard-coded, linear search which hardly screams "efficiency!"

So here's what I came up with - a combination of the module and factory patterns with the info hiding merits of the module pattern provided by the tactic of defining the classes of factory parts inside the factory's register closure.

Finally getting to my question: I can't believe that this hasn't been done before by better coders than me so please share a link to the canonical version of this twist on the factory pattern if you know of one.

N.B. For this example I've run all my code together. In my project the factory, FactoryPartA, FactoryPartB, and client code are all in separate files.

namespace('mynamespace');

// object factory
mynamespace.factory = (function () {
    'use strict';
    var api = {};
    var registry = [];

    // register an item
    api.register = function (item) {
        if (registry.some (function (r) {return r.name === item.name;})) { 
            throw new Error ('factory.register(): name collision detected: ' + name);
        } else {
            registry.push(item);
        }
    };

    // make an item given its name
    api.make = function (name) {
        var item = null;
        var idx = registry.findIndex (function (r) {
            return r.name === name;
        });
        if (idx >= 0) {
            item = new registry[idx].make();
        }
        return item;
    };

    return api;

})();


// define a module & register it with factory
mynamespace.factory.register ({
    name: 'FactoryPartA',
    make: function FactoryPartA () {
        'use strict';
        var label = 'Factory Part A';   // private property

        this.test = undefined;  // public property

        this.label = function () {   // public method
            return label;
        };

        return this;
    }
});

// define a different module & register it with factory
mynamespace.factory.register ({
    name: 'FactoryPartB',
    make: function FactoryPartB () {
        'use strict';
        var label = 'Factory Part B';

        this.test = undefined;

        this.label = function () {
            return label;
        };

        return this;
    }
});

// client code
var aPart = mynamespace.factory.make('FactoryPartA');
var bPart = mynamespace.factory.make('FactoryPartB');

console.log (aPart.label()); // logs 'Factory Part A'
console.log (bPart.label()); // logs 'Factory Part B'

var anotherPart = mynamespace.factory.make('FactoryPartA');
aPart.test = 'this one is not';
anotherPart.test = 'the same as this one';
console.log (aPart.test !== anotherPart.test); // logs true

Interface inheritance hierarchy

As part of code refactoring I have found some code duplicates I'm trying to remove

I have an interface like so , in an assembly I cannot modify.

public interface IArtifact
{
    void Accept(IArtifactVisitor visitor);
}

public  interface IArtifactVisitor
{
      void Visit(Topic topic);
}

In the refrences assembly , which I want to reuse existing interfaces as you can see there is the same function signature

    public interface IArtifact
    {
        void Accept(IArtifactVisitor visitor);
    }


   public  interface IArtifactVisitor
    {
          void Visit(Topic topic);
          void Visit(NewTopic topic);
    }

and the Accept looks something like this

public void Accept(IArtifactVisitor visitor)
{
    visitor.Visit(this);
 }

in order to removed the code reuse , I have tried the following

public interface MyIArtifact : IArtifact
    {
        void Accept(MyIArtifactVisitor visitor);
    }

    public interface MyIArtifactVisitor : IArtifactVisitor
    {
        void Visit(NewTopic topic);
    }

but what this does , it forces me in each implementation class to implement both Accept(MyIArtifactVisitor visitor) and Accept(IArtifactVisitor visitor)

is there a better way to do this ?

Is there a name for this reflective design pattern in python?

This is kind of an odd question. I have written a few classes that use reflection to find methods to execute on a given object.

For example, I have a class that calls methods based on the type of data it encounters. The methods are user-defined, but it's just a nicer interface for making these kinds of modifications(turning all of one type into another etc).

Here is what the class looks like:

class TypeWare(object):
    def modify(self, data_set):
        """ Iterate over data_set, find child class methods and execute them on the appropriate data type. """
        types = [str, float, int, tuple, dict, list]
        data_output = []
        for data in data_set:
            data_type = type(data)
            if data_type in types:
                try:
                    # Try to find the method by name.
                    method = getattr(self, data_type.__name__)
                    # Make modifications to data and add it to the output
                    data_output.append(method(data))
                except AttributeError:
                    data_output.append(data)
            else:
                data_output.append(data)
        return data_output

So any other class could just inherit this, and so long as it has methods named after the type of data it should modify, that method would be called on that data type and the returned value would replace the original value.

Here is a simple example of what that would look like if my explanation is confusing:

class ExampleTypeWare(TypeWare):
    # Square any integers
    def int(self, value):
        return value * value

    # Operate recursively on lists.
    def list(self, the_list):
        return self.modify(the_list)

# Then the instance calls the modify method from the parent class.
tw = ExampleTypeWare()
print tw.modify([2, 4, 6, 8, [10, 12, 14]])

I guess my question is, is there a name for classes that enable this type of behavior? It seems pretty specific, and I have used this pattern a couple times before so I had a clean interface for filtering or modifying data. I just don't know how to explain the concept to anybody without going into full blown detail which might be unnecessary if there is a name for this design pattern.

To reiterate, the pattern in question is basically just using reflection within a main class method to seek out methods that exist in the child class in order to dynamically call those methods on the given data, based on a specific context.

C++ design pattern for an item with multiple representations

I have an "item" whose data can be represented 3 ways. I can convert from one representation to any of the others, at a runtime cost. Once I do the conversion I'd like to keep the new representation around. Any representation of the data can be converted to any of the others without "modifying" the core data. Because of the runtime cost, I want a class that contains 3 representations of the data. At any time, 1 to 3 of them will be valid.

The real point of this is because it also has access methods, where the user can ask for something. This something can be gotten from 1 or possibly more of the representations. For example, you could get the "range" from representation1 and the "volume" from representations 2 or 3.

My solution was to create class with the 3 representations as member data (and a way to know if they are valid). Then I created a getRange() method that internally knows which representation it needs and creates that if necessary. This works fine and solves all my issues except that the get method cannot be const.

So the real issue with this solution is that even a "constant" instance of this class is not really const because it internally might create other representations. However it really is "constant" because changing representations does not modify the core data.

Is there a C++ design pattern that might help with this class? Any suggestions?

Class design for loading data from HTML page

I need to make integration with ancient ERP system that doesn't provide any kind of API. The only way to programmatically access its data is parsing the system's backend (thankfully it's web) via Http Post/Get.

The design of my classes looks as follows (C#):

// Represents product in ERP.
public class Product 
{
    public int ID {get;set;}
    public string Name {get;set;}
    public double {get;set;}
}

// Provides CRUD and Get operations on Product.
public class HttpRepository : IRepository 
{
    public Product Get(int id) {
        var html = WebClient.HttpGet("http://ift.tt/1Wv7BnV"+ id);
        return Parser.ParseHtmlAndGetProduct(html);
    }
}

// Parses html pages and returns useful data out of those.
public class Parser 
{
    public static Product ParseHtmlAndGetProduct(string html) {
        var p = new Product();

        // use Regex for getting product properties
        p.ID = GetProductID(html);
        p.Title = GetTitle(html);
        p.Price = GetPrice(html);

       return p;
    }
}

Is that correct design?

I feel like the Parser shouldn't create and return Product class since Repository is the only place responsible for producing products. With the other hand Repository cannot do parsing directly since it takes too much responsibility and violates SOLID.

So what would be correct class design for this scenario?

Clean use of design patterns in Unity

My students have learned OOP as well as the strategy design pattern during the first semester (Processing/Java), which lead to understanding Unity's component based architecture (similarity of strategy and component pattern).

In the second semester they dive deeper into Unity programming, while applying OOP patterns like the Observer Pattern to keep the code clean and independent. The example I have for them is a box-shaped trigger zone that opens a simple door when an actor enters, and closes the door when he exits. So far so good. But what if we want to open several doors -> observer pattern.

So in the first run we create a nice generic trigger script (our "Subject" in the sense of the observer pattern) that notifies observers of enter and exit events (within Monobehaviour's OnTriggerEnter() and OnTriggerExit()). This doesn't know much about the observers getting notified except that they implement e.g. an interface IDoorBehavior with open/close methods. We implement this once using the built-in UnityEvent mechanism and once using C# delegates/events and discuss pros and cons.

In the Start() function of the trigger script, we gather all objects that derive from an abstract class Openable : Monobehaviour using FindObjectsOfType() (can't use plain interfaces here because Unity demands this method be called with a type derived from Monobehaviour). Then for each of these Openable objects found we add the Open/Close methods to the event/delegate list to be notified.

So here we have the (I feel unusual) issue that the subject searches his observers an forces them to observe them. "You better observe me, or else...". Shouldn't the observers do this?

What if we foresee that in the future there will be different types of doors that can be opened by specific triggers/actions. How to design that in a flexible and clean fashion?

I plan to use the strategy pattern (known to the students) in order to have different open/close behaviors for doors (slide up/down, hinges, etc.).

Later I also want to create a classic pick-up-the-object-and-put-it-to-inventory example in a clean patterny way, so we have a neat sandbox with exemplary scripting design for the students to learn, extend, and design their own games.

So overall I'm looking for insightful comments from experienced OOP/pattern cowboys that might help improve the design and just "get it right" (I know there is not one "right" solution to these problems).

Register node module in design time and read data in run-time

Im implementing a node application that have app.js and server.js (using express) . To run my application you should run the server.js which start to listen to http calls. so far so good :).

There is a new requirements like following:

  1. Register new module to the application during design time like adding new module to it

  2. in Runtime find which modules are register and do my logic on them(the logic is not the point here)

I think its like command design pattern that external module can register to your module and you don't know about them until the need to run

How I can do it in node.js? There is a npm module which allow module registration which I can use as reference ?

I'm not talking about adding a module as node dependency(on package.json), I'm referring that developer will add/register his module to my module by code and in runtime I will know that userModule was register and do additional logic.

require my module myModule.register('userModule');

or register with path to the userModule

myModule.register('/path to user module');

jeudi 28 avril 2016

Large Scale App - Choosing the right database, and serving data from it

I have been doing a lot of research recently non-stop. I know this is a vague question, but I will try be as specific as I can. I have been developing small to medium web systems for a while, but never dealt with noSQL databases, or made something with this scale. The purpose of the question is to make the right decision, as I don't want to shoot myself in the foot. And hopefully it can help someone else like me, new to this and a specific example can clarify more things in my opinion.

To make this easier, I will give an example very close to what I'm trying to achieve, which is very simple and covers a lot of similar systems out there. Hopefully by this example I will clear out the type of data I'm dealing with, the kind of system, and operations that need to be performed.

Example System Overview

1) System Overview: Let's say we are dealing with a multi-tenant system, that allows users to track traffic to specific pages on their sites. The user/customer needs to plant a code of my system into their page, and this code, will call a service on my server that simply stores the data in the database. The data is simply the page visitor's data, stuff like the page they visited, browser, device, time of visit..etc. Here, the data is STORED

2) The users/customers can login to the system, and view their data. Here the data is SERVED

3) In addition to storing, and serving data, there's another service in the system, which will be processing this data. And finding patterns/conclusions about the site visitors. For example, specific page, is more visited via mobile devices.. (and do whatever with this conclusion). Here the data is PROCESSED

4) We are talking about Large volumes of data. Probably starts with 3-4 Million writes per day (visits), and I want to be sure it can scale up to Billion+

Question 1:

Now, I have been cracking my head over Google Cloud Solutions. I thought that it's best to go with App Engine, since I can't afford to maintain a virtual server. I decided to go with the DataStore and here comes my question:

1) Is DataStore the most appropriate solution for this case?

According to my research, I found that datastore is most appropriate, but of course I'm not 100% confident due to my lack of experience. But I chose this because I come from using SQL a lot. I didn't go for Cloud SQL, because my data is not that relational, and due to the volume and the need of reliability and scalability of my system, I thought a NoSQL solution would be better. Datastore has GQL syntax, which is similar to SQL querying language. Properties of objects are also indexed. I will probably need to read/filter data by Device type for example. I also saw that BigTable is very different (probably not used to it), and all data you have is Key:Value, where I think it's not possible/hard to query by specific property for example?

Eventhough I don't believe my data is really structured. Specially that I will be using Namespaces for users/customers (multi-tenant), and it's automatically included in the key. The entities I have at the moment is User (will probably include few entities under it), and Visit as a "standalone" entity.

Question 2

What's the best practice for serving data to customers?

I don't want to show customers Millions of visits. I would give them overall stats. For example how many visits via Android Mobile Devices. Or stats within Time-Range. So I believe there are 2 approaches. First, make separate database. Or maybe separate entity within the same DataStore, that holds total daily stats per customer. And then make serving by adding up "days stats" which doesn't feel right. Second, Every time I want to serve data, I make a query to the one big database. But also the second approach doesn't feel right. Because as I know, Datastore doesn't have "Group by" functionality for example, or aggregates. So every time, a customer wants to see stats "by device" I need to make the "group by" functionality by code on memory? or if I just want to display the "count" of specific filter query result, which is not directly supported with datastore I believe? Also making these calculations in real time when serving the data sounds like a lot.

Now I know there's a solution called BigQuery by Google, which I believe does what I want and allows me to serve the data I want to customers with high flexibility and efficiency, but as I understood it works only on datastore "backups", I need to serve data in real time.


I appreciate a lot anyone taking the time to give any input on the matter. Thank you very much in advance.

Handling many different types of roles and data retrieval

Just to note, I'm using Laravel on the backend. Let's say you had 10 different user levels in an task management system. All these user levels have different access to the tasks themselves, as well as the actual attributes for each task. For example, a super admin might be able to see all the tasks, and a manager too. But the manager only sees a certain subset of attributes for those tasks. On the flip side, a regular would only see their own tasks, and a different subset of the attributes too.

What kind of design pattern or method would you use to handle something like this? It's different for each of the user levels, and I'm trying to avoid having to add switch statements everywhere. For simple things, it's totally fine. But when it's everywhere, it seems like a code smell.

That's basically what I'm trying to find a good solution for. There's something else where I'm returning an array to the view, but the array would be populated with different sets of information depending on the user level. I'm trying to limit the sent data, even if it doesn't show up, because I'm using Angular on the front. So it's pretty simple to check the response for that data.

How can I determine first call to WCF singleton service?

I'm writing a simple Windows WCF service as a singleton using the recommended InstanceContextMode.Single service behavior, e.g.:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]

My code looks like below. The question is, how can I tell from within my constructor (or otherwise) that the very first call to my service has been made? That is, when the singleton has been instantiated for the first (and only) time?

enter image description here

I need to do some special processing on the first call to the service and the constructor seems like the logical place to do this. However, I've tried placing some simple code in the constructor and can't even hit a breakpoint there (using remote debugging). It's like the constructor is never actually called if I go with the InstanceContextMode.Single route (as opposed to the old classic method of having a static class and a static reference to an object, checking a reference to that object in the constructor to see if it's null, etc.) And, I wouldn't know what to check in the constructor even if I could place functional code there.

Have I lost the ability to check for my first call by going the InstanceContextMode.Single route?

Transaction Script and Unit of Work

We have a C# solution in which we applied the Transaction Script pattern; its layers are the following:

  • Adapter: access point to the aplication (consumed by MVC Controllers and API Controllers); allways calls exactly one method from Logic layer;
  • Logic: methods with business logic; inside each method we could have several calls to other logic/repository methods;
  • Data Access: methods with calls to NHibernate and/or NPGSQL (for expensive operations requiring stored procedures)

Now, we want to implement the Unit of Work pattern using TransactionScope to use one and only one transaction per request (i.e.: one transaction per call to methods from Adapter, since we use UoW at Adapter level), but we can't figure out how to manage the connections, since we could have connections for NHibernate and/or NPGSQL inside the same method.

Regards

What design pattern to use for generating multiple simulations?

I have a simulation that runs at a specific height and a specific temperature:

interface ISimulation
{
    string Name { get; }
    int Height { get; }
    int Temperature { get; }
    void Generate();
}

The Generate() process for a simulation typically involves multiple steps:

void Generate()
{
    GenerateStep1();
    GenerateStep2();
    GenerateStep3();
}

Now, it is possible for the user to specify multiple heights and/or multiple temperatures.

In this case, multiple simulations (sub-simulations) are spawned off, one per each height/temperatue combination.

interface IMultiSimulation
{
    string Name { get; }
    int[] Heights { get; }
    int[] Temperatures { get; }
    void Generate();
}

In this case however, the Generate() of the sub-simulation would have to change as follows:

  • If multiple temperatures are specified, then GenerateStep2() needs to be performed only once for all sub-simulations, and not per temperature.
  • If multiple heights are specified, then:
    • GenerateStep1() is performed first on all sub-simulations.
    • Step2 and Step3 are then performed.
  • It is possible to have a grand simulation with multiple heights AND multiple temperatures. This means that 2 above criteria need to be satisfied.

I've been trying to use the decorator pattern but with no success. What are some tips I could use to handle the complexity of my code?

Thanks.

Ireport/Jaspersoft Designer 'dynamic' patterns

I need to create a "dynamic" set of patterns for a double type field. For instance, if the number is 20.10 then pattern is #,##.00 and if the number is 200.10 the pattern will be #,###.00 and if the number is 2000.10 its used the pattern #,####.00

I need this because I'll have an xml with diferent values for the same field but I need a pattern for them all. Is this possible in ireport or the pattern is unique? This will be made in iReport Designer 4.1.2 Thanks

Assign values from string to attributes using patterns

I have strings like this (e.g.):

property1=[43.55;343.44]   -> String=[double;double]
property2>=45.3   ->String >= double

How can I get this values to attributes, when I define appriopriate patterns. I want to use this, inside other string e.g "any string propertie1=[43.55;343.44] any string properties2>=45.3 any string " and as result I want to assign values which match pattern to attributes:

String s=property1 
double a=43.55
double b=343.44

etc.

Register a node module during design time

Im implementing a node application that have app.js and server.js (using express) . To run my application you should run the server.js which start to listen to http calls. so far so good :).

There is a new requirement like following:

  1. Register new module to the application during design time like adding new module to it

  2. in Runtime find which modules are register and do my logic on them

I think its like command design pattern that external module can register to your module and you don't know about them until the need to run

How I can do it in node.js? There is a npm module which allow module registration which I can use as reference ?

I'm not talking about adding a module as node dependency(on package.json), I'm referring that developer will add/register his module to my module by code and in runtime I will know that userModule was register and do additional logic.

Shared JavaScript File with Different Definitions of a Function Call

I have a 300 line javascript file that sets up jQuery event handlers and other needed functions for a partial view that's used by multiple views within a ASP.NET MVC application. The event handlers handle 99% of everything identically regardless of which view is using the partial. This question is about that 1% difference.

Since JavaScript doesn't have interfaces is it safe to define a function to be called by one or more of the event handlers that processes the things that are different in a separate file that is loaded depending on which view is used? If not, what would be the best way to handle this situation? In other languages I'd use interfaces and/or abstract classes in this situation.

Example:

shared file

$(document).ready(function() {
    //shared variables here for methods
    $(document).on('click', '.selectable-table tbody tr', function() {
        //do shared actions
        mySpecificFunction();
        //finish shared actions (if necessary)
    });
});

Definition1.js

function mySpecificFunction() {
   //do stuff
}

Definition2.js

function mySpecificFunction() {
   //do other stuff
}

The views would load the appropriate scripts as such:

<script src="definitionX.js"</script>
<script src="sharedScript.js"></script>

The "signature" (term being used generously because javascript) of mySpecificFunction() would be the same for each definition, but something in my gut is telling me that this is bad practice. Is there a better/correct way to do this or a design pattern for this purpose?

PHP reuse a function in across MVC

My MVC could be described this way:

  • application.php will handle all routing to call controllers accordingly to the requests
  • controller.php is the base controller
  • view.php is the base view, and it is rendered by the controller

So, I have this in my controller:

  private $this->security;

  // Will be done by application
  public function set_security();

  private function is_authorized($area, $action)
  {
    if($this->security[$area][$action]==1)
    {
      return true;
    }
    else
    {
      return false;
    }
  }

The question is how do I re-use the method is_authorized in my controller in view class. It has to have the same value of $security variable which could be done as bellow:

  $this->view->security = $this->security;
  $this->view->render();

So, in my view, I can check if a user is authorized with the same security in my controller without replicating the method.

Node.js design: multiple async functions writing to database using function passed as a closure

I am writing a standalone web scraper in Node, run from command line, which looks for specific data on a set of pages, fetches page views data from Google Analytics and saves it all in an MySQL database. Almost all is ready, but today I found a problem with the way I write data in the db.

To make thing easier let's assume I have an index.js file and two controllers - db and web. Db reads/writes data to db, web scraps the pages using configurable amount of PhantomJs instances.

Web exposes one function checkTargetUrls(urls, writer) where urls is an array with urls to be checked and writer is an optional parameter, called only if it is a function and there is data to be written.

Now the way I pass the writer is obviously wrong, but looks as follows (in index.js):

some code here
....
let pageId = 0;
... some promises code,
which checks validy of urls, 
creates new execution in the database, etc.
...

.then(ulrs => {
     return web.checkTargetUrls(urls,

        function(singleUrl, pageData) {
        ...
        a chain of promisable functions from db controller,
        which first lookup page id in the db, then its
        puts in the pageId variable and continues with write to db
        ...

}).then(() => {

logger.info('All done captain!');
}).catch(err => {logger.error(err})

In the effect randomly pageId gets overwritten by id of preceeding/succeeding page and invalid data is saved. Inside web there are up to 10 concurrent instances of PhantomJs running, which call writer function after they analyzed a page. Excuse me my language, but for me an analogy for that situation would be if I had, say, 10 instances of some object, which then rely for writing on a singleton, which causes the pageId overwriting problem (don't know how to properly express in JS/Node.js terms).

So far I have found one fix to the problem, but it is ugly as it introduces tight coupling. If I put the writer code in a separate module and then load it directly from inside the web controller all works great. But for me it is a bad design pattern and would rather do it otherwise.

var writer = require('./writer');

function checkTargetUrls(urls, executionId) {

return new Promise(
    function(resolve, reject) {

        let poolSize = config.phantomJs.concurrentInstances;
        let running = 0;

        ....
        a bit of code goes here
        ....
        if (slots != undefined && slots != null && slots.data.length > 0) {

           return writer.write(executionId, singleUrl, slots);
         }
         ...
         more code follows
})
}

I have a hard time findng a nicer solution, where I could still pass writer as an argument for checkTargetUrls(urls, writer) function. Can anyone point me in the right direction or suggest where to look for the answer?

how to create less specific class from another class in java

I have a model class A { int a ; int b; int c;} I want to create new class B {int a;int b;} I don't want to rewrite all attributes in class B ,this attributes is already written in A . How to use A to create B . we can add extra features to class with extends but how create less specific class ? . are there any pattern for this ? how should be class A or class B or other polymorphic classes. (i want to use class B for inserting db , model class and db table should be same) Sorry for my poor english

Enforcing variable declaration for a subclass in php

I have an abstract class like this

<?php
    abstract class AbastractCreationCommand extends AbstactCommand {
        protected $repository;
        function handle($payload) {
            $this->repository->create($payload);
        }
    }

    class TagCreationCmd extends AbstractCreationCommand {
        function __constructor() {
            $this->repository = new TagRepository();
        }
    }
?>

Questions:

  • is there a way I could enforce the definition of the repository class in the subclasseses of the AbstractCreationCommand ?
  • Do I need to create a test for each subclass and call handle method or is another way to test all my code?

mercredi 27 avril 2016

is this HTML input form secure?

i managed to build this form using many sources over internet , and it actually works. But do not know if it is good against any breaks.

        <form action="/some/server/some.cgi" method="POST">
            <fieldset>
                <legend>contact me:</legend>
                <input type="hidden" name="recipient"
               value="some@some.com">
                <input type="hidden" name="subject"
           value="message ">
                <br>
                <br>
                <table>
                    <tr>
                        <td>
                            <input type="text" name="name" 
                 placeholder="Your Name please" size="30"
            maxlength="30" title="Your name (no numbers)" 
         pattern="[a-zA-Z]{2,30}" required>
                        </td>
                    </tr>

                    <tr>
                        <td>

                            <input type="email" value="email"  
           name="email" placeholder="Provide valid email please" 
                 pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$"
                title="Your VALID email address" size="30" 
             maxlength="50" required>

                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input type="text" name="message" 
            placeholder="Message" size="30" maxlength="200"

            title="Long text is not allowed" 
                   pattern="[a-zA-Z0-9\s]{5,200}" required>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <input type="submit" value="Send" 
                     name="Submit">
                        </td>
                    </tr>
                </table>
            </fieldset>
        </form>

i am new to regEx and would like to know any issues that can happen with this form. thanks

how to find repeated sub sequences of numbers in big string of numbers?

Can anyone helps me with my problem. the problem is:

Assumption 1: we have undefined number of sub strings(s1,s2,s3,…) that each of this sub strings are a sequence of 100 numbers (Integer number between 20000000 and 80000000) that they have been chosen randomly. We don’t have any knowledge about the numbers that make this sub strings and the number of sub strings. the important thing here is the order of numbers in sub string not the relation between them.`

Assumption 2: we have a big and long string include millions of numbers, this long string is made of repetition of sub string that mentioned in assumption 1. The name of this string is “S”.

We simplify the example like below: Each sub string contain five number instead of 100 number and each number is between 20 and 80 instead of 20000000 and 80000000: We have the “S” string, our algorithm must find sub string s1 and s2 and s3 from string “S”.

S= 59,22,51,25,53,66,26,28,59,51,22,53,25,66,71,26,32,28,45,59,91,51,71,53,66,32,45,91,22,25,26,59,51,28,71,53,32,66,45,91 , … .

The output of this algorithm is like below:

S1= 59,51,53,66
S2= 22,25,26,28
S3=71,32,45,91

I want the algorithm that find the number of sub string(s1,s2,s3s, …) And also find the sub string(s1,s2,s3, …) that make the string “S”.

Can anyone help me to solve this problem? Thanks a lot.

Passing single object vs passing multiple arguments

Suppose I have the following

Class A {
    Foo getFoo();
    Bar getBar();
    Baz getBaz();
}

And I need to define a function doStuff that uses Foo, Bar, Baz of one object and does some stuff

I'm struggling between which method of implementing doStuff is better (suppose it would be undesirable to place doStuff inside class A)

Method A

void doStuff(Foo foo, Bar bar, Baz baz)
{ 
    //some operation
}

or

Method B

void doStuff(A a)
{
    Foo foo = a.getFoo();
    Bar bar = a.getBar();
    Baz baz = a.getBaz();
    //some operation
}

To my limited knowledge, (+ pros, - cons)

Method A

+It is clear exactly what parameters doStuff() operates on

-Susceptible to long parameter lists and more susceptible to user mistakes

Method B

+Simple, easy to use method

-Creates unnecessary dependency towards class A


Can anyone share additional insight towards the pros and cons of these two methods?

Do you know the good design pattern for this algorithm?

Here is my system : I have x Mailer objects, each of them are differents instances of the same class (but with different properties)

I have to structure an algorithm to choose 1 Mailer between them :

  • I have to evaluate all of the Mailers (is_active, is_active_for_this_period, ...), if the Mailer can be used, put it in a list of "valid" Mailer objects
  • Choose randomly between the valid Mailers
  • Return the object (to use it after)

Do youknow a design pattern to do that ? I don't find a good pattern to "choose" an object, given a list of them

Thank you Florian

Facade Design Pattern in JavaFx

Hey I'm wondering how I would use a Facade Design pattering in tandem with an MVC pattern in order to change a view when a button is pressed...

I don't have much experience with the Facade pattern (all I've done is simple printouts) so I'm kinda stuck in the water with this one.

Inheritance dependency injection simplification

This one is a bit complicated, so please read everything through. I'm working on some code that implements the MVVM Pattern for WPF. I have a XAML Markup extension that looks for a specific property on the datacontext. (It's a long and fun story, but out of scope) My view model will be set as the Dataconext on the view.

Here's an example of how I have implemented my BaseViewmodel...

public class ViewModelBase : IViewModelBase
{
    protected CommandManagerHelper _commandManagerHelper;

    //todo find a way of eliminating the need for this constructor
    public OrionViewModelBase(CommandManagerHelper commandManagerHelper)
    {
        _commandManagerHelper = commandManagerHelper;
    }

    private IExampleService _exampleService;

    public IExampleService ExampleService
    {
        get
        {
            if (_exampleService == null)
            {
                _exampleService = _commandManagerHelper.GetExampleService();
            }

            return _exampleService;
        }
    }
}

What's going on there is that I'm effectively lazy loading the _exampleService. I'm sure it's possible to use Lazy, but I've not got round to implementing that just yet.

My Xaml Markup will be looking for and making use of my the ExampleService it could also be used by code within the view model. It's going to be used all over the application.

A point to note is that my application will have only one instance of the ExampleServer that will be passed around, calling GetExampleService from anywhere in the application will return the same instance of the object. There will only be one instance of the ExampleService object, although it is not coded as a singleton.

Here is an example of how I am inheriting from my ViewModelBase...

internal class ReportingViewmodel : ViewModelBase
{
    private readonly IReportingRepository _reportingRepository;

    public ReportingViewmodel(CommandManagerHelper commandManagerHelper, IReportingRepository reportingRepository) : base(commandManagerHelper)
    {
        _reportingRepository = reportingRepository;
    }
}

This code works and works great. However, having to type ": base(commandManagerHelper)" every time that I implement a new inherited member of the ViewModelBase is prone to mistakes. I'm likely to have 100's of these implementations and each one needs to be right.

What I'm wondering is.... is there a way of implementing the same behaviour respecting the SOLID principles and not having to call the base constructor every time I implement an instance of the ViewModelBase?

i.e. I'd like the ReportingViewModel to look like this

internal class ReportingViewmodel : ViewModelBase
{
    private readonly IReportingRepository _reportingRepository;

    public ReportingViewmodel(IReportingRepository reportingRepository)
    {
        _reportingRepository = reportingRepository;
    }
}

but still have the ExampleService populated correctly.

I'm currently considering using the Service locator pattern for this, I'm also considering using a Singleton and I'm open to other better solutions.

The reason that I'm asking the question rather than diving in with code is that I know that the Singleton is generally an anti-pattern, to me it signifies that something else is wrong in the code. I've just read an article on IoC and it's slating the Service locator pattern here's the article http://ift.tt/1t2yfbU.

Design pattern for saving entities into database

I have a class similar to the below (C#):

public class Product {

    public int ID {get;set;}
    public string Name {get;set;}
    public double Price {get;set;}

    public void Save() {
        string sql = "INSERT INTO Product.....";
        Database.Execute(sql);
    }

    public void Delete() {
        string sql = "DELETE Product WHERE.....";
        Database.Execute(sql);
    }
}

My main concern is that the code above violates SOLID principles, since it takes responsibility for creating and deleting itself.

Perhaps these Save and Delete methods should be placed somewhere outside the Product entity (Factory/Repository maybe?).

How to extend a class/prototype in Javascript

Okay, so I have the module pattern of my main class as follows:

    Var draggable = {};

    (function(){

     var initialMouseX = undefined;
     var initialMouseY = undefined;
     var startX        = undefined;
     var startY        = undefined;
     var draggedObject = undefined;

     var startDragX    = undefined;
     var startDragY    = undefined;

     var eventHandler  = undefined;
     var canvas        = undefined;

     var that = this;

     this.setCanvasObject = function(cnv){
         canvas = cnv;
     }

     this.setEventHandler = function(eH){
         eventHandler = eH;
     };

     this.setClickable = function(element){
         ...        
     };

     this.setDraggable = function(element){
         ...
     };

     this.startDragMode = function(ev){
        ...
     };

     this.dragMouse = function(ev){
       ....
     };

     this.setPosition = function(dX, dY){
       ...
     };

     this.releaseElement = function() {
      ...
     };
 }).apply(draggable);

This is my parent or prototype class using my flavour of the module design pattern.

Here is my child class, using the same module pattern:

var toolbarHeader = {};

 (function(){

         this.__proto__ = draggable;

         var that = this;

         this.__proto__.startDragMode = function(ev){
             var evt = ev || window.event;
             var target = evt.target || evt.srcElement;

             target = target.parentNode;
             that.startDrag(target);
             initialMouseX = evt.clientX;
             initialMouseY = evt.clientY;

             eventHandler.addEventSimple(document,'mousemove', that.dragMouse);
             eventHandler.addEventSimple(document,'mouseup', that.releaseElement);                    
         };


 }).apply(toolbarHeader);

What i want to do is my toolbarHeader class to overwrite the parent method and in rest use the parents methods as they are.

Currently it issues an error because it cannot find that.releaseElement, that.startDrag and that.dragMouse.

What am i doing wrong? Is this how i should be using inheritance? Is this a good design?

What OOD design pattern am I thinking of?

I am trying to build a class that is only modifiable by the GameController, but accessible to any class. What design pattern should I research to accomplish this?

*I am building this in Java, and the GameController is my Main class. So, I can not create a private instance in the GameController class. Wish it was that simple.

Dynamically building AngularJS routes at runtime based on JSON config

I have a JSON config that I'd like to build my angular routes based off of. In essence, I'd like the angular app to fetch the json, build the routes, then bootstrap the application. I've come up with a working solution, but it doesn't seem to follow the standard angular paradigm and I'd like to figure out what patterns to use to adapt it properly. Perhaps as a service/factory or separate module?

JSON:

{
    "routes" : [
        {
            "route_name"              : "home",
            "route"                   : "/",
            "visible_in_menu"         : true,
            "menu_title"              : "Home",
            "menu_font_awesome_icon"  : "fa-home",
            "controller"              : "HomepageController",
            "template"                : "app/templates/home.html",
            "child_routes"            : null
        },
        {
            "route_name"              : "discover",
            "route"                   : "/discover",
            "visible_in_menu"         : true,
            "menu_title"              : "Discover",
            "menu_font_awesome_icon"  : "fa-search",
            "controller"              : "DashboardAppController",
            "template"                : "app/templates/dashboard.html",
            "child_routes"            : null
        }
    ],

}

Fully functioning Code:

var app = angular.module('dashboardApp',['ngRoute', 'ngAnimate', 'ui.bootstrap']);


// Grab dashboard config, load angular app
fetchData().then(bootstrapApplication);


/**
 * Grabs the dashboard configuration prior to the angular application
 * being loaded.
 */
function fetchData() {
    var initInjector = angular.injector(["ng"]);
    var $http = initInjector.get("$http");

    return $http.get("app/routes_menu_config.json").then(function(response) {
        app.constant("routes_menu_config", response.data);
    }, function(errorResponse) {
        // Handle error case
    });
}


/**
 * Enables the angular application
 */
function bootstrapApplication() {
    buildRoutes();
    angular.bootstrap(document, ["dashboardApp"]);
}


/**
 * Method for building the application's routes at run time based on the routes_menu_config.json 
 */
function buildRoutes(){

    // Grab the JSON extracted from the config file
    var routesAndMenuConfig = angular.injector(['dashboardApp']).get('routes_menu_config');

    var routes = routesAndMenuConfig["routes"]; 

    // Configure angular routes based on JSON
    app.config(['$routeProvider', '$locationProvider',
        function($routeProvider, $locationProvider) {

            for(var i=0; i < routes.length; i++){

                var currentRoute = routes[i];

                // If the current node actually has a route, add it
                if(currentRoute.route){
                    $routeProvider.
                        when(currentRoute.route, {
                            templateUrl: currentRoute.template,
                            controller: currentRoute.controller
                    });
               }

               // If the current node actually has child routes, add them
               if(currentRoute.child_routes){
                    for(var j=0; j < currentRoute.child_routes.length; j++){
                        var currentChildRoute = currentRoute.child_routes[j];

                        $routeProvider.
                            when(currentChildRoute.route, {
                                templateUrl: currentChildRoute.template,
                                controller: currentChildRoute.controller
                      });
                    }
               }

            }

    }]);

}

Model to Model Transformation Techniques or Design Pattern in c#

I have come across a requirement where I need to come up with a Generic framework for transforming one Model to another Model and it should work for any model to any model transformation. So, It will have input model type and output model type.

I know for that purpose, We need to have a mapping file for defining mapping of types in Model.

So, I was just wondering it is a well known problem. So, there must be solution available for this already or any pattern which handles it very nicely.

dynamic business document creation

I am preparing a C#.Net project for our company and would like to know which design pattern is the best fit for creating all those business documents. I have studied some of the available design patterns, to be honest I have problems in applying them to my real world problem, to get concrete here my scenario: Different types of documents have to be created, read into and maintained through windows forms and finally stored back to a database , like e.g. invoices(sales and purchase), contracts(sales and purchase), bill of lading, letter of credit, various inventory and warehouse documents, maybe later a bunch of accounting documents. In the first place I thought factory method would do the job but I am not sure if it is the right choice for this task. I guess it is the best approach to have a abstract class called "Document" with all the common fields (like docId, docDate, docNumber, docIssuer,etc.) as my base and then dive into the concrete creation of the desired document object. What options are there? In case of factories: do I need to define a concrete class for each and every document and create the object(which would be simple inheritance, wouldn't it?) or how should a factory approach look like in regard to my problem? Isn't it better to define each and every document spec (which finally would be like each and every database table field) as an own class and using builder pattern or composite pattern to assemble the desired document at runtime? Or are there any other approaches available? I wonder that many business-related programs have to make this decision but I could not find any prior questions on StackOverflow for this rather common issue.

As said before we are in planning phase and this issue may be considered a crucial pillar of the architecture, therefore any constructive advise would be highly appreciated.

Creating generic types with enum values

I'd like to be able to create new generic types using enum values. I believe this is possible with C++ templates, but I don't know if it's possible to do with C#.

So what I'd like to do is:

public class MyClass <T>
{
  public void Do<T>() {} 
}

public enum Metals
{
  Silver, Gold
}

and I'd like to pass in an enum like:

var myGoldClass = new MyClass<Metals.Gold>();

I guess I could create classes called Gold, Silver to achieve this, but I quite like having an enum to constrain the types of my generic class.

The reason I want something like this in the real world is I'm creating an event aggregator (a publish-subscribe model) and I'd want my subscribers to subscribe to messages of a certain type T. So i thought it would be nice if i could have my subscribers subscribe using enums.

EDIT: To clarify, Metals.Gold is just an example enum. I'd like the client library to create their own enums\classes and use it instead. I'm not defining the enum myself.

Consequences of using an adapter pattern

I have read in lecture notes that consequences of using adapter pattern are:

  1. for class case:

    • cannot adapt class with its subclasses
    • can overload adaptee object methods
  2. for object case:
    • can adapt class with its subclasses
    • cannot overload adaptee object methods
    • gives possibility to add new functionality

So what means that you can or cannor overload adaptee methods? Is it correct? Or maybe it should be that you can overload a target methods?

Is decorator design patter is perfect for this situation or else is better

Work on asp.net mvc5 EF-6 TPH(table per hierarchy), My project have many classes switch,camera,rainbow,router inherit device,here device has common properties but other class have unique properties on each.

enter image description here

For insertion of my camera or switch class properties will I follow Decorator Design Pattern,Because my base is device and want to add new functionality to an existing object without changing its structure then insert the object in database.

Is decorator design patter is perfect for this situation or else is better?

using the factory pattern with derived classes accepting diverse number of parameters

I'm using the following factory pattern:

using System;

class Program
{
    abstract class Position
    {
    public abstract string Title { get; }
    }

    class Manager : Position
    {
    public override string Title
    {
        get
        {
        return "Manager";
        }
    }
    }

    class Clerk : Position
    {
    public override string Title
    {
        get
        {
        return "Clerk";
        }
    }
    }

    class Programmer : Position
    {
    public override string Title
    {
        get
        {
        return "Programmer";
        }
    }
    }

    static class Factory
    {
    /// <summary>
    /// Decides which class to instantiate.
    /// </summary>
    public static Position Get(int id)
    {
        switch (id)
        {
        case 0:
            return new Manager();
        case 1:
        case 2:
            return new Clerk();
        case 3:
        default:
            return new Programmer();
        }
    }

The way to use this pattern is in the example from the same source:

static void Main()
{
for (int i = 0; i <= 3; i++)
{
    var position = Factory.Get(i);
    Console.WriteLine("Where id = {0}, position = {1} ", i, position.Title);
}
}

Should I be using this pattern if my derived classes are using different numbers of parameters for their constructors?

The probable modification that I would need to make is when instantiating the factory:

var position = Factory.Get(i);

I would probably need to pass in parameters for all of the derived classes, regardless of whether they would use them or not:

var position = Factory.Get(i, param1, param2, param3);

and the switch statement would need to be modified:

public static Position Get(int id, param1, param2, param3) //HERE IS THE MODIFIED PARAM LIST
{
    switch (id)
    {
    case 0:
        return new Manager(param1); //MODIFIED
    case 1:
    case 2:
        return new Clerk(param2, param3); //MODIFIED
    case 3:
    default:
        return new Programmer(param3); //MODIFIED
    }
}

Do the modifications that I've made to the factory pattern break the pattern, and should I be using a different pattern for object creation?

Why singleton breaks open/closed principle?

Could anyone tell me why does singleton break open/closed principle? Is it because there could be problems with inheriting from that class?

mardi 26 avril 2016

C# complex regular expression for finding a specific pattern in big documents

I'm trying to come up with a regular expression that will capture a quoted text followed by a set of parenthesis containing a bible verse reference. This is so that a document containing a chapter from a Christian book that references bible verses can have it's verses matched and replaced with any desired translation of the bible.

I've been having a lot of trouble with this. I can only come up with patterns that partially work. Here is an example text that gives me trouble.

"make disciples" - to build men like themselves who were so constrained by the commission of Christ that they not only followed, but led others to follow His way. Only as disciples were made could the other activities of the commission fulfill their purpose. PRAY FOR HARVESTERS Leadership was the emphasis. Jesus had already demonstrated by His own ministry that the deluded masses were ripe for the harvest, but without spiritual shepherds to lead them, how could they ever be won? "Pray ye therefore the Lord of the harvest," Jesus reminded His disciples, "that He will send forth laborers into His harvest" (Matt. 9:37, 38; Luke 10:2). More text here.

this is the best regular expression I have yet.

(\"[^\s\d]*[^:]*[^\s\d]*)*\"\s*\(([\w. ]+[\d\s]+[:][\s\d\-]+[^)]*)

All the regular expressions I have come up with will capture this pattern only in conditions where this isn't happening. The problem with this is, it will capture the very first quote and then the last quote right before the parens at the end and then those parens and the verses. However, for this example I would only want it to capture "that He will send forth laborers into His harvest" (Matt. 9:37, 38; Luke 10:2).

Any ideas????? Is this possible with regular expressions?

Also, sorry for the biblical references here, I'm just interested in solving this somewhat complex problem.

Here is a link to what I have so for.

Better Design Pattern?

I have myArrayList that already have values in it. For this example lets say there are only two elements in it(firstName and lastName). I need to get values from myArrayList and compare them to String and if it matches then get value from the bean and put it into map:

        Map<String,String> myMap;
        for(String element: myArrayList){
               if(element.equalsIgnoreCase("firstName")){
                   myMap.put("firstName", bean.getFirstName());
               }else if(element.equalsIgnoreCase("lastName")){
                   myMap.put("lastName", bean.getLastName());
               }
        }

The problem is when you have thirty-forty elements in myArrayList you will have performance issues(I assume), and it just doesn't feel right.

I tried this:

        String name = null;
        String value = null;
        for(int i = 0; i < myArrayList.size(); i++){
            name = myArrayList.get(i);
            value = bean.get(name);
            predisbursementDiscMap.put(name, value);
        }

But the line "value = bean.get(name);" is saying that method get(String) is undefined in bean class, indeed we don't have such method in bean class, it has only standard getter and setter methods:

public class Bean implements Serializable {
    private String firstName;
    private String lastName;

    public String getFirstName(){
        return firstName;
    }

    public void setFirstName(String firstName){
        this.firstName = firstName;
    }

    public String getLastName(){
        return lastName;
    }

    public void setLastName(String lastName){
        this.lastName = lastName;
    }

}

Now I am thinking how I could come up with some design pattern that optimizes my logic and doesn't affect performance of the code. Please feel free to ask questions, I will edit if you need more info. Any help is greatly appreciated. Thanks.

How can i improve designing skills ? Is there any place to get suggestions on our implementation?

I would like to implement design for the real time software problems and need suggestions on my implementation ? IS there any website that can help me on this?

Tight coupling & DI threshold

I have a code that goes like

class A
{
    public $b, $c;

    //Inject D and E here? (B $b, C $c, D $d, E $e, ...)
    public function __construct(B $b, C $c)
    {
        $this->b = $b;
        $this->c = $c;
    }

    public function main()
    {
        if (rand(0,1)) {
            new D();
        } else {
            new E();
        }
    }
}

Should I inject the possible D and E classes in constructor of A? The problem here is that the hierarchy of the project follows this tree-like structure thus making the upper node A to hold all the dependencies of its child nodes. Or is it sane enough to be stupid at some point?

design pattern for navigating to another page using angular js

I am just starting up with angular js. My question is more specific to the design pattern on my use case.

I have a landing page for my business which has a user login. This user login on authentication needs to take the user to the personal page.

I am coming from jsf world where i will be writing a control flow rule to navigate the user to a totally new page. In jsp world also I have done something redirecting to a new page after authentication from the servlet.

So, what is the recommended way in angularJS. Currently, The login button on the landing page invokes the controller defined in the js. which in turns invokes google cloud endpoint to authenticate and returns the response as true or false. now i need to navigate if its true.

Understanding Liskov Substituion Principle

My sample program like below;

    public class Animal
    {
        public virtual string MakeSound()
        {
            return "General Sound";
        }
    }

    public class Dog : Animal
    {
        public override string MakeSound()
        {
            return "Bow..Bow..";
        }
    }
}

        static void Main(string[] args)
        {
            Animal obj1 = new Animal();
            Console.WriteLine("General Animal's sound id " + obj1.MakeSound());

            Dog obj2 = new Dog();
            Console.WriteLine("Dog Animal's sound id " + obj2.MakeSound());

            //Violate LSP
            Animal obj3 = new Dog();
            Console.WriteLine("Animal's sound id " + obj3.MakeSound());

            Console.ReadKey();
        }

Here as my understanding when we create Dog instance for Animal like obj3, we are violating LSP. Please confirm my understanding. If yes, please tell me how to achieve in this case to understand better. I think my coding is conceptionwise correct

Need help designing a better way of handling user errors

I have created a file that contains all my validation functions. They are being called multiple times all over my application. Here are some of them.

Note: I am using php, but I don't think it matters that much.

// check if uploaded file is valid:
function validate_file($full_path, $error_code) {
    if (is_file($full_path)) {
        throw new Exception('This file already exist.');
    }
    if ($error_code != 0) {
        throw new Exception($error_code);
    }
}

// get all database specific errors after each sql operation
public function get_db_errors() {
    $message = $this->db->_error_message();
    if (!empty($message)) {
        throw new Exception($message);
    }
}

// add unique record to the database
public function insert($table_name, $columns, $unique_columns = null) {
    if ($unique_columns == null || empty($this->get($table_name, $unique_columns))) {
        $this->db->insert($table_name, $columns);
    } else {
        throw new Exception('this ' .key($unique_columns) . ' already exist.');
    }
    $this->get_db_errors();
}

Here's how I can use them:

class controller {
    try {
        // call any function above if needed.
    } catch(Exception $e) {
        $e->getMessage();
    }
}

I'm pretty happy using this code, since I have one error handler that catches any exception my helper functions can throw. I can even do this in any controller. Until I've read that putting everything in exceptions is actually not the preferred way of handling bad inputs.

Obviously, I will have to destroy all those functions and create a new error handling mechanism for my application. The thing is now I have no idea how to proceed.

How can I proceed designing a user error handler while remaining simple as before? I've heard that one option is to put all error messages in an array and give each of them an error_code. Is that the preferred solution?

How does the observer pattern reduce coupling?

I understand how the observer pattern works, but I am not sure as to why is it that the observer pattern reduces coupling between UI and business logic components in software design?

How to add different set of parameters to factory method design pattern to achieve proper design

I have a scenario where two different classes have many properties and one different property. How do I use factory design pattern or should I not use it? Internal private methods of these sub classes make use of these properties.

public class RunsValidator  
{  
     //Few common properties  
     public int DataSegmentID { get; set; }  
     public int AttributeOffset { get; set; }  
}

public class ProductAttributeRunValidator : RunsValidator  
{

    public ProductAttributeRunValidator(string productNames)
    {
       this.ProdNames = productNames;
    }
}

public class CategoryAttributeRunValidator : RunsValidator  
{  

     public CategoryAttributeRunValidator(int orgIDs) : base()  
          {  
            this.totalOrgIDs = orgIDs;  
          }  

}  

//Factory implementation

public class RunAttributeFactory  
{     

    public static RunsValidator GetRunValidator(string type, string productNames, int orgIds)  
     {  
      RunsValidator runValidator = null;  
      if(type == "Product")  
      {   
           runValidator = new ProductAttributeRunValidator(productNames);  
      }  
      else if (type == "Category")  
      {  
           runValidator = new CategoryAttributeRunValidator(orgIds);  
      }  
      else  
      {  
          runValidator = null;  
      }  
      return runValidator;  
    }  
}

In the client code, I have access to variables that should be sent as parameters (productNames, orgIds and type) to the Factory method. I would like to access the returned runValidator in many places in the client code as it needs to be set only once based on the type.

Which is the best way to achieve this?

how to register parameterized based constructor classes in unity container in C#?

I am new to Dependency injection Pattern. Please look in to the below scenario. Right now, my below code is in tightly coupled. I want to make this as lightly coupled.

Could someone help me out to implement dependency injection using Unity?

// Implementation of class A
    public class A
    {
      public B b{get;set;}
      public A(B b,string c)
      {
         this.b=b;
         this.A(b,c);
      }
    }

//Implementation of Class B
    public class B
    {
        public int value1 {get;private set;}
        public string stringValue {get;private set;}

        public B(int value,string strValue)
        {
           this.value1=value;
           this.stringValue=strValue;
        }
    }

    //Implementation of class C
    public class C
    {

      public void Dosomething()
      {
         B b=null;
         string value="Something";
         A a=new A(b,value); // Here I need to implement unity to resolve tight coupling without creating object of Class A

      }
    }

lundi 25 avril 2016

Is there an Android design pattern to handle multiple fragments in a single activity?

I inherited some code at work and I have a question about some implementation. The application I'm working on has an Activity that contains about 15 different fragments. The logic in the Activity handling these fragments can roughly be summarized with the following pseudocode:

if (button_1 selected) { 
    load fragment_1; 
} else if (button_2 selected) {
    load fragment_2;
} else if (button_3 selected) {
    load fragment_3;
} ...and so on x15ish

My question is: does there exist some kind of Android design pattern to handle situations like this? The code works; however, I don't feel too comfortable with a giant if/else or case statement. I saw this question and it seems very similar to the problem that I'm having. I did quite a bit of searching on the internet but I haven't found examples or best practices for this kind of scenario.

If someone can point me in the right direction or have some suggestions; that'd be awesome. Thanks!

What are the common design patterns in Rails?

I'm researching the design patterns in Rails. And I'm an amateur in the design pattern sector.

Who can tell me what common design patterns are used in Rails ? Please make a little introduction for each of them. Thank you so much. Have nice day.

Factory method example in scala repl giving error

I am unable to run below code in Scala repl. This is a reproduction from Scala cookbook example provided by Alvin Alexander

This works fine when compiling (scalac) and executing (scala). Can you please tell me how I can make this example work on repl as well? Thanks a lot for your help!

trait Animal {
    def speak
}
object Animal {
    private class Dog extends Animal {
        override def speak = {
            println("woof")
        }
    }

    private class Cat extends Animal {
        override def speak { println("meow") }
    }
    def apply(s: String):Animal = {
        if (s == "dog") return new Dog
        else return new Cat
    }

}


# repl
Animal("dog") 

# compiling
object test {
    def main(args: Array[String]){
        Animal(args(0)).speak
    }
}

Validation methods outside of validators

I have a few methods that return true or false if the value passed to them meets certain requirements.

These validations will be called from several different controllers, and possibly different models as well.

I would like to do this without plugging them into an object and running validation on the object. Is this possible?

Do I group all of these "validating methods" into a class? If so, where does that class go"

Which technology should I choose?

Hi I am MS computer science student and wanted to do carrier in big data Can you guide me how should I proceed without big data knowledge. Do i have to get training or can able to apply directly without training. Can you please guide me. I have knowledge of software architecture, data mining, software requirement gathering, project planning and management and object oriented analysis, design patterns . I have academic background and worked as professor in India

Patterns for knowing if a pub-sub message was successful

I'm developing microservices for a project and we're experimenting with pub-sub communication using AWS SNS+SQS. We're unsure how to signal to services whether or not other services have successfully completed tasks or not.
For example, if service A emits an SNS Event and service D, E, and F all are listening to the subscribed SQS Queue, how does service A know if the activities kicked off by service A inside of service D, E, and F were successful?

I'll give a more concrete example: A new user registers for a website. This network call first reaches the user service in the backend. If the user was successful, it sends off an event saying a new user was created. That triggers the email service to send an email to for the user to confirm his registration. What happens if it fails to send an email? Has the user service:

1) Already responded to the frontend saying it was successful

2) Or is it waiting for a confirmation? What is a good pub-sub pattern for confirmations?

I know we could have just done a synchronous call, but this example is simplified for brevity's sake.

How to scaffold for NativeScript services

I am proposing to do is to have a separate folder which will contain 'services'. This would be for calls out to various REST APIs. Below is the pattern I'm thinking of using. Does this break any conventions of NativeScript or is it even good practice? The services could be called from other folders within the app so I am trying to keep things DRY.

app.js // The main app file, loads /items/items_list/items_list.xml
          as first screen of the app.

/services
  /parts
     get_parts.js // Lets say this would be a http service, called from
                     either /items or /jobs, or even anywhere else
                     within the app.

/items
  /items_list
    item_list.css
    item_list.xml
    item_list.js
    ...
/jobs
  /jobs_list
    jobs_list.css
    jobs_list.xml
    jobs_list.js
    ...

The names are made up for the purposes of the question so hopefully it still makes sense.

Design pattern to use when you need to initialize your object?

I have a class, which has an Initialize method, which creates a bunch of tables in a database. This class looks like this:

public class MyClass
{
  private bool initialized = false;

  public void Initialize()
  {
    if(!initialized)
    {
        //Install Database tables
        initialized = true;
    }
  }

  public void DoSomething()
  {
    //Some code which depends on the database tables being created 
  }

  public void DoSomethingElse()
  {
    //Some other code which depends on the database tables being created 
  }
} 

The two methods DoSomething and DoSomethingElse need to make sure that the Initialize method has been called before proceeding because they depend on having the tables in the database. I have two choices:

  1. Call the Initialize method in the constructor of the class - this does not seem like a good idea because constructors should now call methods, which are non-trivial and could cause an exception.

  2. Call the Initialize method in each of the two methods - this does not seem like a great solution either especially if there are more than a handful of methods.

Is there a design pattern which could solve this in a more elegant way?

Proper handling of errors stored in a class in code igniter

I am doing a project using code igniter and I have to pass all error messages to ajax. So I'm thinking of putting them in an array. How can I go about this?

The first approach I've thought is to create a class that store all error messages and displays them, like this.

class errors {
    public $errorList = array();
    public function set_error($key, $message)
        $errorList[$key] = $message;
    }

    public function display_errors()
    {
        return $errorLis;
    }
}

I would use it like this:

public function upload_file()
{
    // if file not uploaded,
    set_error("file upload", $this->upload->display_errors());
}

Is this approach fine? What is wrong with it? What's a better way?

Using Web API as a core system

The company where I'm working at, has a software system with two web applications, four desktop applications and a web API based on a SQL-database.

I implemented the API using WEB API 2.During load tests, I found that performance is excellent, even with lots of records we have. Accordingly, my company has asked me to design and implement a WEB API and an Authentication system for getting, processing, authenticating and responding all transactions from web, windows and Mobile apps.

Now here are the questions:

1- Is this the right way to use WEB APIs as the Core system and manage all transactions through it?

2- According to your experiences, does web API really have enough performance to act as a DATA ACCESS?

3- Does authenticating transactions through the web API have enough security?

4- If yes, now according to the Web API design patterns which layers are necessary in order to implement web or desktop applications? (Data access, Model, Service, View model, web, etc.)

Thank you in advance :)

javascript design pattern on page with 2 or more objects

I need to choose the right design pattern. My page have 2 objects created from same constructor. The problem that i have is detecting which object is getting a click event.

I am doing this after object creation:

$("table tr, table button,.dataTables_paginate a").click(function (e) {
    **myTableName.buttonPressed($(this));**

});

and

 buttonPressed: function (el) {
    if (el.is('a') && el.closest('li').hasClass('paginate_button')) {
        var objName = el.attr('aria-controls');
        debugger;
    }
    else {
        var objName = $(el).closest('table').attr('id');
    }

    **this.getName(objName);**
    tbl = myTableName.tbl;
    editor = myTableName.editor;
    //myTableName.acl(myTableName.currentForm);

},

and then

 getName: function (objName) {
    // search through the global object for a name that resolves to this object
    for (var name in window)
        if (window[name] == this) {
            if (objName) {
                myTableName = window[objName];
                //window.myState[this.myInstanceName] = jQuery.extend({}, this);
                break;
            } else {
                window[name] = this;
                window[window[name]] = window[name];
                myTableName = window[window[name]];
                // window.myState[this.myInstanceName] = jQuery.extend({}, this);
            }
            break;
        }
},

Besides these are all globals , i dont fell this is the correct way to do that.

Thoughts?

How do I implement this protocol in struct

I'm new to Swift and I want to create an abstract factory for db access. Here is my protocol

protocol IDAOFactory
{
  associatedtype DAO: IDAO

  func createAccountDAO<DAO: IAccountDAO>() -> DAO
}

struct RealmFactory: IDAOFactory
{

}

protocol IDAO
{
   associatedtype T
   func save(object: T)
}

protocol IAccountDAO : IDAO
{

}

struct AccountDAORealm: IAccountDAO
{

}

How to implement the IDAOFactory in struct RealmFactory and IAccountDAO in struct AccountDAORealm? Can anybody help?

How to talk between HTTP request & cli class objects

I have a application running that's listing to HTTP request. Each request is passed to single page where a framework object $app is instantiated and this takes care of routing / controller / model etc.

Now i have a another class whose object is instantiated via. a CLI script lets call it $cliApp now problem is how do i make both the object talk to each other. $app is instantiate every-time there is a new request.

But $cliApp is instantiate only once when script is ran. This scripts runs in loop via $loop object by PHP React Event loop.

Cli App is running websockets. So basically i want http & sockets to communicate via. http api.

P.s. :

Right now i have one solution to use message queueing e.g. 0mq etc. but that seems overkill since i'm not looking to scale and keep it simple.

Server application design pattern?

I'm developing a new server-client application and I wondered what should design pattern should I use for the server side?

I learned in class about the reactor design pattern and implemented it in Java, and it works pretty well, but the code is complicated.

Recently I have been mainly programming in Python - Aמג I'm looking for something simpler that already implemented - in Python.

dimanche 24 avril 2016

How to avoid changing every child constructor when parent constructor changes

Say I have the following (C++)

class Parent
{
     Parent(Foo f){};
}

class Child : public Parent
{
    Child(Foo f, Bar b)
        : Parent(f)
    {};
}
...
// And a whole bunch of other children, all calling Parent constructor

Suppose now I need to add a new parameter to the Parent constructor

Parent(Foo f, Baz z){};

Then I will have to change every single child class to the following

Child(Foo f, Baz z, Bar b)
    : Parent(f, z)
{};

Is there anyway I can avoid having to change every single child class?

Guess might be related to this, how to avoid repetitive constructor in children which suggests that I must change every child class.

If so, are there any languages / design patterns that would make such a change less painful?