jeudi 31 décembre 2015

How to solve undetected event using AND operator inside EPL statement?

If I have event sequence of: 1:17 2:18 3:17,18 4:2

The sequence of 17--> 18 --> 17 AND 18 should produce derived event of 303 class.

My EPL statement: SELECT a.Identifier, a.SensorValue FROM pattern [every a=GenericSensor(SensorValue=17) -> b=GenericSensor(SensorValue=18) -> c=GenericSensor((SensorValue=17) AND (SensorValue=18))].win:length(4);

My Problem: The derived event of 303 is undetected though there have the true sequence.

How to solve this problem.? I thought the statement is supposedly correct. Thanks in advanced.

Looking for Name of Common Server Pattern

I have been having some trouble identifying whether or not there is a name for the following common pattern:

A thing which has at minimum the following lifecycle:

  • comes online
  • accepts requests for an indefinite period of time
  • receives a signal to stop accepting new requests, but finish processing any currently processing requests
  • goes offline

I mean this as opposed to something with a terminal lifecycle, something like:

  • comes online
  • does some work on one request
  • goes offline

The most concrete example of this pattern in my mind is a web server which is subject to a load balancer, but am having trouble finding some general literature on the subject.

Is document/view architecture in MFC basically a Model/View/Controller pattern but without the controller?

Is document/view architecture in MFC basically a Model/View/Controller pattern but without the controller part?
I'm studying MFC (yes, MFC!) and I simply love it to bits. I know is somewhat outdated and somewhat bit more difficult to use, but I discovered that it gives me so much more power and performance gain when compared for example to QT.
Anyway, I'm studying the MFC doc/view model now and from what I see this is simply MVC but without the Controller part. Am I correct?

mercredi 30 décembre 2015

Conventions for functions that operate on structs

Let's say I have the following in foo.h:

typedef struct {
    char* my_buf;
    int my_int;
} MyFoo;

/* Creates a foo, allocating memory for my_buf and initializing my_int */
void init_foo(MyFoo *foo);
/* Destroys a foo, freeing the memory for my_buf */
void free_foo(MyFoo *foo);

Now in another module, bar.h let's say I have the following:

#include "foo.h"

/* Do something with a foo */
void do_something(MyFoo *foo, SomeType_t otherType, ...);

As written, it's unclear whether or not the MyFoo provided to do_something should have been initialized with create_foo. Since it's not const, I think it's reasonably clear that a foo (i.e. space allocated for a foo) should be passed in, it will be modified in some way, and then the user can use the modified foo. But how do I most effectively indicate whether or not that foo should have been 'created'? A common pattern is to do something like

MyFoo stackFoo;
do_something(&stackFoo, ...);

But then, if do_something creates the foo, the user has to know that they're responsible for freeing the foo. On the other hand, there's no way to enforce that the foo should have been created; I'm just asking for a pointer (I admit this is a weak counter argument since it applies to a lot of things in C).

Another option would be to have MyFoo include a "created" flag so that it the function can reject any foos that haven't been created, but this seems like I'm over-engineering things.

I just want to be sure I'm not missing a common convention or standard way of handling this. Maybe I'm forcing OOP too much. Thoughts and comments appreciated!

How to refactor the following codes?

I have the following codes, I think the content is too large and I am deeply think about how to refactor it, may someone has good advice to refactor it ?

List<AccountEntity> fillNameAccounts = agentDao.getAgentListByIds(accountIdList);
    for (T bean : results)
    {
        for (AccountEntity entity : fillNameAccounts)
        {
            String chineseName = entity.getChineseName();
            String firstName = entity.getFirstName();
            String fillName = StringUtils.isBlank(chineseName) ? firstName : chineseName;
            String entityId = entity.getId().toString();
            if (bean instanceof AgentPostResponseBean)
            {
                if (StringUtils.equals(((AgentPostResponseBean) bean).getParentId(), entityId))
                {
                    ((AgentPostResponseBean) bean).setParentName(fillName);
                }
                if (StringUtils.equals(((AgentPostResponseBean) bean).getPosterId(), entityId))
                {
                    ((AgentPostResponseBean) bean).setPosterName(fillName);
                }
            }
            else if (bean instanceof ImportAgentPostResponseBean)
            {

                if (StringUtils.equals(((ImportAgentPostResponseBean) bean).getParentId(), entityId))
                {
                    ((ImportAgentPostResponseBean) bean).setParentName(fillName);
                }
                if (StringUtils.equals(((ImportAgentPostResponseBean) bean).getPosterId(), entityId))
                {
                    ((ImportAgentPostResponseBean) bean).setPosterName(fillName);
                }
            }
        }
    }

Thanks.

Android MVP design - few views in same screen

I have an activity with collapsing toolbar layout content, provided by domain layer, and two fragments, which will be shown simultaneously on tablets. Fragments need content from domain layer as well.

What is the best way to implement MVP?

Should presenter have link only to activity? So should fragments interact with app through its activity? It's seems obvious, but this breaks idea, that fragment is independent and reusable view object and make many problems, like when activity receive update for fragment, when it doesn’t present and don't have content for just created fragment.

Unit of Work / Repository pattern updating multiple sources at the same time

I have implemented unit of work / repository pattern for SQL Server and MySql. They work great when I have to update either database server.

A new requirement has come in - for one object type, I need to update both SQL Server and MySql at the same time. Ideally, this would be done in a transaction.

Can someone please suggest a way to implement this?

Best way to implement or use CallBack function

I am facing an issue with callback mechanism which I use to pass data from my library to client. What client does is sometime in the callback function they do some time consuming processing. Which blocks the callback function. Like if client tries to close my library from my callback function I get deadlock because I can't close the library unless I close the thread which is used by the callback function.

Is there any standard to using the callback? Like any design pattern that dictates how a callback should be implemented by a library or used by a client.

Visitor pattern: change object state?

Is it acceptable that visitor change the state of object in which it operates? These kind of operation are not considered as anti patterns?

Command Pattern :How does command allows extensible?

I read command pattern here in this link http://ift.tt/1QZv2ET

Its says command pattern " Command pattern is easily extendible, we can add new action methods in receivers and create new Command implementations without changing the client code."

How it is possible client codes has to change if we add new command .Suppose in above code example if I want to add DeleteCommand. Client program main has to change right I mean he was to need code in to client code.

What does the change word means exactly it means ? Does it mean we dont need to change existing code but we can add new code. Is that is the meaning of Extensible of command pattern ??

Unlock patterns using adb sendevent in Android

After checking some answers:

Is there a way to unlock android phone via adb, if I KNOW the pattern and Unlock Screen Galaxy Nexus ADB

Im trying to unlock a pattern using adb commands using this script http://ift.tt/1QZWYIx (for automation purpose).

Unfortunately the events arent working but I noticed that if I turn on the screen by myself (without using adb shell input keyevent 26) while the script is running, the events work and the pattern unlock.

Could someone explain me why this is happening and if there is another way to unlock patterns? maybe without using events (like I wrote before is for automation purpose, not for a phone that was locked).

Observer Pattern with events instead of parameters (Push-Model)

Right now I am trying to fully understand the concept of the Observer Pattern.

To my understanding (correct me if I am wrong): It is recommended to use events instead of parameters if you have different Observers who needs a different set of parameters and you dont want your updateFuntion to contain all the variables

=> unnecessary data transfer in the updateFunction

=> problems when updateFunction needs one more parameter (you have to change all the Observers)

Can you explain to me how using events will solve this problem and how this is implemented? (perhaps in Java?)

Bridge pattern double bridge

I am trying to design a system. I thought that bridge pattern would be helpful but maybe I am going mad and there is a better option. I am not a software pattern expert.

I need to draw a shape depending on the shape type, the colour and the wall where is going to be painted on.

There are two shapes: Rectangle and Circle There are two colours: Red and Blue There are two walls: Wood wall and Concrete wall

First naive attemp would be:

                    ----Shape---
              /                      \
        Rectangle                     Circle
          /                              \
BlueRectangleWoodWall               BlueCircleWoodWall
BlueRectangleConcreteWall           BlueCircleConcreteWall
RedRectangleWoodWall                BlueCircleWoodWall  
RedRectangleConcreteWall            BlueCircleConcreteWall

In total 11 classes! I think that's not a good idea. If I didn't have to worry about the type of wall, I would do a bridge:

      ----Shape---                        Color
     /            \                       /   \
Rectangle(Color)   Circle(Color)        Blue   Red

But I need to add the wall variation so I thought doing something like a "double bridge"?

      ----Shape---                            Color
     /            \                          /      \
Rectangle(Color)   Circle(Color)           Blue(Wall) Red(Wall)


        Wall
       /      \                         
 ConcreteWall WoodWall

Is this a good idea? I am not a software pattern expert. That's why I am asking for help. In this case I only decrease from 11 classes to 9. Thank you!

What is the industry standard for API endpoint routing and management? Database or routing file?

What is the industry standard for managing large API endpoints routing logic?

Do say Google, Twitter, and Amazon store their API end-points in databases for controller look-ups, or an extensive flat file lookup system? Laravel PHP framework for example uses a routing file to manage endpoints.

Good book to learn Design patterns and its implementation in terms of automation testing frameworks?

Being a automation developer I would like to know if there is any book or blog etc which can help me to learn about design patterns and how they should be implemented while writing automation testing frameworks .

Start with Qt with weak C++ knowledge

Whether it is wise to start using Qt with a weak C++ knowledge? Or it is more recommended to go throught C++ 5th Primer book and then switch to Qt?

mardi 29 décembre 2015

Patterns to manage database relationships in memory

A while ago, I wrote a small framework in C# to manage database relationships (1 to 1, 1 to N) in memory. I've since refactored some of the design and here's an example of the how one might use the current code:

class A : FrameworkEntity
{
    public static readonly Relationship1To1<A, B> relationship
        = RelationshipManager.Instance.Relate1To1<A, B>();

    public B B
    {
        get { return relationship.GetForward(this); }
        set { relationship.SetForward(this, value); }
    }

    public C Parent
    {
        get { return C.relationship.GetReverse(this); }
    }
}

class B : FrameworkEntity
{
    public A A
    {
        get { return A.relationship.GetReverse(this); }
        set { A.relationship.SetReverse(value, this); }
    }
}

class C : FrameworkEntity
{
    public static readonly Relationship1ToN<C, A> relationship
        = RelationshipManager.Instance.Relate1ToN<C, A>();

    // the implementation will call the RelationshipManager
    // to update the relationship on add/update/delete
    public ICollection<A> Children
    {
        get { return relationship.GetFoward(this); }
    }
}

To me, this seems like a use of the mediator design pattern with dependency properties. There's a central singleton object, the RelationshipManager, that's used to manage changes to an object's relatives. That static dependency is accessed by each instance through instance properties.

Is there another way to do this, without using dependency properties? I didn't design the original code for this framework, and am curious how else someone might do this.

Pattern search algorithm

I have few letters and want to find pattern which happen often.

I have below letters.

 ---------TAAA-GAGAG----T--T-------T
 -------------T------A---------T----
 ----------AAA-GAGAG---C-----------T
 ------C------------T-A----T-----TA-
 -----AC----------------TT--------C-
 -------------------T---------------
 ---A---------------T---------------
 -------------------------T----T----
 ------C---------------------T-----T
 ----------AAA-GAGAG---C------------
 ----A--------------------T-------A-
 --------G-G-----------G-------T----
 ----A--------------------T---------
 ---------T-------------------------
 -----AC------T--------------------T
 --GA-G------------GT--------------T
 -----A--G-AAA-GAGAG-AA-------------
 -----------------------------------
 -T-------C-G-------T---TT------T--T
 TT-----------------T---------------
 -------------------T---TT-T--------
 ---A----G------------A--------T----
 -----------------------------------
 -------T--AA--G-GAG---C------------
 -T-A----------------A--------------
 ------------T------------------T---
 -----------G-----------------------
 --G-A------------------C---T---T---
 ----A---G---A-------A------T-------
 --------G-------------------T-----T
 -TG--------A---------A-T-----------
 --G--A--------GAGAG---CT-----------
 ---A-------G------------T----G---A-
 T-------G----T---------------------
 -T----C-GCAA--GAGAG-A-C-----T--TT--
 -----A----AAA-GAGAG-A-T------G---A-
 -T---------G-----------------------
 ---A---T---------------------G-----
 ---A---------T-------A---T---A---A-
 -----------------------------------
 TC--A----T----------G-------T-T--G-
 -T----CT---G-T-----T-A----T-T--T---
 -------------T-----TA------------A-
 --G----T-----------------T-T--T----
 ---A------AA--GAGAG---C-----T------
 --------------GAGAG-A-C------------
 ----------AA--GAGAG---C-G----------

And as you can see there is pattern on the middle there is "GAGAG"

So I can say This G+A+G+A+G <- is coming from same data.

So I want to split out that lines and group.

Wrong Case. First line There is T+A+A+A but another line does not together with T+A+A+A , only A+A+A always together. So in this case T and A is not group.

Anybody has idea this kind of related algorithm or how to find a pattern.

I try to do with Java Programming.

Thank you.

"managed" depends on "manager" structure

I have a structure problem with DependancyInject.

Situation

I'm working on creating a server for a voxel based game; it's entirely modulated, but the relevant modules are the following 3.

NetworkModule(sends and receives packets) WorldModule(Handles world related events and stores worlds) World(Stores all the blocks and has a list of players in the world) Block(Has a material, and some other fields)

Problem

When the setMaterial(Material material) method is called in the Block class, a "BlockChange" packet should be sent to all the players in the world to let the client know that the block has changed type. To send that packet, the Block class must have access to the NetworkModule. There is an instance of NetworkModule stored inside the WorldModule. Technically this can be easily solved, just pass the WorldModule, or NetworkModule into each Block class. To me that rings alarm bells, it ties the manager to the managed and also wastes space saving that instance. I feel like there must be a better way to do this such that they don't depend on each other.

Java DAO design pattern category?

Which category (Creational, Structural or Behavioral) does a Java DAO design pattern falls into?

Singleton with static inner class and double-checked locking

I am reading about Singleton design pattern and evaluating different implementations. I have doubt with the below implementations:

A. Singleton Implementation with static inner class

public class SingletonWithStaticClass {

private SingletonWithStaticClass(){}

private static class SingletonInnerClass{
    public static SingletonWithStaticClass INSTANCE = new SingletonWithStaticClass();

}

public static SingletonWithStaticClass getInstance(){
    return SingletonInnerClass.INSTANCE;
}

}

B. Singleton double checked locking

public class SingletonWithDoubleCheck {
private static SingletonWithDoubleCheck INSTANCE = null;

private SingletonWithDoubleCheck(){
    if(INSTANCE != null){
        throw new RuntimeException("Accessing private constructor is prohibited. Use getInstance method instead");
    }
}

public static SingletonWithDoubleCheck getInstance(){
    if(INSTANCE == null){
        synchronized (SingletonWithDoubleCheck.class) {
            if(INSTANCE == null){
                INSTANCE = new SingletonWithDoubleCheck();
            }
        }
    }
    return INSTANCE;
}

}

Which one is better?

I feel we can access the private constructor with Reflection in first implementation where as second implementation is safe.

However, I am not going to use any of these in my production code, I will use enum instead. But out of these two, isn't the first implementation is broken when considered Reflection attack?

Please correct me if my understanding is wrong.

angularjs ng-pattern for input[email] doesn't work as expected

I want to allow ANYTHING, including invalid emails (without @, empty, etc)

http://ift.tt/1mNBTo7

I'm using:

ng-pattern="/.*?/"

But it doesn't works until you don't put an *@* (like a@b) in the input.

How can I avoid this?

Driving license number format / regex pattern for European countries

I'm trying to create a regex pattern based validator for the Driving License numbers across various European countries (United Kingdom, Germany, France, Denmark, Holland, Italy, Ireland, Spain). Out of this list, on the web I could get some insight only into the UK DL format, but could not find any information on the patterns for the other countries' DLs. Can anyone provide any information about the Driving License number pattern for these countries?

By the way, this is where I got the pattern for UK (England, Scotland and Wales) DLs. Am looking for similar stuff for the other countries too.

lundi 28 décembre 2015

How to test a class that sets up its properties on constructor?

I have a lot of classes implementing some interfaces and I built some classes that "coordinates" the usage. So, I created a base class that contains the orchestration, and built a class for each combination of these interface implementations that I needed. Something like this:

public abstract class BaseDirector
{
   public IInterfaceA A { get; set; }
   public IInterfaceB B { get; set; }

   public virtual void Do()
   {
      A.Do();
      B.Do();
   }
}

public class Director1: BaseDirector
{
   public Director1()
   {
      A = new A1();
      B = new B2();
   }
}

public class Director2: BaseDirector
{
   public Director2()
   {
      A = new A2();
      B = new B12();
   }
}

It smells bad and I don't see how I can test this. Can someone give some directions on how to test this? Do I need to change the approach on "director" classes?

Passing arguments to multiple functions

I have 2 general questions about function programming.

Consider the following 3 functions:

result = fun3(fun2(fun1(param1))); // param4

function fun1(param1) {
    // ...
    return param2;
}
function fun2(param2) {
    // ...
    return param3;
}
function fun3(param3) {
    // ...
    return param4;
}

Each function expects 1 parameter, does some computation and returns a variable.
In my case, every subsequent function relies on the output of the preceding function.

  1. Is the solution in my example a common practice? Or are there better ways?
  2. What if a function produces 2 outputs and 2 different functions need them?

Like in this example:

function fun1(param1) {
    // ...
    return param2, param3;
}
function fun2(param2) {
    // ...
    return param4;
}
function fun3(param3) {
    // ...
    return param5;
}


PS: Although this is a general programming questions, maybe it could be important to mention, that I use PHP.

Design pattern for device data link

I have three types of devices (USB, COM and wireless) and one PC software to connect with them. Every device have functions like connect, read and write data from RS485 network. On PC software I must implement application layer classes to work with devices. I am looking for some design pattern to write connection between application layer and transport layer. The first idea is to write abstract class DataLink and every device will inherit from the abstract class interface (pure OOP):

class DataLink {
    public:
    virtual bool read() = 0;
    virtual bool write() = 0;
};

class USBDevice : public DataLink {
    public:
    bool read() { /* some code */ }
    bool write() { /* some code */ }
    bool specificUSBFunction() { /* some code */ }
};

class COMDevice : public DataLink {
    public:
    bool read() { /* some code */ }
    bool write() { /* some code */ }
    bool specificCOMFunction(){ /* some code */ } 
};

DataLink *dl = new COMDevice();
dl->read();
dl->write();

Now if I want to use specific USB or COM function I must use ugly cast. The other problem is that this class must be singleton because we have only one device available so we cannot create multiple objects. I am looking for a good way to do this using C++ (can be v11 or v14).

How to get number of concrete classes from factory pattern?

Factory pattern usually creates a base class for the concrete classes and the concrete classes then inherit from that base class. For a lot of applications, we need to know the number of the concrete classes this factory can create. For instance, a factory that creates the typical Shape objects (circle, rectangular, etc.) C# code example below:

public class ShapeFactory
{
    public IShape GetShape(int shapeIndex)
    {
        IShape s = null;

        switch (shapeIndex)
        {
        case 1: s = new Square(name);
            break;
        case 2: s = new Triangle(name);
            break;
        case 3: s = new Circle(name);
            break;
        }

        return s;
    }
}

The user may want to know how many kinds of shapes are supported by the program. I know 2 ways to do this:

  1. Set the number as a constant in the factory class and make it visible to public. The drawback is that every time you add a new Shape, you have to manually increase the number of shapes.
  2. Create a dynamic container (List in C#) that contains all instances of the concrete objects the factory can create. The advantage is that it can automatically figure out the number of Shapes it can create, even if new Shape classes are added. The drawback is obvious, every kind of Shapes have to be created together with the Shape requested!

What is the best way to do this? Any best practice on this specific topic?

Implementing Strategy pattern instead of several if statements

I have this method with lot of if statements, in which I'm filtering SharePoint list based on employee position.The result is query string which is passed as parameter to another method QuerySPList.

 public List<Phone> GetListOfPhones(Employee emp)
 {
    List<Phone> records = new List<Phone>();
    string query = string.Empty;

    if (emp.Positions.Count == 1 && emp.Positions[0] == "Regular")
    {
       query = "";// some querystring                              
    }


    if (emp.Positions.Count == 1 && emp.Positions[0] == "OfficeDirector")
    {   
       query = "";// some querystring    
    }

    if (emp.Positions.Count == 1 && emp.Positions[0] == "Admin")
    {
        query = "";// some querystring 
    }              

    if (emp.Positions.Count == 2 && emp.Positions.Contains("Regular") && emp.Positions.Contains("OfficeDirector"))
    {

      query = "";// some querystring 

     }

   var rawItems = QuerySPList(query);

   foreach (SPListItem item in rawItems)
   {
        //business logic 
   }
   return records;
}}

I've read that with implementing strategy pattern we can avoid messy code with lot of if's , however , I'm new to developing , and design patterns , so I need little help with this one,so if someone can guide me what should I do and give me advice , feel free to answer my question.I have idea , but I think that I'm going in the wrong direction. Idea is to create interface IRoleHandler and than implement it to 3 classes , for example RoleAdmin ,RoleRegular,RoleOfficeDirector.Something like this :

public interface IRoleHandler<T>
{
    string handleRole(T obj);
}
public class RoleAdmin:IRoleHandler<Employee>
{

    public string handleRole(Employee emp)
    {
        if (emp.Positions.Count == 1 && emp.Positions[0] == "Admin")
        {
            //return some string query
        }

    }
}

Then idea is to create dictionary,something like this :

Dictionary<string, IRoleHandler<Employee>> strategyHandlers = new Dictionary<string, IRoleHandler<Employee>>();
        strategyHandlers.Add("Admin", new RoleAdmin());
        strategyHandlers.Add("Regular", new RoleRegularUser());

Data link design pattern

I have three types of devices (USB, COM and wireless) and one PC software to connect with them. Every device have functions like connect, read and write data from RS485 network. On PC software I must implement classes application layer classes to work with devices. I am looking for some design pattern to write connection between application layer and transport layer. The first idea is to write abstract class DataLink and every device will inherit from the abstract class interface. I am looking for a better way to do this. I am using c++ v11.

How to create object based on boolean condition?

I have an Item object having 4 String fields and 3 boolean fields. I have to construct this object based on the 3 boolean variables. The target is whenever any one of the boolean variable is true we have to create the object having that/those boolean variable set. If for any situation none of the boolean variables are true, we wont create the object. I am using a COR to check whether any of the boolean fields will be set or not based on some business logic. I was trying this with builder, but then I have to construct so many objects and later discard them when none of the boolean variables found true.

Can anyone have any better idea, to solve this kind of problem ?

java object designing help for ETL process

I am designing an ETL process where E ->Extractor : which is source and Transformer which transform content and Loader : is output where data to send/ store . I want all must be configurable means If currently source is file in future it can be database also same for output in future it can be database so class/object design should support this

I have following hierarchy of class 

public interface DataSource
{
public void init();
public Object getNextRecord();  
}

//I want to return generic result from getNextRecord 

public class FileSource implements DataSource
{
    public Object getNextRecord();
    {
        return file.readLine();     // one by one return file contains     
    }
}

public class SQLSource implements DataSource
{
    public Object getNextRecord();
    {
        Object[] result = new Object[colssize];
        for (int i = 0; i < cols; i++)
          result[i] = rs.getObject(i + 1);  

        return result: // return one row as object array        
    }
}

public interface Loader
{
    public void addRecord(Object object);
}

public class fileLoader
{
    public void addRecord(Object object)
    {
        writeLineToFile((String) object);
    }
}

public class SQLLoader implements Loader
{
    public void addRecord(Object object)
    {

// problem here getting object array and don't know the tables details writeObjectToDB(object) } } public class CapitalizedFileTransformer {

    @Override
    public void transform(DataSource source, Loader loader)
    {

    // for file source and file loader this works like this
        String data = null;
        while ((data = (String) source.getNextRecord()) != null)
        {
            loader.addRecord(data.toUpperCase());
            loader.addRecord("\n");
        }
        source.close();
        loader.close();


    // but for sql source and sql loader I have problem
    because its returning object array also don't have table info here to which I have to insert and don't want to change code of CapitalizedFileTransformer 
    }
}

It will be great if anyone can help me to re-design this classes I want a source and loader and transformer to be generic i.e any file source should work with sql loader and with any transformer

Which pattern would you suggest for handling those events?

I'm trying to improve my code, and i think i found something that I could manage better, but Even after watching lots video about patterns design i still have doubt on how to modify my source code.

In my software i have a certain JPanel which contains some JComponents. These JComponents have a MouseAdapter that fires events on mouseClick and MouseHover (both entered and exited). The thing is: when a mouseClick is fired the related JComponent enters in the "Edit status", and when one JComponent is in this status, the others do not have to fire their events.

to achieve this kind of behave, i added a boolean to the JComponents container, which is modified by those events, and each events check its status before doing anything. It works as expected, but i m sure there is something more clever to implement this kind of behaviour.

Here is a sample code, and 2 images of the tool:

img 1

img 2

Main Class:

public class Main {
    public static void main(String[] args)  {   
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){           
                JFrame myFrame= new MyFrame();
                myFrame.setVisible(true);
            }
        });     
    }
}

Code JFrame:

public class MyFrame extends JFrame{

    private  boolean onEdit;
    private MyComponent myComp1;
    private MyComponent myComp2;
    private MyComponent myComp3;
    private MyComponent myComp4;

    public MyFrame(){
        super.setTitle("MyFrame");
        super.setPreferredSize(new Dimension(400,400));
        super.setLocationRelativeTo(null);
        super.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        super.setLayout(new GridBagLayout());
        onEdit = false;
        initComponents();
        addComponents();
        super.pack();
    }

    private void initComponents() {
        myComp1 = new MyComponent(this);
        myComp2 = new MyComponent(this);
        myComp3 = new MyComponent(this);
        myComp4 = new MyComponent(this);
    }

    private void addComponents() {
        Container myContainer = getContentPane();
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 0;
        gbc.gridy = 0;
        myContainer.add(myComp1,gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        myContainer.add(myComp2,gbc);

        gbc.gridx = 1;
        gbc.gridy = 0;
        myContainer.add(myComp3,gbc);

        gbc.gridx = 1;
        gbc.gridy = 1;
        myContainer.add(myComp4,gbc);
    }

    public void setOnEdit(boolean toggle){
        onEdit = toggle;
    }

    public boolean isOnEdit(){
        return onEdit;
    }

}

Code JComponents:

public class MyComponent extends JComponent{

    private MyFrame mainFrame;

    public  MyComponent(MyFrame myFrame){
        mainFrame = myFrame;
        this.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
        this.setLayout(new FlowLayout(FlowLayout.LEFT));
        this.setPreferredSize(new Dimension(100,50));
        this.add(initTextField());
        this.add(initCheckBox());
        this.addMouseListener(new MyComponentMouseListener(this));
        this.addKeyListener(new MyComponentKeyListener(this));
    }

    private JFormattedTextField initTextField() {
        NumberFormat myFormat = NumberFormat.getInstance();
        JFormattedTextField text = new JFormattedTextField(myFormat);
        text.setDisabledTextColor(Color.BLACK);
        text.setColumns(5);
        text.addMouseListener(new MouseEventDispatcher());
        text.addKeyListener(new KeyEventDispatcher());
        text.setEnabled(false);
        return text;
    }

    private JCheckBox initCheckBox() {
        JCheckBox check = new JCheckBox();
        check.addMouseListener(new MouseEventDispatcher());
        check.addKeyListener(new KeyEventDispatcher());
        check.setEnabled(false);
        return check;
    }

    public MyFrame getMainFrame() {
        return mainFrame;
    }

    public void saveEdit() {
        /**not relevant for the example*/
    }

    public void resetEdit() {
        /**not relevant for the example*/
    }

}

class MouseEventDispatcher extends MouseAdapter{
    @Override 
    public void mouseEntered(MouseEvent e) {
        dispatchMouseEvent(e);
    }

    @Override 
    public void mouseExited(MouseEvent e) {
        dispatchMouseEvent(e);
    }

    @Override
    public void mouseClicked(MouseEvent e){
        dispatchMouseEvent(e);
    }

    private void dispatchMouseEvent(MouseEvent event) {
        Component source = event.getComponent();
        Component destination = SwingUtilities.getUnwrappedParent(source);
        MouseEvent mouseEvent = SwingUtilities.convertMouseEvent(source, event, destination);
        destination.dispatchEvent(mouseEvent);
    }
}

class KeyEventDispatcher extends KeyAdapter{
    public void keyPressed(KeyEvent e) {
        if(EnterPressed(e) || EscPressed(e)){
            dispatchKeyEvent(e);
        }
    }

    private boolean EnterPressed(KeyEvent e) {
        return e.getKeyChar() == KeyEvent.VK_ENTER;
    }

    private boolean EscPressed(KeyEvent e) {
        return e.getKeyChar() == KeyEvent.VK_ESCAPE;
    }

    private void dispatchKeyEvent(KeyEvent event) {
        Component source = event.getComponent();
        Component destination = SwingUtilities.getUnwrappedParent(source);
        destination.dispatchEvent(event);
    }
}

Code MouseAdapter :

public class MyComponentMouseListener extends MouseAdapter {

private MyComponent myComponent;

    public MyComponentMouseListener(MyComponent comp){
        myComponent = comp;
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        if(!myComponent.getMainFrame().isOnEdit()){
            myComponent.setBorder(BorderFactory.createLineBorder(Color.GREEN));
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        if(!myComponent.getMainFrame().isOnEdit()){
            myComponent.getMainFrame().setOnEdit(true);
            myComponent.setBorder(BorderFactory.createLineBorder(Color.RED));
            myComponent.getComponent(0).setEnabled(true);
            myComponent.getComponent(1).setEnabled(true);
            myComponent.getComponent(0).requestFocus();
        }
    }

    @Override
    public void mouseExited(MouseEvent e) {
        if(!myComponent.getMainFrame().isOnEdit()){
            Rectangle componentArea = e.getComponent().getBounds();
            Point cursorPosition = e.getPoint();
            if(cursorIsOut(cursorPosition,componentArea)){
                myComponent.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
            }
        }
    }

    private boolean cursorIsOut(Point p, Rectangle r) {
        return p.x < 0 || p.y < 0 || p.x >= r.width || p.y >= r.height;
    }

}

Code KeyAdapter:

public class MyComponentKeyListener extends KeyAdapter {

    private MyComponent myComponent;

    public MyComponentKeyListener(MyComponent comp){
        myComponent = comp;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if(EnterPressed(e)){
            saveChanges(e);
        }
        if(EscPressed(e)){
            cancelChanges(e);
        }
    }

    private boolean EnterPressed(KeyEvent e) {
        return e.getKeyChar() == KeyEvent.VK_ENTER;
    }

    private boolean EscPressed(KeyEvent e) {
        return e.getKeyChar() == KeyEvent.VK_ESCAPE;
    }

    private void cancelChanges(KeyEvent e) {
        myComponent.resetEdit();
        exitEdit();
    }

    private void saveChanges(KeyEvent e) {
        myComponent.saveEdit();
        exitEdit();
    }

    private void exitEdit() {
        myComponent.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
        myComponent.getComponent(0).setEnabled(false);
        myComponent.getComponent(1).setEnabled(false);
        myComponent.requestFocus();
        myComponent.getMainFrame().setOnEdit(false);
    }

}

Thanks for any suggestion!

dimanche 27 décembre 2015

Is there a commonly accepted design pattern for base methods implementing "early exit" functionality?

I have a class hierarchy of patterns: patterns are split into simple patterns and compound patterns, both of which have concrete implementations.

Patterns have a Match method which returns a Result, which can be a Node or an Error.

All patterns can check for a memoized result when matching. Simple patterns return an error on EOF.

Is there a pattern that allows a more simple way to reuse implemented functionality than mine? Let's say we're using a single-inheritance, single-dispatch language like C# or Java.

My approach is to implement Match at pattern level only and call a protected abstract method InnerMatch inside it. At simple pattern level, InnerMatch is implemented to handle EOF and calls protected abstract InnerInnerMatch, which is where concrete implementations define their specific functionality.

I find this approach better than adding an out bool handled parameter to Match and calling the base method explicitly in each class, but I don't like how I have to define new methods. Is there a design pattern that describes a better solution?

Connector design pattern?

I want to connect several classes which are functioning separately but are related.

Lets say I am writing an app in which you can swipe to draw a chart. There are lots of classes in the app which are related and should be connected.

For example three of the classes are:

Swiper - responsible for interpreting the gesture of the user

Points - responsible for handling the points on the chart

ChartDrawer - responsible for drawing the chart on the screen

I want to know is there any design pattern such as a connector which can handle the relation and communication of these classes? Any way i can redesign in a better way or make mind more object oriented?

Sorry if too broad...

Strategy to handle Nearby Messages API - Android

I am currently working on an messaging application for Android that communicates with other devices using Nearby Messages API. Since this is the first time that I work with this API, I would like to know if there is a pattern or strategy to handle the connections.

For instance, when the user changes the activity (e.g. opens a new conversation), I would like to keep the connection active, so I would like to work with a Connection Manager or something to keep listening and parsing the messages.

Extending the PDO class and connection issues

So I designed a system that extends the PDO class as such...

class PdoConfig extends PDO {

    private $engine;
    public $host;
    public $database;
    public $user;
    public $pass;

    public function __construct(){

        // DB CONFIG
        if (DEVELOPMENT) {
            $dbhost = 'localhost';$dbuser = 'blah';$dbpass = 'blah';$dbname = 'blah';
        } elseif (STAGING) {
            $dbhost = '199.79.xxx.xxx';$dbuser = 'blah';$dbpass = 'blah';$dbname = 'blah';
        } else {
            $dbhost = '199.79.xxx.xxx';$dbuser = 'blah';$dbpass = 'blah';$dbname = 'blah';
        }

        $this->engine = 'mysql';
        $this->host = $dbhost;
        $this->database = $dbname;
        $this->user = $dbuser;
        $this->pass = $dbpass;
        $dsn = $this->engine.':dbname='.$this->database.";host=".$this->host;
        self::__construct( $dsn, $this->user, $this->pass );

    }

    public function reconnect() {

      try {
        $this->query('SELECT 1');
      } catch (PDOException $e) {
        $dsn = $this->engine.':dbname='.$this->database.";host=".$this->host;
        self::__construct( $dsn, $this->user, $this->pass );
      }

      return true;   

    }


}

and then I use this PDOConfig class as the base class for all my model classes that require DB access, as such...

class dbHealthNewsContent extends PdoConfig { ... }
class dbHealthVideoContent extends PdoConfig { ... } etc

this has allowed me to make db queries where the PDO connections and statements are part of the class ie

public function get_fbmessage () {

    $article_id = $this->row['id'];

    $sql = "SELECT fb_message FROM fb_post 
                WHERE article_id = $article_id LIMIT 1";

    $stm = $this->prepare($sql);
    $stm->execute();    

    if ($stm->rowCount() == 1) { ... }
}

and it's worked quite well up to now.

So the issue is that due to the popularity of the app, we are determining that too many connections are being made and performance is suffering and I have been trying to figure out how to make the PDOConfig class into either a global, sharable object or a singleton class, but without returning an "instance" and rather using a shared PDO connection within the class, transparent to all the derived classes.

Basically, I am trying to do a refactor by fixing the issues within the class itself and not having to go thru the entire codebase, changing all the superclass models.

Any insights or comments welcome.

Which design pattern to use to improve this Java program

I write a program to parse an XML file to get a specific tag value named SerialNum which is contained in a Header tag. The file is constructed as below:

  • it contains 1 Header and 1 Body
  • the Header may contains many SerialNum tags. We need to extract the value of the last tag.

I used the Stax parser to get the SerialNum value, and I wrote this code:

public String findIdValue(HttpServletRequest request) {

    String serialNumberValue = null;

    if(request != null){
        ServletInputStream servletInstream;
        try {
            servletInstream = request.getInputStream();
            XMLInputFactory factory = XMLInputFactory.newInstance();
            XMLStreamReader xmlStreamReader = factory.createXMLStreamReader(servletInstream);
            //begin parsing if we get <Header>
            //end parsing if we get <Header/> or </Header>

            int event = xmlStreamReader.getEventType();
            boolean enableToParse = false;
            boolean gotSerialNumber = false;
            boolean parseComplete = false;

            while( (xmlStreamReader.hasNext()) && (!parseComplete) ){
                switch(event) {
                case XMLStreamConstants.START_ELEMENT:
                    if("Header".equals(xmlStreamReader.getLocalName())){
                        //tag is header, so begin parse
                        enableToParse = true;
                    }else if(("SerialNum".equals(xmlStreamReader.getLocalName())) && (enableToParse) ){
                        //tag is serialNum so enable to save the value of serial number
                        gotSerialNumber = true;
                    }
                    break;
                case XMLStreamConstants.CHARACTERS:
                    //get serial number and end the parsing
                    if(gotSerialNumber){
                        //get wsa and end the parsing
                        serialNumberValue = xmlStreamReader.getText();
                        gotSerialNumber = false;
                        parseComplete= true;
                    }

                    break;
                case XMLStreamConstants.END_ELEMENT:
                    //when we get </Header> end the parse
                    //when we get </SerialNum> reinit flags
                    //when we get </Header> end the parse even we don't get a serial number
                    if("Header".equals(xmlStreamReader.getLocalName())){
                        parseComplete= true;
                    }else if("SerialNum".equals(xmlStreamReader.getLocalName())){
                        //reinit flag when we get </SerialNum> tag
                        gotSerialNumber = false;
                    }
                    break;
                default:
                    break;
                }
                event = xmlStreamReader.next();
            }


        } catch (final XMLStreamException e) {
            //catch block
            LOG.info("Got an XMLStreamException exception. " + e.getMessage());
        }
        catch (final IOException e1) {
            //catch block
            LOG.info("Got an IOException exception. " + e1.getMessage());
        }

    }


    return serialNumberValue;
}

This code extract the needed value but the code quality is not very good: it is not easy to read and maintain. It contains a switch case and if else blocks nested in a while loop. Which design pattern to use to enhance the code quality?

I want to Design a simple ETL process where source and output and transformation all three needs to be independent

I want to Design a simple ETL process where source and output and transformation all three needs to be independent i.e source can be a file and output to database and transformation logic must me plugaable. Could any one please help me to design classes where every thing should be dynamic and plugable . ex Extract / input source : read from a file

//future input source can be dbms also

transform : transform file content to capital form.

// this can be easily changeable

Load / output source : put above transform content to a file

/// future output source can be dbms also

Need help in designing classes in java which supports all this. I can use strategy pattern to plug strategy but all three but not able to do it

Codeigniter windows server web.config - how to escape .jpg or images files from url

I have a codeigniter website in a Windows server and it seems to be working well after I used the web.config file. But the the problem is that i cannot pass .jpg files in the url. There is a function to delete image in my admin section as follows;

http://ift.tt/1ShsLEd

Which returns me a 404 not found error.

If I remove '|jpg|jpeg|png|gif|' from the pattern {REQUEST_FILENAME} of web.config , the delete function work, but no images are displayed in the website at all.

 <rule name="Rewrite to index.php">
                    <match url="index.php|robots.txt|images|test.php" />
                    <action type="None" />
                </rule>
                <rule name="Rewrite CI Index">
                    <match url=".*" />
                    <conditions>
                        <add input="{REQUEST_FILENAME}" pattern="^.+\.(css|js|jpg|jpeg|png|gif|ico|htm|html|eot|woff|ttf|svg|txt|pdf|swf)$" negate="true" />
                    </conditions>
                    <action type="Rewrite" url="index.php/{R:0}" />
                </rule>

is there a workaround for this. Many thanks for checking it.

samedi 26 décembre 2015

A table left outer joining with itself: How does this work?

I'm reading the book SQL Antipatterns and trying to understand its example of building a "tree" with a self-referential table such as

                         Comments
-------------------------------------------------------------------
  comment_id | parent_id | author |      comment
-------------------------------------------------------------------
       1          NULL     Fran      What's the cause of this bug?
       2            1      Ollie     I think it's a null pointer.
       3            2      Fran      No, I checked for that.
       4            1      Kukla     We need to check for invalid input.
       5            4      Ollie     Yes, that's a bug.
       6            4      Fran      Yes, please add a check.
       7            6      Kukla     That fixed it.

So the book says

You can retrive a comment and its immediate children using a relatively simple query:

SELECT c1.*, c2.*
FROM Comments c1 LEFT OUTER JOIN Comments c2
  ON c2.parent_id = c1.comment_id

I'm trying to understand how this works. The way I've always understood left outer joins between a table t1 and t2 is that you take all the rows from t1 and for the rows where the ON clause is not satisfied you fill in NULL for the columns from the second table. In this case there is only one table, but I can imagine that the query is taking place with two tables where the second one is a copy of the first. Still, I don't understand how that query returns

two levels of the tree.

What exactly is the resulting table and can you walk me through the logic of how it is resulted?

Canvas random images in pattern

So far i got the code:

var image = new Image();
image.onload = function() {
  // create an off-screen canvas
  var patt = document.createElement('canvas');
  // set the resized width and height
  patt.width = sirinaopto;
  patt.height = sirinaopto;
  patt.getContext('2d').drawImage(this, 0,0, patt.width, patt.height);
  // pass the resized canvas to your createPattern
      drawBG(patt);
image.src = 'img/e.svg'

//repeat background
function drawBG(patternCanvas) {
      var space = ctx.createPattern(patternCanvas, 'repeat');
      ctx.fillStyle = space;
    ctx.save();
    ctx.translate(zacetek, 0);
      ctx.fillRect(0, 0, ctx.canvas.width,  visina2);
    ctx.restore();
    }

What this does is create pattern with one image "img/e.svg". Lets say I have 4-5 images (e.svg, e1.svg, e2.svg..... ) How could I create the same pattern but use all of the pictures and use them randomly in the pattern? The patern would look simmilar to: e.svg, e3.svg, e.svg, e2.svg.... instead of e.svg, e.svg, e.svg.....

How can a clone can create a new object of 'Singlton' class

I asked this question and got a good solution. And i understand that how an object can be created without new (which i thought the only way to construct an object).

Now i was studying the Design patterns and learned that by creating a Singlton class we force a class to instantiate only once.

// a simple Singlton class.
class Singleton
{
    private static $object = null;
    private function __construct() {}
    public static function createObject()
    {
        if (self::$object == null) {
            self::$object = new Singleton();
        }
        return self::$object;
    }
}

Now i instantiate this class.

//$obj = new Singleton(); Obviously an error

$obj1 = Singleton::createObject();
// object(Singleton)[1]

$obj2 = Singleton::createObject();
// object(Singleton)[1]
// $obj1 and $obj2 are same. Both have same id = 1

$obj3 = clone $obj1;
// object(Singleton)[2]
// $obj3 is a new  instantiate. id = 2

So my question is how is this happening. how does the clone work here.
i wish php have an singlton keyword to create singlton class. :)

Swift: conforming to protocol using extension and composition pattern

On slide 62 in this PDF: Some Columbia College Presentation it says that one of the ideas behind Swift and its extensions was to conform to protocols using the composition pattern.

Now I understand the syntax for extensions in Swift

//example from Apple:
extension SomeType: SomeProtocol, AnotherProtocol {
// implementations of not yet provided functions and properties of SomeType go here
}

But what does the composition pattern have to do with it? The guy did mean the composite pattern described here, right? Can someone please provide a minimal example how it is used?

CodeSys 2.3 State Machine

What is the best way to make efficient and flexible state state machine(SM) in IEC61131-3 / CodeSyS v2.3? Are there any good examples of SM realizations on CodeSys V2.3?

As far as I understand, there are 3 different types of SM:

1.Case logic SM - simple, just change states based on if logic, not flexible at all, hard to maintain.

2.Table driven SM - better, but without function pointers there is need in additional conditional instructions to run some actions based on current state.

3.State Design Pattern SM - best option, flexible, no huge CASE statements, no duplication.

I am trying to adopt C State Design Patter by Adam Tornhill: http://ift.tt/1R16o4J But it is quite hard to translate from plain C to Structural Text. CodeSys has support for Function Block pointers but I can't figure out how to declare incomplete pointer type in ST (is it even possible?):

/*C-style incomplite state pointer*/
typedef struct State* StatePtr;

struct State
{
   EventFunc exampleFunc1;
   EventFunc exampleFunc2;
}

{ST-style incomplite state pointer ???}
TYPE Sm_state_t :
STRUCT
State:POINTER TO ???;
END_STRUCT
END_TYPE

Design pattern for message packet header

I am writing my own messaging API using libevent. The data is wrapped by a packet structure which contains a packet body of data byte array and a packet header that contains the entire packet size information (for the reason to invoke callback at a complete stream).

class PacketHeader {
  size_t packet_size;
};

class Packet {
  PacketHeader header;
  uint8_t* body;
};

However, I wanna users be able to customize their own PacketHeader, while I can handle the underlying size information for messaging. What is the best practice to do this? Should I use inheritance or pure virtual abstraction (interface class). I was thinking about the following but not sure if it is the best practice.

template <class Derived>
class PacketHeader{
  size_t packet_size;
  size_t header_size() const {return sizeof(Derived);}
}

vendredi 25 décembre 2015

How to use builder pattern with all parameters as mandatory?

I have a builder pattern in which most likely all my parameters are going to be mandatory so I have created a long constructor as shown below in the code.

public final class ResponseHolder {

    // all below six are related to response information
    private final String response;
    private final boolean isLinking;
    private final TypeHold typeOfId;
    private final long userTimeInMs;
    private final long userLmdInDays;
    private final String maskInfo;

    // below two are related to error handling
    private final ErrorCode error;
    private final StatusCode status;

    private ResponseHolder(Builder builder) {
        this.response = builder.response;
        this.isLinking = builder.isLinking;
        this.typeOfId = builder.typeOfId;
        this.userTimeInMs = builder.userTimeInMs;
        this.userLmdInDays = builder.userLmdInDays;
        this.maskInfo = builder.maskInfo;
        this.error = builder.error;
        this.status = builder.status;
    }

    public static class Builder {
        protected final String response;
        protected final TypeHold typeOfId;
        protected final String maskInfo;
        protected final ErrorCode error;
        protected final StatusCode status;
        protected final boolean isLinking;
        protected final long userTimeInMs;
        protected final long userLmdInDays;


        public Builder(String response, TypeHold typeOfId, String maskInfo, ErrorCode error,
                StatusCode status, boolean isLinking, long userTimeInMs, long userLmdInDays) {
            this.response = response;
            this.typeOfId = typeOfId;
            this.maskInfo = maskInfo;
            this.error = error;
            this.status = status;
            this.isLinking = isLinking;
            this.userTimeInMs = userTimeInMs;
            this.userLmdInDays = userLmdInDays
        }

        public ResponseHolder build() {
            return new ResponseHolder(this);
        }
    }

    // getters here
}

Now I am confuse when all the parameters are mandatory, then how it can be useful? Is there any better way of representing my above Builder pattern? May be logically grouping the parameters being passed in to their own classes to reduce the number of parameters being passed to the builder constructor?

While having separate objects simplifies things quite a bit, it also makes things a little difficult to follow if one is not familiar with the code. One thing I can do is moving all parameters into their own addParam(param) methods and then performing validation on required parameters in the build() method at runtime?

What is best practice I should follow here and is there any better approach that I can use here?

Improve builder pattern on validation check?

I recently started using Builder pattern in one of my projects and I am trying to add some sort of validations on my Builder class. I am assuming we cannot do this at compile time so that's why I am doing this validation at runtime. But may be I am wrong and that's what I am trying to see whether I can do this at compile time.

public final class RequestKey {

    private final Long userid;
    private final String deviceid;
    private final String flowid;
    private final int clientid;
    private final long timeout;
    private final boolean abcFlag;
    private final boolean defFlag;
    private final Map<String, String> baseMap;

    private RequestKey(Builder builder) {
        this.userid = builder.userid;
        this.deviceid = builder.deviceid;
        this.flowid = builder.flowid;
        this.clientid = builder.clientid;
        this.abcFlag = builder.abcFlag;
        this.defFlag = builder.defFlag;
        this.baseMap = builder.baseMap.build();
        this.timeout = builder.timeout;
    }

    public static class Builder {
        protected final int clientid;
        protected Long userid = null;
        protected String deviceid = null;
        protected String flowid = null;
        protected long timeout = 200L;
        protected boolean abcFlag = false;
        protected boolean defFlag = true;
        protected ImmutableMap.Builder<String, String> baseMap = ImmutableMap.builder();

        public Builder(int clientid) {
            checkArgument(clientid > 0, "clientid must not be negative or zero");
            this.clientid = clientid;
        }

        public Builder setUserId(long userid) {
            checkArgument(userid > 0, "userid must not be negative or zero");
            this.userid = Long.valueOf(userid);
            return this;
        }

        public Builder setDeviceId(String deviceid) {
            checkNotNull(deviceid, "deviceid cannot be null");
            checkArgument(deviceid.length() > 0, "deviceid can't be an empty string");
            this.deviceid = deviceid;
            return this;
        }

        public Builder setFlowId(String flowid) {
            checkNotNull(flowid, "flowid cannot be null");
            checkArgument(flowid.length() > 0, "flowid can't be an empty string");
            this.flowid = flowid;
            return this;
        }

        public Builder baseMap(Map<String, String> baseMap) {
            checkNotNull(baseMap, "baseMap cannot be null");
            this.baseMap.putAll(baseMap);
            return this;
        }

        public Builder abcFlag(boolean abcFlag) {
            this.abcFlag = abcFlag;
            return this;
        }

        public Builder defFlag(boolean defFlag) {
            this.defFlag = defFlag;
            return this;
        }

        public Builder addTimeout(long timeout) {
            checkArgument(timeout > 0, "timeout must not be negative or zero");
            this.timeout = timeout;
            return this;
        }

        public RequestKey build() {
            if (!this.isValid()) {
                throw new IllegalStateException("You have to pass at least one"
                        + " of the following: userid, flowid or deviceid");
            }
            return new RequestKey(this);
        }

        private boolean isValid() {
            return !(TestUtils.isEmpty(userid) && TestUtils.isEmpty(flowid) && TestUtils.isEmpty(deviceid));
        }
    }

    // getters here
}

Problem Statement:

In my above builder pattern, I have only one parameter mandatory clientId and rest of them are optional but I need to have either userid, flowid or deviceid set. If none of those three are set then I am throwing IllegalStateException with an error message as shown above in the code. That check I am doing at runtime. I want to do this check at compile time if possible by any chance and don't build my pattern unless everything is provided?

It is not mandatory that they will pass all those three id's everytime, they can pass all three or sometimes two or sometimes only one but the condition is either one of them should be set.

How can I improve my builder pattern so that I can do id validation at compile time only instead of doing this at runtime?

I found out this SO link which exactly talks about same thing but not sure how can I use it in my scenario? And also this builder pattern with a twist and this SO question

Can anyone provide an example how can I fix this in my builder pattern?

Improving builder pattern by doing validations at compile time

I recently started using Builder pattern in one of my projects and I am trying to add some sort of validations on my Builder class. I am assuming we cannot do this at compile time so that's why I am doing this validation at runtime. But may be I am wrong and that's what I am trying to see whether I can do this at compile time.

Traditional builder pattern

public final class RequestKey {

    private final Long userid;
    private final String deviceid;
    private final String flowid;
    private final int clientid;
    private final long timeout;
    private final boolean abcFlag;
    private final boolean defFlag;
    private final Map<String, String> baseMap;

    private RequestKey(Builder builder) {
        this.userid = builder.userid;
        this.deviceid = builder.deviceid;
        this.flowid = builder.flowid;
        this.clientid = builder.clientid;
        this.abcFlag = builder.abcFlag;
        this.defFlag = builder.defFlag;
        this.baseMap = builder.baseMap.build();
        this.timeout = builder.timeout;
    }

    public static class Builder {
        protected final int clientid;
        protected Long userid = null;
        protected String deviceid = null;
        protected String flowid = null;
        protected long timeout = 200L;
        protected boolean abcFlag = false;
        protected boolean defFlag = true;
        protected ImmutableMap.Builder<String, String> baseMap = ImmutableMap.builder();

        public Builder(int clientid) {
            checkArgument(clientid > 0, "clientid must not be negative or zero");
            this.clientid = clientid;
        }

        public Builder setUserId(long userid) {
            checkArgument(userid > 0, "userid must not be negative or zero");
            this.userid = Long.valueOf(userid);
            return this;
        }

        public Builder setDeviceId(String deviceid) {
            checkNotNull(deviceid, "deviceid cannot be null");
            checkArgument(deviceid.length() > 0, "deviceid can't be an empty string");
            this.deviceid = deviceid;
            return this;
        }

        public Builder setFlowId(String flowid) {
            checkNotNull(flowid, "flowid cannot be null");
            checkArgument(flowid.length() > 0, "flowid can't be an empty string");
            this.flowid = flowid;
            return this;
        }

        public Builder baseMap(Map<String, String> baseMap) {
            checkNotNull(baseMap, "baseMap cannot be null");
            this.baseMap.putAll(baseMap);
            return this;
        }

        public Builder abcFlag(boolean abcFlag) {
            this.abcFlag = abcFlag;
            return this;
        }

        public Builder defFlag(boolean defFlag) {
            this.defFlag = defFlag;
            return this;
        }

        public Builder addTimeout(long timeout) {
            checkArgument(timeout > 0, "timeout must not be negative or zero");
            this.timeout = timeout;
            return this;
        }

        public RequestKey build() {
            if (!this.isValid()) {
                throw new IllegalStateException("You have to pass at least one"
                        + " of the following: userid, flowid or deviceid");
            }
            return new RequestKey(this);
        }

        private boolean isValid() {
            return !(TestUtils.isEmpty(userid) && TestUtils.isEmpty(flowid) && TestUtils.isEmpty(deviceid));
        }
    }

    // getters here
}

Problem Statement:

As you can see I have various parameters but only one parameter clientId is mandatory and rest of them are optional. In my above code, I need to have either userid, flowid or deviceid set. If none of those three is set then I am throwing IllegalStateException with an error message as shown above in the code. If all three or two is set then it's fine and I am doing some priority logic on those three or two to decide which one to use but atleast one of them has to be set.

It is not mandatory that they will pass all three id's everytime, they can pass all three or sometimes two or sometimes only one but the condition is either one of them should be set.

What I am looking for is - Instead of doing all these things at runtime, can I do this at compile time and don't build my builder pattern unless either of these three is set and at compile time it should tell what is missing?

I found out this SO link which exactly talks about same thing but not sure how can I use it in my scenario? And also this builder pattern with a twist and this SO question

How to break and improve cyclic dependency without using proxy pattern?

My classes are depending upon too many other classes and I couldnot find ways to improve it. The problem goes something like below:

I have a ProductRepo, ProductFactory and a ImageFactory classes. ProductRepo does the db thing on products table and fetches rows as array. This array is passed to ProductFactory to create a Product Modal. Product modals also has images linked to it.

client code:

$products = $this->productRepo->findAll('...');
foreach($products as $product){
    ...
    //get images
    $images = $product->getImages();
    ...
}

Class ProductRepo implements ProductRepositoryInterface{
    protected $productFactory;
    protected $imageFactory;
    public function __construct(ProductFactoryInterface $productFactory, ImageFactoryInterface $imageFactory)
    {
        $this->productFactory = $productFactory;
        $this->imageFactory = $imageFactory;
    }

    public function findAll(...)
    {
        $result = $this->execute('....');
        $products = $this->productFactory->make($result);
        return $products;
    }

    public function getImages($productId)
    {
        $result = $this->execute('....');
        $images = $this->imageFactory->make($result);
        return $images;
    }
}

Class ProductFactory implements ProductFactoryInterface{
    protected $productRepo;
    public function __construct(ProductRepositoryInterface $productRepo)
    {
        $this->productRepo = $productRepo;
    }

    public function make($items)
    {
        ...
        $products = [];
        foreach($items as $item){
            $product = new Product($item);
            $item->setImages($this->productRepo->getImages($product->getId()));
            $products[] = $product;
        }
        ...
        return $products;
    }
}

Class ImageFactory implements ImageFactoryInterface{
    public function make($items)
    {
        ...
        $images = [];
        foreach($items as $item){
            $image = new Image($item);
            $images[] = $image;
        }
        ...
        return $images;
    }
}

So, I have following problems:

  1. cyclic dependency ProductRepo --> ProductFactory --> ProductRepo

    To skip this, I can use a setter injection or use a proxy pattern. But I think that would not a good solution. How do you guys handle this kind of problems?

  2. ProductRepo depends on both the ProductFactory and ImageFactory. Is this a good practise to depend on more than one factory?

I think the problems are clear. :) Thank you

Validation Check is always 0 Matlab

I used matlab and use pattern recognition The problem is , after when im trying to train system, in the result in my

validation Check

is a 0(zero),always ,with my data set. Is that ok ? or validation check must change and upper than 0 ?

jeudi 24 décembre 2015

Changing RegEx pattern during the using of program from textBox

I just need to know, how to change RegEx pattern during the using of program. I mean. Changing of pattern from text Box, I was trying, but, I cannot find the answer. Simple string value doesn't work, then I really don't know what...

public class LinkExtractor
    {
        public static List<string> Extract(string html)
        {
            List<string> list = new List<string>();
            Regex regex = new Regex("(?:href|src)=[\"|']?(.*?)[\"|'|>]+", RegexOptions.Singleline | RegexOptions.CultureInvariant);
            if (regex.IsMatch(html))
            {
                foreach (Match match in regex.Matches(html))
                {
                    list.Add(match.Groups[1].Value);
                }
            }

            return list;
        }
    }

Design Pattern in Bound Service?

I am exploring the Bound services in Android. I came across below line in Android developer documentation about the Bound service.

Multiple clients can connect to the service at once. However, the system calls your service's onBind() method to retrieve the IBinder only when the first client binds. The system then delivers the same IBinder to any additional clients that bind, without calling onBind() again.

As mentioned here, it seems Android system is using an already existing IBinder to return to additional clients.

Is this implementation is loosely based on concept of Flyweight Design pattern? As we know, Flyweight pattern is primarily used to reduce the number of objects created and to decrease memory footprint and increase performance.

How this is actually achieved?

how to think about this... (design pattern)

I am building a multimedia organizer to track the media that i have

here is the object hierarchy:

-MediaObject (root parent)

--EpisodeSequence:

---Season

---Show

---Arc

--Episode

The above interacts differently with other MediaObject. e.g. a Season can have an Arc as it's child, but can't have a Show. e.g. a Show can have any MediaObject as it's child:

enter image description here

in addition, a specific MediaObject can be initiated in different ways. You can add the file directly (as a file path), add a virtual file (tracking things that you are watching online), or even generate the file name automatically from the "last watched" index.

enter image description here

i want to enforce these rules and i don't know how to do this.

my best guess is to use a factory to create (or reject the creation of) whatever MediaObject i want and pass the factory a MediaObjectSC (Media Object Search Criteria) that contains all the info i will ever need to create whatever MediaObject. The downside is that MadiaObjectSC will look like an abomination (with a lot of useless fields) and the factory will be too complicated (in my opinion)

from the above, i can see that i am missing a lot of insight on the matter. Any further guidance is much appriciated.

Why should I use MVP pattern in GWTP application?

I've implemented such an architecture for two times, so haven't realised real profits it gives.

All I obtained is code of View, separated in two places. Most of the methods contain lines of code like getView().* In additional there are at least two additional entities: class *Presenter and interface *UiHandler

Do I something wrong?

mercredi 23 décembre 2015

Java SE / Maven - Clever way to implement "plug and play" for different library modules

I'm trying to do something clever. I am creating a weather application in which we can replace the weather API with another weather API without affecting the code base. So I started with a Maven project with multiple modules.

I have a Base module that contains the Interface class and the Base class. The Interface class contains the calls to the APIs (all calls are similar, if not exact) and the Base class contains the properties to the APIs (again, all properties are similar, if not exact).

I have a module for each of the two weather APIs we are testing with plans to create more modules for new weather APIs as we grow the application.

Finally, I have created a Core module (includes main) to implement the specific module class for the weather API I want to test.

Now, I know the simplest way to do this would be to use a switch statement and enumeration. But I want to know if there is a more clever way to do this. Maybe using a Pattern? Any suggestions?

Here is a picture of the structure I have just described:

enter image description here

Here is the UML representation:

enter image description here

This is a learning process for me. I want to discover how a real Java Guru would implement the appropriate module and class based on a specified configuration.

Thank you for your suggestions.

WPF Button Command Pattern :Interpret to UML diagram to show actors

Command Pattern UML

I am newbie in WPF programming world. I have studied Command pattern and I understood it encapsulates a request(any kind of action) and execution can be given to other entity(invoker).

Recently I have been asked interview question showing like above command pattern UML diagram and they asked me to compare with WPF Button class and tell who is Invoker ,who is client, who is receiver, where is command, and where is ICommand.They asked me explain with wpf button and rename all actors on that UML diagram .

I renamed client as button. ViewModel as Receiver, but could not explain invoker, Concrete command. As per command pattern client will create command will give to receiver but in terms of WPF button ... button and view model are totally decoupled.

Would some help me to understand this?

Storing and loading configuration for REST server avoding global state (i.e. singleton vs. context vs. dependency injection)

I am developing an architecture in Java using tomcat and I have come across a situation that I believe is very generic and yet, after reading several questions/answers in StackOverflow, I couldn't find a definitive answer. My architecture has a REST API (running on tomcat) that receives one or more files and their associated metadata and writes them to storage. The configuration of the storage layer has a 1-1 relationship with the REST API server, and for that reason the intuitive approach is to write a Singleton to hold that configuration.

Obviously I am aware that Singletons bring testability problems due to global state and the hardship of mocking Singletons. I also thought of using the Context pattern, but I am not convinced that the Context pattern applies in this case and I worry that I will end up coding using the "Context anti-pattern" instead.

Let me give you some more background on what I am writing. The architecture is comprised of the following components:

  • Clients that send requests to the REST API uploading or retrieving "preservation objects", or simply put, POs (files + metadata) in JSON or XML format.

  • The high level REST API that receives requests from clients and stores data in a storage layer.

  • A storage layer that may contain a combination of OpenStack Swift containers, tape libraries and file systems. Each of these "storage containers" (I'm calling file systems containers for simplicity) is called an endpoint in my architecture. The storage layer obviously does not reside on the same server where the REST API is.

The configuration of endpoints is done through the REST API (e.g. POST /configEndpoint), so that an administrative user can register new endpoints, edit or remove existing endpoints through HTTP calls. Whilst I have only implemented the architecture using an OpenStack Swift endpoint, I anticipate that the information for each endpoint contains at least an IP address, some form of authentication information and a driver name, e.g. "the Swift driver", "the LTFS driver", etc. (so that when new storage technologies arrive they can be easily integrated to my architecture as long as someone writes a driver for it).

My problem is: how do I store and load configuration in an testable, reusable and elegant way? I won't even consider passing a configuration object to all the various methods that implement the REST API calls.

A few examples of the REST API calls and where the configuration comes into play:

// Retrieve a preservation object metadata (PO)
@GET
@Path("container/{containername}/{po}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public PreservationObjectInformation getPOMetadata(@PathParam("containername") String containerName, @PathParam("po") String poUUID) {

    // STEP 1 - LOAD THE CONFIGURATION
    // One of the following options:
    // StorageContext.loadContext(containerName);
    // Configuration.getInstance(containerName);
    // Pass a configuration object as an argument of the getPOMetadata() method?
    // Some sort of dependency injection

    // STEP 2 - RETRIEVE THE METADATA FROM THE STORAGE
    // Call the driver depending on the endpoint (JClouds if Swift, Java IO stream if file system, etc.)
    // Pass poUUID as parameter

    // STEP 3 - CONVERT JSON/XML TO OBJECT
    // Unmarshall the file in JSON format
    PreservationObjectInformation poi = unmarshall(data);

    return poi;
}


// Delete a PO
@DELETE
@Path("container/{containername}/{po}")
public Response deletePO(@PathParam("containername") String containerName, @PathParam("po") String poName) throws IOException, URISyntaxException {

    // STEP 1 - LOAD THE CONFIGURATION
    // One of the following options:
    // StorageContext.loadContext(containerName); // Context
    // Configuration.getInstance(containerName); // Singleton
    // Pass a configuration object as an argument of the getPOMetadata() method?
    // Some sort of dependency injection

    // STEP 2 - CONNECT TO THE STORAGE ENDPOINT
    // Call the driver depending on the endpoint (JClouds if Swift, Java IO stream if file system, etc.)

    // STEP 3 - DELETE THE FILE

    return Response.ok().build();
}


// Submit a PO and its metadata
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("container/{containername}/{po}")
public Response submitPO(@PathParam("containername") String container, @PathParam("po") String poName, @FormDataParam("objectName") String objectName,
        @FormDataParam("inputstream") InputStream inputStream) throws IOException, URISyntaxException {

    // STEP 1 - LOAD THE CONFIGURATION
    // One of the following options:
    // StorageContext.loadContext(containerName);
    // Configuration.getInstance(containerName);
    // Pass a configuration object as an argument of the getPOMetadata() method?
    // Some sort of dependency injection

    // STEP 2 - WRITE THE DATA AND METADATA TO STORAGE
    // Call the driver depending on the endpoint (JClouds if Swift, Java IO stream if file system, etc.)

    return Response.created(new URI("container/" + container + "/" + poName))
            .build();
}

Is there a generic way to call another method whenever a method is called in C# [duplicate]

This question already has an answer here:

I have a method something like this:

public Something MyMethod()
{
    Setup();

    Do something useful...

    TearDown();

    return something;
}

The Setup and TearDown methods are in the base class.

The problem I'm having is that I have to write this type of method over and over again with the Setup() and TearDown() method calls.

Is there an elegant way of doing this without having to write this every single time?

Perhaps I'm delusional, but is a way to add an attribute to the method and intercept the method call, so I can do stuff before and after the call?

a website that loads a lot of objects - remote proxy?

i have a website built using html5, bootstrap and angular. when loading it, the user is asked to fill in a lot of search information and when pressing "go", i get a lot of data from my DB, and for each "operation" asked by the used, i create a table and a chart using high-charts.

the problem is that when the user asks for a lot of "operations" to show, it takes about 30sec+ to load the data and make it possible for the user to perform any action (including rolling down).

is there any way to improve this?

one way i thought of was using proxy design pattern to make some of the charts and tables virtual until the moment when the user rolls down to see them, and only then create them but i dont really know how to implement this with js and high-charts.

it is important to say that when checking the networking using chrome debugger, almost half of the loading time was on the client side - i have to assume that this much time is consumed for building the charts. (ofcourse the other half is on the server-side and i will have to handle it there)

thank you very much, even directions of search will be helpful

mardi 22 décembre 2015

Maintaining backward compatibility in Service Oriented Architecture on client side

I am in a situation where my application will get updated from the app store or play store but the APIs that the apps are using wouldn't be updated.

So, the scenario is that the client is at an updated version (e.g. 2.0) and the APIs are not (e.g. 1.0).

In this case, I need to find a pattern in which the client at the updated version can still access and use APIs of older version.

Can anyone please propose a solution for the same.

Note: My apps are built in iOS and Android respectively.

P.S.: I cannot force update the APIs.

Is AWS SNS a scaled out version of the observer pattern?

The observer pattern talks about publishers and subscribers. Isn't this something real close to what AWS SNS does? A notification is broadcasted to all the subscribers which might be SQS queues, email addresses, etc. What are the notable differences if there are any?

Pattern for returning results based on multiple parameters

I am working on legacy code where a method is supposed to return results based on mulitple parameters. The pattern used in code works but I'm thinking if it could be improved further. I'll give an example

Let's say I have a class JobPosting which has various properties

class JobPosting {
    int jobPostingId;
    String description;
    Dept dept; // A posting ca belong to 1 department at a time
    Location loc; // A job posting can belong to 1 location at a time
    String created By;
    int headcount; // number of people required to fill the job posting
    List<User> assignedUsers; // number  of people who have applied for the posting already
    List<User> reservedUsers; // users who are eligible to apply for the posting, if this is empty, then anyone can apply to posting
    DateTime visibleDate; // date from when posting is visible to users
    Date endDate; // posting's deadline
    ...
}

These details for a posting is stored in DB in one table

Now I have various use cases to get the postings:

- Get job postings for a loc & dept- I only care about description and headcount.
- Get job posintgs for a loc & dept with users who have filled the postings
- Get job postings for a loc & dept with users who have filled and users who are eligible for the postings
- Get job postings for a loc & dept which are visibleToUsers (visibleDate < curdate)

and so on, I can have various possibilities for getting the postings depending on the scenario.

Current implementation is that we have builder pattern for parameters

class postingsParams {
    boolean excludeFilledPostings;
    boolean excludeNonVisiblePostings;
    boolean returnAssignedUsers;
    boolean returnEligibleUsers;
}

and one method which takes in parameters and determines what fields in JobPostings to fill and what postings to exclude

getPostingsByLocDept(loc, dept, postingsParamas) { ...// code calls dynamic SQL queries to return results and if conditions to filter }

This seems to work fine, but what I don't like is

- Each caller must be aware of all the possible crtireia to search
- If in future I want to add another criteria like excludePostingsWithPassedDeadline, I need to make changes to this method and need to test all the places where it is called to make sure nothing breaks

One approach is to create specific get methods for the use case, but with that approach we may end up with multiple get methods, which may not be desirable.

Is there a way to improve this design or is the current approach best way to deal with this kind of scenario?

Slice pattern for list

I have a list in which there is an undefined number of elements:

l1 = [a, b, c, d ...]

I need to create a list such that:

l2 = [[a,a],[a,b],[b,b],[b,c],[c,c],[c,d],[d,d],[d,e],...]

Now, in order to obtain l2, this is what I did:

l1 = sorted(l1*4)[1:-1]
l2 = [l1[x:x+2] for x in xrange(0,len(l1),2)]

It works, but I don't like it because in case the number of elements inside l1 is very big then this code will be quite memory (*4) and time (sorted) consuming. Do you have any tips on how to do this?

Code organization in mvc

In our web application we have repositories with CRUD operations and a generic finder function, for instance userRepository.Get(u => u.Username == someString). And UserRepository will return only User objects.

But what if I have a complex query which do the join between Table1, Table2 and Table3 and returns CustomObject which contains some properties from these 3 tables.

Should I put those queries in a Service layer? Should repositories only contain basic CRUD and finder function and return basic entity object and nothing else? I ask because some people told me that no queries should be in Service layer...

lundi 21 décembre 2015

How to design this function efficiently?

I have the below UpdateCustomer function. The problem I'm running into is that I want ValidCustomer function to work by itself and not require existing customer object. In other words it should be calling the database to get the existing customer and do all the complex business rules checking. If I do that I will be calling the database multiple times since CustomerDataChanged function also requires existing customer object. What is the best way to design this function? Is there a design pattern I could follow to refactor this?

public string UpdateCustomer(Customer CustomerToUpdate)
{

  Customer ExistingCustomer = GetExistingCustomerFromDataBase(CustomerToUpdate.ID);

  string ErrorMessage = ValidCustomer(CustomerToUpdate, ExistingCustomer);

    if (string.IsNullOrEmpty(ErrorMessage)) {
       bool DataChanged = CustomerDataChanged(CustomerToUpdate, ExistingCustomer);

       if (DataChanged) {
          UpdateCustomer(CustomerToUpdate);
       }
    }
  return ErrorMessage;

 }

Service Locator pattern in Swift

I'm interested in a flexible universal Service Locator design pattern implementation in Swift.

A naive approach may be as follows:

// Services declaration

protocol S1 {
    func f1() -> String
}

protocol S2 {
    func f2() -> String
}

// Service Locator declaration
// Type-safe and completely rigid.

protocol ServiceLocator {
    var s1: S1? { get }
    var s2: S2? { get }
}

final class NaiveServiceLocator: ServiceLocator {
    var s1: S1?
    var s2: S2?
}

// Services imlementation

class S1Impl: S1 {
    func f1() -> String {
        return "S1 OK"
    }
}

class S2Impl: S2 {
    func f2() -> String {
        return "S2 OK"
    }
}

// Service Locator initialization

let sl: ServiceLocator = {
    let sl = NaiveServiceLocator()
    sl.s1 = S1Impl()
    sl.s2 = S2Impl()
    return sl
}()

// Test run

print(sl.s1?.f1() ?? "S1 NOT FOUND") // S1 OK
print(sl.s2?.f2() ?? "S2 NOT FOUND") // S2 OK

But it would be much better if the Service Locator will be able to handle any type of service without changing its code. How this can be achieved in Swift?

Note: the Service Locator is a pretty controversial design pattern (even called an anti-pattern sometimes), but please let's avoid this topic here.

name of convention to export libraries

I'm trying to start a library, and i would like to export with require, exports or other types..

I see in the major libraries a code like this:

(function(factory) {
  // Establish the root object, `window` (`self`) in the browser, or `global` on the server.
  // We use `self` instead of `window` for `WebWorker` support.
  var root = (typeof self == 'object' && self.self == self && self) ||
    (typeof global == 'object' && global.global == global && global);
  // Set up Backbone appropriately for the environment. Start with AMD.
  if (typeof define === 'function' && define.amd) {
    define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
      // Export global even in AMD case in case this script is loaded with
      // others that may still expect a global Backbone.
      root.Backbone = factory(root, exports, _, $);
    });
    // Next for Node.js or CommonJS. jQuery may not be needed as a module.
  } else if (typeof exports !== 'undefined') {
    var _ = require('underscore'),
      $;
    try {
      $ = require('jquery');
    } catch (e) {}
    factory(root, exports, _, $);
    // Finally, as a browser global.
  } else {
    root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
  }
})(function(root, Backbone, _, $) {

});

What is the name of this pattern? I can't find anywhere a tutorial.

Thanks!!

Design Patterns to Handle Versioning

I am building software which references a DLL containing ~10 classes each representing a message. Each message contains fields that are specific to that message type. Every six months or so updates are made to each message type and I am looking to make the software flexible enough to smoothly handle these transitions. I would like to be able to select a version and a message type from a drop down menu in the GUI which would then reference the given version of that message type. I have a copy of the Gang of Four text and am trying to find a suitable solution to this task. Any help would be much appreciated.

Why make singleton object private instead of public

In Java you can create a singleton like this:

public class SingleObject {

   //create an object of SingleObject
   private static SingleObject instance = new SingleObject();

   //make the constructor private so that this class cannot be
   //instantiated
   private SingleObject(){}

   //Get the only object available
   public static SingleObject getInstance(){
      return instance;
   }
}

Is there any reason why you just couldn't make instance public and dispense with getInstance?

Singleton instance as static field vs. static variable in getInstance() method

In this thread, the following is said about singleton instances:

The static variable can be static to the GetInstance() function, or it can be static in the Singleton class. There's interesting tradeoffs there.

What are these trade-offs? I am aware that, if declared as a static function variable, the singleton won't be constructed until the function is first called. I've also read something about thread-safety, but am unaware of what exactly that entails, or how the two approaches differ in that regard.

Are there any other major differences between the two? Which approach is better?

In my concrete example, I have a factory class set up as a singleton, and I'm storing the instance as a static const field in the class. I don't have a getInstance() method, but rather expect the user to access the instance directly, like so: ItemFactory::factory. The default constructor is private, and the instance is allocated statically.

Addendum: how good of an idea is it to overload operator() to call the createItem() method for the singleton, such that Items can be created like so: ItemFactory::factory("id")?

dimanche 20 décembre 2015

Best design pattern for multiple if statements in an interface impementation

I have an IComposer interface in my c# project:

public interface IComposer
{
    string GenerateSnippet(CodeTree tree);
}

CodeTree is a base class that contains a List<CodeTree> of classes that inherit from CodeTree. For example:

public class VariablesDecleration : CodeTree
{
     //Impl
}

public class LoopsDecleration : CodeTree
{
     //Impl
}

I can have a few classes that implement IComposer and in each I have the GenerateSnippet that loops over the List<CodeTree> and basically do:

foreach (CodeTree code in tree.Codes)
{
    if (code.GetType() == typeof(VariablesDecleration))
    {
        VariablesDecleration codeVariablesDecleration = (VariablesDecleration) code;
        // do class related stuff that has to do with VariablesDecleration
    }
    else if (code.GetType() == typeof(LoopsDecleration))
    {
        LoopsDecleration codeLoopsDecleration = (LoopsDecleration) code;
        // do class related stuff that has to do with LoopsDecleration
    }
}

I have this foreach and if statements repeating in each class that implements IComposer.

I was wondering if there is a better design pattern to handle such a case. lets say tommrow I add a new class that inherits from CodeTree - I would have to go over all the classes that implement IComposer and modify them.

I was thinking about the Visitor Design Pattern - but wasn't sure and not exactly sure if and how to implement it. Does Visitor even the right solution for this case?

Categorizing and Classifying of Data in Sql Server Table

In my database, I have a table Called GroupValHeader. In short this table has GroupValCode, GroupValName, and GroupCode. The purpose of this table is to categorize the data. Say I have Patient Table and a Patient can be Regular, Corporate, Camp and so on. So GroupValHeader contain data like this

GroupValCode        GroupValName                            GroupCode
------------        ------------                            ---------
REGULAR             A Regular Patient                       PATIENTCAT
CORPORATE           A Corporate Patient                     PATIENTCAT
CAMP                A Camp Patient                          PATIENTCAT
GOVTHEALTHSCHEME    A Patient From the Govt Health Scheme   PATIENTCAT
RURALPATIENT        A Patient From Rural and Triabal areas  PATIENTCAT
POORPATIENT         A patient from lower income group       PATIENTCAT

So the patient table has foreign key relation with this table for establishing Patient Category. Similarly have many tables have fk relation with GroupValHeader table.

So I want to know what this pattern is called. Any search keywords that could help. Search on the net did not help, so please guide.

Factory class to handle logic of a constructor?

I have a Maze class which has a constructor:

public class Maze implements MazeInterface {

  private int width;          // Width of maze in units
  private int height;         // Height of maze in units
  private long seed;          // Seed generated for the maze
  private Cell[][] board;     // 2D representation of the maze

  public Maze(int w, int h, Cell[][] maze, long s){
      width = w;
      height = h;
      board = maze;
      seed = s;
  }

  // Bunch of other methods/stuff irrelevant

}

I was reading online about good practices and now I understand that a complex constructor is bad practice. So I thought a factory class would be a viable solution. What I want to do is generate a random seed, random w/h values for the maze (how many units wide or tall the maze is), and other logic for the Maze object. Is the factory pattern the right way to do this?

public class MazeFactory {

  public Maze createMaze(int w, int h){
      long s = generateSeed();       // Generation of a seed
      int w  = generateW();          // Random w value
      int h  = generateH();          // Random h value

      return new Maze(w, h, new Cell[w][h], s);
  }

  private long generateSeed(){
      // Do stuff and return a seed
  }

  private int generateW(){
      // Do stuff
  }

  private int generateH(){
      // Do stuff
  }

}

Would this separation of logic be beneficial by putting it into a Factory class or is this the wrong way to go about this (wrong pattern use/etc) or should I just do this within the Maze class in the constructor by writing private methods and calling them in the constructor? I am trying to learn about different patterns/best practices, but I think i'm misunderstanding the way Factory design is handled or if I am just using the wrong pattern.