dimanche 31 mai 2015

Microsoft Word template/pattern

How can I make a template/pattern in microsoft word? For example, Enrollment paper have already lines, contents. Then the user only need to is to print the data (Student name, ID number etc.. ). The data must be printed exactly in the lines..

Ambiguity at Builder Design Pattern

I have several questions on the Builder Pattern. Builder Pattern uses several methods for constructing an instance of a class and each method return this as return value.

My questions are:

  1. Why does each method return a return type instance of same class?
  2. What is the benefit of this pattern vs using setter method?

How to update a fragment from another class that isn't an fragment

I'm a beginner of android programming then sorry if this question could seem silly but I need to understand how to update the view from a class that it is not an activity or a fragment. I have created a class that fetch data from the Google Play services API. I need to redirect this data to the fragment. which are the common software design patterns to achieve it?

bussiness logic in domain objects

Having this class:

public class DataPeriod {

private final String key;
private final LocalDate from;
private final LocalDate to;

private final Map<LocalDate, DataPoint> dataPoints = new HashMap<LocalDate, DataPoint>();

public DataPeriod(String key, LocalDate from, LocalDate to) {
    this.key = key;
    this.from = from;
    this.to = to;
}

public LocalDate getFrom() {
    return from;
}

public LocalDate getTo() {
    return to;
}

public void hit(int id) {
    DataPoint dataPoint = getOrCreate();
    dataPoint.hit(id);
}

private DataPoint getOrCreate() {
    LocalDate now = LocalDate.now();
    String dataPointKey = key + now.toString();
    if ( !dataPoints.containsKey(now) ) {
        DataPoint dataPoint = new DataPoint(dataPointKey);
        dataPoints.put(now, dataPoint);
    }

    return dataPoints.get(dataPointKey);
}

public long count() {
    long count = 0l;
    for (DataPoint dataPoint : dataPoints.values()) {
        count += dataPoint.count();
    }
    return count;
}

Could be a good idea extract the methods hit(int id) and getOrCreate() to some other class as a service or helper. But then they should be modified in order to receive parameter for DataPoint.

I think has sense include them into DataPointclass because they represent actions which DataPeriodmust know.

There is some pattern for that scenario? In terms of concurrency extract or not extract these methods makes any difference?

Are Singleton bad but (sometimes) necessary?

Singleton has become the first example of SW anti-pattern as it can be misused and create hidden dependencies among classes. However even the frameworks supporting dependency injection (one of the most adopted alternative to singleton) use singleton themselves. For instance Google Guice provides a class (Guice) which is a singleton acting as a factory of injectors http://ift.tt/1Bzuaur. Are we then really sure Singleton is that bad and shall be considered an anti-pattern or, as it always happens, there are some cases in which it is bad and some in which it is a necessary and even elegant solution?

How to create Abstract base class in JavaScript that can't be Instantiated

I have a class

function Node() {
    //implementation
}
and another class

function AttributionalNode() {
    this.prototype.setAttr = function (attr) {
        this.atText = attr;
    };
}

AttributionalNode.prototype = new Node();
AttributionalNode.prototype.constructor = AttributionalNode;

How to make class Node() so it can't be instantiated? e.g when I try

var node = new Node();

So it throws an Exception?

What's the cost of using private class data pattern?

I used to have this as a TimeUnit declaration in a library:

Solution1:

typedef boost::posix::ptime TimeUnit;

TimeUnit createTimeUnit( int hours, int minutes );
std::string toString( const TimeUnit& timeUnit );

Let's say I'd like to move this to something more object-oriented:

Solution2:

class TimeUnit : public boost::posix::ptime
{
public:
    TimeUnit( int hours, int minutes );

    std::string toString() const;
};

And now, let's say I don't want libraries using this class to directly depend on boost, so I'd like to use the private class data pattern, to remove any boost reference from my header file:

Solution3:

class TimeUnitPrivate;
class TimeUnit
{
public:
    TimeUnit( int hours, int minutes );
    ~TimeUnit();

    std::string toString() const;
public:
    TimeUnitPrivate* m_data;
};

TimeUnitPrivate being roughly the same as Solution2's TimeUnit and the new TimeUnit being simply:

TimeUnit::TimeUnit( int hours, int minutes ) : 
    m_data( hours, minutes )
{}

TimeUnit::~TimeUnit()
{
    delete m_data;
}

std::string TimeUnit::toString()
{
    return m_data->toString();
}

Solution3 is very smart and I'd save compilation time + limit boost dependencies for sure.

But I was wondering what was the cost of each solution in term of:

  • Memory usage. Will the three solutions of TimeUnit objects need the same amount of bytes to be stored in memory? If not, which one is the best (I suppose it's Solution1)
  • Performance: For sure, Solution3's toString() will be slower than Solution2's (as function cannot be inline, there will be an additional function call needed in the end). That's not a big deal. But I'm wondering if object creation/destruction will be slower...how would the three solutions be sorted in term of performance for object creation/destruction?

How to delete lines between 2 line patterns using regex?

So I have a file like:

    FLAGSHARE
    xxxxxx
    xxxxx, 1 2015

    words....

    FLAGSHARE
    xxxxxx
    xxxxx, 2 2015

    words....

    FLAGSHARE
    xxxxxx
    xxxxx, 3 2015

    words....

etc.etc.

How would I be able to delete the three lines FLAGSHARE, xxxxxx, xxxxx, * 2015 (essentially remove FLAGSHARE, 2015 and lines between FLAGSHARE and 2015) using Notepad++?

lisp: dynamic scope vs explicit parameter passing

I see two different patterns for "output" functions in (common) lisp:

(defun implicit ()
  (format t "Life? Don't talk to me about life!"))

(defun explicit (stream)
  (format stream "This will all end in tears."))

(defun test-im-vs-ex-plicit ()
  (values
   (with-output-to-string (stream)
     (let ((*standard-output* stream))
       (implicit)))
   (with-output-to-string (stream)
     (explicit stream))))

Is using dynamic scope like in implicit considered bad practice or is this a generally accepted use of dynamic scoping? Note that I'm assuming this is for e.g. a DSL to build complex output, like HTML, SVG, Latex or whatever and is not expected to do anything different apart from producing a printed representation.

Are there - apart from style - any important differences, e.g. with respect to performance, concurrency, or whatever?

MVP, JavaFx and components references

I've studied all popular GUI patterns - MVP,MVC,MVVM and finally I decided to implement MVP (Supervising Controller). So I have the following OBJECTS(!). Stage<-View<->Model. It's important Stage!=View, it is another object. Between view and model data binding. Besides I have a presenter(controller) which handles all events and works with view and model, so View<-ViewInterface<-Controller->Model. The problem is now how to get references to labels, textAreas etc in view. Javafx allows to use @FXML annotation to inject these components to controller. However, using MVP I need these components in View, as all logic for view is in View and I don't need them in controller. The only solution I know is:

public class MyView{
 private Button button;
 public MyView(){
  ...
  button=(Button) root.lookup("#myButton");
 }
}

That is to get references by their ID. However I don't like it. Or I do something wrong or I understand something wrong but I think a better solution exist. Please, help me to find it.

samedi 30 mai 2015

How to deal with user rights and restrictions in complex SPA

I'm working on a single page enterprise application with a pretty complex logic. There are several entity classes on the server side:

class User {
    Long id;
}
class Node {
    Long id;
    String name;
    Status status;
    Node parent;
    List<User> admins;
}
enum Status {
    STATUS_1, STATUS_2
}

Entities are converted to JSON and send to client where are displayed in a tree-like structure, like this:

enter image description here

There are several restrictions:

  1. Simple user that works with application can see tree of nodes, but can't change anything.

  2. User can change node name if he is among admins of node or any of its parent nodes.

  3. Admins can also change status of node, from STATUS_1 to STATUS_2, but only if all child nodes has STATUS_2 status.

  4. There is a list of super adminstrators that can do whatever they want: change properties of any node, change status as they want.

So somehow, during rendering of the tree on the client, I need to know what application user can or cannot do with each of the node on the page. I can't just assign user a role within a whole application because user rights vary from one node to another. Also I can't see whole picture on the client side because child nodes may be not loaded. How can I manage user rights and restrictions in situation like this? What's the proper way or pattern to use?

View - Model Pattern Components and Sub-Components

I am developing an signalprocessing application and have some problems developing a good architecture for the core compoenent.

There are multiple components, each consisting of a view, a model and a controller which is used as an interface between view and controller. Each component is created by an factory with a given model. The view is set up with a given model and every component has its own view. I also let the model handle the signal-processing, I think this is a legit thing to do.

To organize the communication between the components, I have a "Super-Component". This thing is also split into view, model and controller and each layer is also communicating with the component classes on the same layer. The SuperModel for instance controlls the general signal-processing and uses the signal-processing of the component-models. The SuperView has to deal with the visual connections between the components.

I have appended a graphic of the whole achitecture without the factory here. What do you think, is this a legit way to organize this application-component? I think the architecture is some thing between MVP and MVC...

vendredi 29 mai 2015

Returning of abstract class creates "cannot convert" exception

Here is a part of factory Method class:

abstract class AbstractProduct
        {
            public int Id { get; set; }
            public AbstractProduct(int id)
            {
                Id = id;
            }
            public AbstractProduct() { }
        }
    class ProductA : AbstractProduct
        {
            public bool SOMETHING { get; set; }
            public ProductA(int id) : base(id)
            {
                SOMETHING = something;
            }
            public ProductA() { }
        }
 abstract class Creator
    {
        public abstract AbstractProduct FactoryMethod(int id,  bool something);
        public abstract AbstractProduct FactoryMethod();
    }

C# samples of this pattern recomend to write something like:

class ProductACreator : Creator
{

    public override AbstractProduct FactoryMethod(int id, bool something)
    {
        return new ProductA(id, something);
    }

}

But i`ve tried to use abstract class for this:

 public override AbstractProduct FactoryMethod(int id, bool something)
        {
            return new ProductA(){ Id = id, SOMETHING = something };
        }

And when I call FactoryMethod from code, my variant of FactoryMethod throw a compiler error on 2nd line:

Creator creator = new ProductACreator();            
AbstractProduct product = creator.FactoryMethod(1, true);

"Cannot convert from 'Program.AbstractProduct' to 'Program.ProductA'"

Please, explain why does it happends and what should I know for not doing this kind of mistakes in future?

Design Pattern for list of Multiple data type

I have data set like below.

Name     |  Type   | OptionType   | Value
--------------------------------------------
Count    | int     | null         | 20
volume   | double  | null         | 10.2
customer | string  | null         | tim
direction| option  | Left, Right  | Left
shape    | option  | rect, circle | rect
…        |   …     | …            | …

(not only 5. so many data set)

What is the best design pattern or data structure to handle data set ?


I try think that below…

Dictionary <name, object> dataDictionary;

// add
dataDictionary.Add("count", (int)20);
dataDictionary.Add("volume", (double)10.2);
dataDictionary.Add("customer", "tim");
dataDictionary.Add("direction", enumDirection.Left);
dataDictionary.Add("shape", enumShape.Rect);

// get - **I have to know data type….**
int count = (int)dataDictionary["count"];
double volume = (double)dataDictionary["volume"] ;
string customer = (string)dataDictionary["customer"];
enumDirection eDirection = (enumDirection)dataDictionary["direction"];

Is anything better?

Injecting an instance using Unity whose constructor parameter is not known

I have an interface as follows

public interface IDataProvider
{
     List<string> GetData();
}

Implementation of it

public class TextDataProvider: IDataProvider
{
    public TexDataProvider(string source){...}
    public List<string> GetData() {...}
}

One of my services uses IDataProvider to get data. Different implementations could be injected by changing the Unity Register method with alternate implementations.

However, the source parameter of the constructor is only known at the time GetData is called. So, when Unity registers an implementation of IDataProvider, the source parameter is not known.

I understand one alternative is to move the source to GetData method and the other is to create an Abstract Factory whose CreateMethod takes the source parameter and passes it to IDataProvider implementation constructor. Then we can inject Factory instead of IDataProvider instances.

But is there a better way this can be addressed ?

A program based on software patterns - any ideas?

I have to make a simple program that resolves one computer science problem based on two of the following Software Design Patterns: Template Method, Observer, Factory, Chain of Responsibility,Decorator. I do not have any idea on ​​the simple program. Can anybody help me? Any ideas? Program should be easy to implement.

Avoiding use of instance of:

I'm writing a simple game where we have a collection of objects where a player moves around on a grid, collecting coin and avoid monsters.

My class structure looks as follows.

Game Controller - Reponsible for spawing coins and tracking game state

Grid - A class which stores the objects which are currently on the grid, and a few grid related methods.

GridObject - An abstract class representing an object on the grid. e.g. player, monster or coin.

Player, Monster, Coin - All extend GridObject.

My question is what is the most OOP way to program collision handling. The desired result is: Player hits Monster - end game, Player hits Coin - increase score, Monster hits Coin - nothing.

At present, when a GridObject moves, it notifies the board object that it wants to move, if this will cause a collision, I call a handler on the GameController (through a listener pattern), to handle the collision. In that handler, which takes two GridObjects as parameters, I'm using a lot of "instanceof" commands to distinguish the above cases.

What is the best way to avoid using all this "instanceof", which I have read usually means bad design.

Thanks for any input!

Will

Why separation of interface and implementation?

In production code I often see classes defined as follows:

public interface SomeComponent { // Some methods }
public class SomeComponentImpl implements SomeComponent { // Some methods}

public interface SomeComponentV2 extends SomeComponent { // Some methods }
public class SomeComponentV2Impl extends SomeComponentImpl implements SomeComponent { // Some methods }

Why in this case we want to separate the interface and its implementation?

Or put it this way, why is it bad to simply have one base class, and let V2 extend/override V1 as follows:

public class SomeComponent { // Some methods }
public class SomeComponentV2 extends SomeComponent 
{
  // Override methods for reimplementation
  // Add new methods for new features.
}

Javaxfx: MVP (Supervising Controller) must view keep reference to presenter(controller)

I want to implement MVP (Supervising Controller) with javafx. I've studied several examples in internet and saw that view keep reference to presenter. Is this right? I thought that view should not know about presenter at all. There is biderectional data binding between view and model VIEW<->MODEL although view doesn't keep reference to model. And presenter (controller) which knows about view (but works with view via interface) and model and handles all events. Model knows neither view nor presenter.

Refactoring a concrete method in abstract class which contains an abstract method

Considering the below code,

abstract class AbstractClass
{
 public abstract void AbstractMethodA();
 public void ConcreteMethodA()
 {
  //Some operation
  ConcreteMethodB();
 }
}

 public void ConcreteMethodB()
 {
  //Huge code unrelated to this class
  AbstractMethodA();
 }
}

class DerivedClass : AbstractClass
{
public void AbstractMethodA()
{
//Some operation
}
}

Now I wish to move ConcreteMethodB() to separate class and make a call to this from the method ConcreteMethodA() in abstract class. But since ConcreteMethodB() uses an abstract method AbstractMethodA() implemented in DerivedClass, I am unable to access the method AbstractMethodA() from the new class? Any idea on how to resolve this?

Create a text file table with java with pattern

here is the result I need to get:

+ ------------- + ----------- +
|    field1     |   field2    |
+ ------------- + ----------- +
|    f1val1     |   f2val1    |
+ ------------- + ----------- +
|    f1val2     |   f2val2    |
+ ------------- + ----------- +

and so on. As you can see the values must be centered. So I need to get a pattern like (colwidth - string.length ) / 2 for blanks each the right and the left side.

The size of each filed is set by 2 variables. Each one saying how many - signs there are to be set and therefore stating the padding of the table.

The values are in 2 arrays arr1(vala,valb,valc,vald) and arr2(val1,val2,val3,val4)

The first value is the header value.

It all needs to be written to a text file.

To be honest I have researched a lot and have not idea on how to get this going. I got the basics sort of set but the pattern is still missing completely.

File dir = new File("C:\\testdir");
dir.mkdirs();
File outfile = new File(dir, "output.txt");
FileWriter writer = new FileWriter(outfile);
int col1 = 10;
int col2 = 15;
String[] arr1 = {"vala","valb","valc","vald"};
String[] arr2 = {"val1","val2","val3","val4"};
for (int i = 0; i < arr1.length; i++) {
'this needs to go into the file'
System.out.print(intArray[i]); if(i != intArray.length - 1) 
System.out.print(", ");
};

Any idea on how to get this done? Help would be greatly appreciated.

The main problem is how to get the table with the pattern.

Thanks in advance.

nlog logging pattern for common behaviour

I use loggin in my operation service class this way

   public class   MyServiceImplementation : IServiceInterface
    {
           static Logger log = LogManager.GetCurrentClassLogger();

           public bool A()
           {
              try
              {
                 log.Trace("Started");                 
                 // Do something A
                 log.Trace("Completed");
                 return true;
              }
              catch( Exception e )
              {
                  log.Error(e);               
              }
              return false;
           }


           public bool B()
           {
              try
              {
                 log.Trace("Started");                 
                 // Do something B
                 log.Trace("Completed");
                 return true;
              }
              catch( Exception e )
              {
                  log.Error(e);
              }
              return false;
           }
    }

As result in log i see pretty records as

MyServiceImplementation:B   Started
MyServiceImplementation:B   Completed
MyServiceImplementation:A   Started
MyServiceImplementation:A   Completed

But at look of code design it's not pretty because of duplication of logic, and i want to write as

   public class   MyServiceImplementation : IServiceInterface
    {
           static Logger log = LogManager.GetCurrentClassLogger();

           private bool CallMethod( Action m )
           {
              try
              {
                 log.Trace("Started");                 
                 m();
                 log.Trace("Completed");
                 return true;
              }
              catch( Exception e )
              {
                  log.Error(e);               
              }
              return false;

           }

           public bool A()
           {
              return CallMethod(()=> { //Do Something A  } )
           }

           public bool A()
           {
              return CallMethod(()=> { //Do Something B  } )
           }


    }

but in this case i lost stacktrace in log and information about A or B method is calling losted, i see CallMethod in all cases

MyServiceImplementation:CallMethod   Started
MyServiceImplementation:CallMethod   Completed
MyServiceImplementation:CallMethod   Started
MyServiceImplementation:CallMethod   Completed

How to take two goals - pretty logging and pretty code ?

jeudi 28 mai 2015

pass instance variable while using observer pattern in rails

I'm using observer pattern in rails. The "delivered_email" method in TestObserver will be called after notification email been sent out. How could I pass the instance variable in "notification" to the "delivered_email"? I could add it either in the header or subject. But it could pose security issue since user who received email could also see the variable. Is there any better way to solve it?

class GeneralMailer < ActionMailer::Base
  def notification(data)
    @emails = data[:emails]
    subject = "#{@sender.to_s}"
    mail(:to => @emails, :subject => subject)
  end
end

class TestObserver
  def self.delivered_email(message)
    begin
      # do something here
      puts @emails
    rescue => ex
      # do something here
    end
  end

ActionMailer::Base.register_observer(TestObserver)

IOC containers: de-duplicating the configuration code

I am using spring framework for 2 different applications. Let's say both of the applications talk to one single MongoDB database. Following is how I configure MongoDB in both the applications:

@Configuration
@PropertySource("file:/etc/x/y/mongodb.properties")
public class MongoConfiguration {

    @Autowired
    private Environment env;

    @Bean
    public UserCredentials mongoCredentials() {
        String mongoUserName = env.getProperty("mongodb.username");
        String mongoPassword = env.getProperty("mongodb.password");
        UserCredentials credentials = new UserCredentials(mongoUserName, mongoPassword);
        return credentials;
    }

    @Bean
    public MongoClient mongoClient() throws Exception {
        String mongoUrl = env.getProperty("mongodb.url");
        String mongoPort = env.getProperty("mongodb.port");
        MongoClient mongo = new MongoClient(mongoUrl, Integer.valueOf(mongoPort));
        return mongo;
    }

    @Bean(name="mongoTemplate")
    public MongoTemplate mongoTemplate() throws Exception {
        String mongoDatabaseName = env.getProperty("mongodb.databasename");
        MongoTemplate mongoTemplate = new MongoTemplate(mongoClient(), mongoDatabaseName, mongoCredentials());
        return mongoTemplate;
    }

Now, this piece of code is duplicated in two different application configurations. How do I avoid doing this configuration at two different places?

Design pattern help: jQuery working with mutiple elements

I'm new to jQuery. I wanted to know what's the best way to access the element when I am using the same element across multiple functions in the same .js file Below are the two approaches I can think of. I have scoped functions ( F1 & F2) as well as other functions(F3,F4). I want to use elements in some or all of these functions. Whats the best way.

Approach 1

    var elm1 = $("#ID1")
    var elm2 = $("#ID2")
    var elm2 = $("#ID3")

    $(function () {

        function F1() {
            // work with elm1,elm2,elm3
        }

        function F2() {
            // work with elm1,elm2,elm3
        }    
    })

    function F3() {
        // work with elm1,elm2,elm3
    }

    function F4() {
        // work with elm1,elm2,elm3
    }

Approach 2

    var id1 = "#ID1";
    var id2 = "#ID2";
    var id3 = "#ID3";

    $(function () {

        function F1() {
            // get elements usings IDs
            var elm1 = $(id1)
            var elm2 = $(id2)
            var elm3 = $(id1)
        }

        function F2() {
            // get elements usings IDs
            var elm1 = $(id1)
            var elm2 = $(id2)
            var elm3 = $(id1)
        }   
    })

    function F3() {
        // get elements usings IDs
        var elm1 = $(id1)
        var elm2 = $(id2)
        var elm3 = $(id1)
    }

    function F4() {
        // get elements usings IDs
        var elm1 = $(id1)
        var elm2 = $(id2)
        var elm3 = $(id1)
    }

on other note, what terminology we use for functions F3 & F4? Global Functions?

Java Design Pattern Apply

I am developing one API, with following snaps of code.

RowMappable.java

package com.api.mapper;
import org.apache.poi.ss.usermodel.Row;
public interface RowMappable<T> {
  T mapRow(Row row);
}

Issue.java

package com.api.pojo;

import org.apache.poi.ss.usermodel.Cell;

/**
 * It will contain all the fields related to Issue.
 * 
 * @author vishal.zanzrukia
 * 
 */
public class Issue {

  private Cell description;

  /**
   * @return
   */
  public String getDescription() {
    if (description != null) {
      return description.getStringCellValue();
    }
    return null;
  }

  /**
   * @param description
   */
  public void setDescription(Cell description) {
    this.description = description;
  }
}

ExcelColumn.java

package com.api.excel;

import org.apache.poi.ss.usermodel.Row;
import com.api.mapper.SimpleExcelIssueMapper;
import com.api.pojo.Issue;


/**
 * @author vishal.zanzrukia
 * 
 */
public class ExcelColumn {

  private int descriptionColumnIndex;

  /**
   * This is inner class to protect visibility of mapRow method
   * 
   * @author vishal.zanzrukia
   *
   */
  class InnerSimpleExcelIssueMapper implements RowMappable<Issue> {

    @Override
    public Issue mapRow(Row row) {
      Issue issue = new Issue();
      issue.setDescription(row.getCell(descriptionColumnIndex));
      return issue;
    }
  }

  /**
   * set issue description column index<BR>
   * <STRONG>NOTE :</STRONG> index starts from <STRONG>0</STRONG>
   * 
   * @param descriptionColumnIndex
   */
  public void setDescriptionColumnIndex(int descriptionColumnIndex) {
    this.descriptionColumnIndex = descriptionColumnIndex;
  }
}

Here, ExcelColumn is the class which end user (API user) will use for mapping the excel column index with it's purpose (here, it's description for example).

Now, ExcelColumn can implements directly to RowMappable rather than inner class (InnerSimpleExcelIssueMapper), but if I do so, end user (API user) will be able to call mapRow method. I don't want to call mapRow outside the package because it will create confusion for end user (API user). So I have achieved it using inner class concept.

Is this correct way to do it? Is there any better way to achieve the same?

Is there any design pattern applicable here?

How do I minimize object creation in this particular situation?

While implementing a database structure, my goal is to provide easy access to player data.

So, I have created the User class, which holds a Json instance and exposes the methods to take specific information from it.

public class User {
    private Json data;
    public User(UUID id) {
        data = new Json(id + ".json");
    }
    public boolean isPremium() {
        return data.getBoolean("premium");
    }
}

The problem is that I would have to create a new instance every time I needed to know something about the player. That's very expensive!

But since players stay online for a while, I will most likely need the same data at the same time. So, is there a design pattern for this particular situation?

Design pattern for refactoring

I have those three functions and I find it ugly to repeat all the same code, this is not DRY at all. At the same time, I'm not sure how could I refactor those functions to keep clear expression. Could you recommend anything?

Thanks

def download_loc(instance, filename):
    username = instance.username_or_anonymous()
    slug = instance.slug
    filename_with_timestamp = filename_timestamped(instance, filename)
    return "%s/%s/stl/%s" % (username, slug, filename_with_timestamp)

def preview_loc(instance, filename):
    username = instance.username_or_anonymous()
    slug = instance.slug
    filename_with_timestamp = filename_timestamped(instance, filename)
    return "%s/%s/preview/%s" % (username, slug, filename_with_timestamp)

def screenshot_loc(instance, filename):
    username = instance.username_or_anonymous()
    slug = instance.slug
    filename_with_timestamp = filename_timestamped(instance, filename)
    return "%s/%s/screenshot/%s" % (username, slug, filename_with_timestamp)

Creating simple Object pool in Android

I've been reading many articles on how we can improve android app performance by reducing GC work of reclaiming unused object and heap thrashing. Now the question arises:

1) Is it possible to reduce the work done by GC ?

2) Some people say the DVM GC is so efficient that trying to “work around” its performance characteristics will just make things worse.

So, the "work around" could be creating Object Pool of fixed size where objects are pre-allocated when the pool is created. When application needs an object, it request from pool instead of creating one.

Then, I encountered a class in support.v4 library in android Pools.SynchronizedPool which I think can serve the purpose instead of the previous ObjectPool design pattern.

But, now how to use it in my simple android app just to test the performance.

C++ Class inheritance design choice for composite classes


Problem Background

I need to represent trajectory points and trajectories (encapsulating these points) in the form of a collection of classes. All trajectory points have two essential elements: time and state. A trajectory is an ordered set of trajectory points.

The time can be discrete or continuous, but, more generally, I would like to ensure that an arbitrary data type (e.g. float or double) can be used for storage of the information about time. The state should also be of an arbitrary type (e.g. a float or std::vector<std::complex<int>>).

Nevertheless, both for the time and state there exist certain data types which are of interest. Moreover, I may need to provide specific functionality for a combination of data types for the time and state. For example, I may need to provide an interface to simple data analysis/export type based on the type of state or time or a combination of thereof.

The problem described above also applies to the trajectory classes which should store the instances of the trajectory points in the form of an std::vector<std::unique_ptr<TrajectoryPointType>>. Ideally, there should be a base trajectory class that provides the core functionality for any type of a trajectory point and a set of specialised classes that operate on concrete types of trajectory points.

My current implementation seems to be intuitive. However, I am concerned that there may be a more efficient way of doing what I am trying to achieve through the use of established design patterns that are unknown to me.


Current Implementation

In the current implementation, I have a base class template for the definition of the trajectory points (DSTrajectoryPoint) and a base class template for the definition of the trajectories (Trajectory). The class DCTrajectoryPoint accepts two template arguments: TTimeType and TStateSpaceType.

At the second level of the inheritance, the classes that derive from the class DSTrajectoryPoint would, typically, derive by providing either a concrete type for TTimeType or a concrete type for TStateSpace. Thus, for example, at the second level I could have a class

DSTrajectoryPointCT: public DSTrajectoryPoint<double, TStateSpace>

(represents points with continuous time) or a class

DSTrajectoryPointCn: DSTrajectoryPoint<TTimeType, std::vector<std::complex<int>>>

(represents points whose state is a vector of complex numbers).

At the third level, the classes use multiple inheritance to derive from a class with a concrete type for the time and a concrete type for space. Thus, for example, at the third level, I could have a class

DSTrajectoryPointCTCn: public DSTrajectoryPointCT<std::vector<std::complex<int>>>, public DSTrajectoryPointCn<double>

The trajectory classes would be structured in a similar way. However, there is an additional complexity. The trajectory class needs to know both the type of the trajectory point and the types of the time and state associated with the trajectory point. Thus, the base trajectory class template accepts three template parameters, i.e. DSTrajectory<TTimeType, TStateSpaceType, TTrajectoryPointType>.

The inheritance diagram for the classes that derive from DSTrajectory would look similar to the inheritance diagram for the DSTrajectoryPoint. The intention is to have a trajectory class (or class template) corresponding to each trajectory point.

#include <iostream>
#include <complex>
#include <memory>
#include <vector>

class Base
{
public:
    virtual ~Base(void) = 0;
};
Base::~Base(void){}

template<typename TTimeType, typename TStateSpaceType>
class DSTrajectoryPoint : public Base
{
protected:
    TTimeType TTimeTypeInstance;
    std::unique_ptr<TStateSpaceType> u_TStateSpaceTypeInstance;
public:
    DSTrajectoryPoint(){}
    virtual ~DSTrajectoryPoint(void){}
};

template<typename TStateSpaceType>
class DSTrajectoryPointCT:
    virtual public DSTrajectoryPoint<double, TStateSpaceType>
{
public:
    using DSTrajectoryPoint<double, TStateSpaceType>::DSTrajectoryPoint;
    virtual ~DSTrajectoryPointCT(void)
        {}
};

template<typename TTimeType>
class DSTrajectoryPointCn:
    virtual public DSTrajectoryPoint<TTimeType, std::vector<std::complex<int>>>
{
public:
    using DSTrajectoryPoint<
    TTimeType, std::vector<std::complex<int>>
    >::DSTrajectoryPoint;
    virtual ~DSTrajectoryPointCn(void){}
};

class DSTrajectoryPointCTCn :
    public DSTrajectoryPointCT<std::complex<int>>,
    public DSTrajectoryPointCn<double>
{
public:
    DSTrajectoryPointCTCn(void):
        DSTrajectoryPoint<double, std::complex<int>>(),
        DSTrajectoryPointCT<std::complex<int>>(),
        DSTrajectoryPointCn<double>()
        {};
};

template<
    typename TTimeType,
    typename TStateSpaceType,
    class TDSTrajectoryPointType
    >
class Trajectory: public Base
{
protected:
    std::vector<std::unique_ptr<TDSTrajectoryPointType>> m_Trajectory;
public:
    static_assert(
        std::is_base_of<
        DSTrajectoryPoint<TTimeType, TStateSpaceType>,
        TDSTrajectoryPointType
        >::value,
        "Error: TDSTrajectoryPointType must derive"
        " from DSTrajectoryPoint"
        );
    Trajectory(void){}
    virtual ~Trajectory(void){}
};

int main()
{
    Trajectory<
        double,
        std::complex<int>,
        DSTrajectoryPointCTCn
        > T;
}

What is the best way to refactor Utility class in java (static classes)

I am thinking about refactoring some of our utility class(static classes). Static classes are very hard to test and the main problem is that its making Our code very tightly coupled , a lot of dependency. What is the best design pattern to use for refactoring ? I thought about immutable object with a builder, but I am not sure

When to use proper version of singleton thread-safe implementation?

I have a stateless helper-like class which I want to make as a singleton. This class will be shared across different threads.

Am I correct that in this case (instance does not require huge memory allocation size and thus can be loaded several times without resources and performance impact) there is no need in implementing such a singleton with proper multi-threading lazy initialization strategy (Double Checked Locking & volatile, On Demand Holder idiom, Enum Singleton, Synchronized Accessor)?

Is it right to implement such a singleton with a simple non-multi-threading lazy initialization version strategy (like in the code below) in order to have less amount of boilerplate code?

public class Singleton {
    private static Singleton INSTANCE;

    public static Singleton getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new Singleton();
        }
        return INSTANCE;
    }
}

And only in case when state of the singleton class shared across different threads it is required to add proper multi-threading version of a singleton initialization?

How to use one web page to create and edit database entries

My team and I are developing a java web application which allows our admins to create and edit "methods" which can later be viewed by other users.

We are currently discussing the best way to implement this and aim for a screenflow similar to creating / editing events in google calendar.

I.e. The admin starts on a page which shows all current "methods" and a "create new method" button. If he chooses to edit a "method" he is redirected to page "EDIT" where he can change the method's attributes (editing and then sending it via AJAX to update the attribute). If he chooses to create a new method he should be redirected to a page looking the same, changing attributes, etc. But if he does not change anything and goes back / closes the browser the method should not be saved.

We currently have 2 ideas to do this, both with some drawbacks:

A) Create the "method" with default values and redirect the user to the edit-page. Drawback: Should the user go back or close the browser, we have created an unnecessary entry in the db, which our product owner would like to avoid. (There is a 'delete' button, but this would require another action by the admin)Idea A screenflow

B) We create separate pages for create and edit (and the corresponding handlers). Drawback: We have to create and maintain 2 (or even 4) files which do basically the same thing.

Is there any way to negate our drawbacks or another alternative how to implement this? We are using Java Web Projects, JSPs and Servlets as technology.

Is there any way to restrict a class to create only 2 objects

I know about singleton object design pattern. How to allow a class to create only 2 different objects, then it should throw a error.

mercredi 27 mai 2015

Sql data model patterns for 'version control' of rows of OCR'd data

The program OCRs text forms. It saves the data one row per form. The end users consume the data through SQL. I want them to be able to query the contents of the document by just selecting one row of the table.

The OCR is nowhere perfect. But there are a lot of small tricks I can do to improve bits of it post-scan. I think of them as 'grooming filters' on the data.

So I might OCR a form and it generates the initial row of imperfect data. Then later I realize I can run various operations on the row data to improve it. So maybe

  1. removeSpuriousPunction(row)
  2. implyCorrectColumnValueFromOtherColum(row)
  3. updateColumnWithExternalLookup(row) etc. etc.

All those filters can improve the quality of columns of a given row.

But I'd like to be able to track the changes caused by these grooming filters so that (1) I can look at a given row and understand what filters made the row look like it does (2) undo the change of a given filter if it's behaving badly

Is there a canonical pattern for a model like this?

The additional twist, remember, is that I don't want the end user to have to deal with this more complicated model. They don't need to care about the intermediate version of a row -- they just want to search a table, get a row, and know that row is the most-groomed version of the OCRd document.

Idea- using optional singletons

I'm writing a PCL in .NET and I have a stateless class that acts only on the parameters given to its methods. I wanted to make it static, but it already implements two interfaces, so that's out of the question; in the end, I resolved to make it a singleton. However, I know there is a lot of negative stigma associated with the singleton; after hours of internal debate, I'm settling on something like this:

class OptionalSingleton : IInterfaceA, IInterfaceB
{
    private static readonly OptionalSingleton _SharedInstance = 
        new OptionalSingleton();

    public static OptionalSingleton SharedInstance
    {
        get { return _SharedInstance; }
    }

    // default, public constructor

    // rest of implementation
}

I settled on this because a full Singleton encourages tight coupling and Singleton.Instance rather than passing it around as a parameter, while I still want to encourage people to use a shared instance rather than create their own container classes or use new Class(), which is kind of pointless. Because again, this is stateless and therefore thread-safe.

Is this a good idea or are there pitfalls in this I'm not seeing?

How to manage dynamic event handlers in javascript views?

I am trying to make an application analogous to MS Painter. You have a set of tools, and some interact-able elements on the page.

The elements have a click/drag event handler, but the handlers need to change depending on the tools chosen (e.g. the drag handler for resizing vs drag when using drag tool).

I prefer not to use a series of switch statements inside the elements to check for which tool was selected, as it might be problematic when you change the tool names or something. I thought perhaps a state pattern might come in handy here, but it would make the View object look extremely lengthy.

var Square = new Backbone.View.extend({
    ...
    events: { 
        'drag' : 'onDrag',
        'click': 'onClick',
    },

    onDrag: function (event) {
         if(App.Tool.state == 'resize') this.resizeOnDrag(event)
         else if (App.Tool.state == 'drag') this.dragOnDrag(event)
         ...
    },    

    ...// in some obscure location, 
    ...// a nightmare for maintenance and readability
    resizeOnDrag: function () {
          this.doSomething();
    } 
});

Any suggestions on a better way to handle this?

scala pattern matching dilemma

i have the following program which contains a recursive fucntion with pattern matching. This code works

def randomSelect(num:Int, lst:List[Symbol]):List[Symbol] = (num, lst) match{

     /** traveerse list recursively extracting randomelemnents

    * 

    */

  case (n, l) =>  {

      if (n>0) {
        println("At " + n + " we got:" + l)
        val rnd = getRandom(l.length)
        val item = l(rnd)
        lst(rnd) :: randomSelect(n - 1, l.filter(it => it != item))
      } else List[Symbol]()

  }

}

while the following does not. And i cannot understand why

def randomSelect(num:Int, lst:List[Symbol]):List[Symbol] = (num, lst) match{

     /** traveerse list recursively extracting randomelements

    * 

    */

  case (n, mylist) =>  {
         val rnd = getRandom(mylist.length)
         val item = mylist(rnd)
         lst(rnd) :: randomSelect(n - 1, mylist.filter(it => it != item))

  }
  case (0, mylist) => List[Symbol]()

}

in the second conde snippet, case(0,mylist) is never invoked.

what am i missing?

kind regards marco

Design Pattern for Context-sensitive representation

Question

Is there a design pattern that allows me to create a context-sensitive representations of classes?

Definition

Representation: the available getters, and the values they return.

Context: the request context of the object.

Example

A site publishes houses for sale.

A guest user has House.getPrice(), which returns 100,000 for house X.

A registered user has House.getPrice(), which returns 95,000 for house X.

A registered user has House.getLandLordEmail(), which the guest user doesn't have.

Purpose

The practical use of this a Rest-service, to make use of automated mappings to XML/JSON with JAX-B.

Note

I'm not asking for code to implement this. I just want to know if there is a design pattern for this and what it is called.

Recommendation for Backend and Database Structure

this might seem like a broad question so bear with me as I'd like to find out the best approach to solving this issue using popular ideas and techniques.

I'm currently developing an App which lets you log on via Facebook and e.g. say you live in Munich displays a List of all future Events in local Bars & Clubs. This works, because usually all larger Venues create FB Events for almost every Night they're open. However, additional Information, which is not available on FB will need to be provided somehow, e.g. Genre of Music, Prices, Tickets, etc.

The idea was to create a Backend Service with a DB (either use Parse.com or rent a Server and setup a Node.js/MongoDB Setting) and Tables for each Event. Since the basic Information is already provided by FB, the DB would only need to store additional Fields for each Event. The App itself thus makes two Calls. One to FB, gathering Images, and Dates, etc. and One to our Backend gathering additional Tags such as Genre. Is this even good Practice?

Besides, it proves difficult as there is no way to connect a Backend with FB, except for creating a Website where Clubmanagers could log-in with FB and have their Events imported to our Database. In this Case we would mirror FB's Data, which we try to avoid. We somehow have to map FB's Event IDs with our DB though, to be able to deliver that additional information.

How would you go on solving this in a good Way? I seem overwhelmed with this, and it's part of my Bachelors thesis :/

Visitor pattern

When i read about visitor pattern it says like

Allows for one or more operation to be applied to a set of objects at run-time, decoupling the operations from the object structure.

If my assumption is correct, we will define an abstract visitor which holds methods for treating each Objects. Then concrete visitor will implement each of these methods. By this we are separating the logic of handling objects from Object class to visitor implementation.

My doubt is if we have only one visitor implementation, do we really need to use this pattern? can't we just place the implementation in each Object class and call it directly? Please correct me if i miss something in between.

How to generate typelist for factory?

I use library Loki. I need to generate concrete and abstract factory for classes:

class base1 {
public:
    virtual void print() = 0;
};
class base2 {};
class base3 {};

class derived1 : public base1 {
    int a;
public:
    derived1() : a(0) {}
    void print()override { std::cout << a << std::endl; }
};
class derived2 : public base2 {};
class derived3 : public base3 {};

The default declaration of factor in Loki:

typedef Loki::AbstractFactory <
     LOKI_TYPELIST_3(base1, base2, base3)
> BaseAbstarctFactory;

typedef
    Loki::ConcreteFactory
    <
        BaseAbstarctFactory,
        Loki::OpNewFactoryUnit,
        LOKI_TYPELIST_3(derived1, derived2, derived3)
    >
DerivedConcreteFactory;

I noticed that

LOKI_TYPELIST_3(base1, base2, base3)

is equal to

Typelist<base1, Typelist<base2, Typelist<base3, NullType>>>

If I had a list of types

typedef boost::mpl::vector <base1, base2, base3> base_types;

How can i generate Typelist to use it in a factory declaration which is equal to base_types?

Java sharing objects by multiple threads - design pattern needed

I would like to get some advice on a simple multithreading system I am designing.

The idea: The application is capturing frames and displaying them in 1st imageview. These captured frames are also being processed (by MyHandDetectionThread) and then displayed in 2nd imageview.

My solution:

public class VideoManager {
    private volatile BufferLinkedList<InputFrame> mInputFrames;
    private volatile BufferLinkedList<ProcessedFrame> mProcessedFrames;

    private static VideoManager mVideoManagerInstance = new VideoManager();

    private Timer captureTimer;
    private MyVideoCaptureThread myVideoCaptureThread;
    private MyFrameDisplayThread myFrameDisplayThread;
    private MyHandDetectionThread myHandDetectionThread;
    private MyProcessedFrameDisplayThread myProcessedFrameDisplayThread;

    private enum ThreadMessages {
        PROCESS_INPUT_FRAME,
        NEW_INPUT_FRAME,
        NEW_PROCESSED_FRAME_ARRIVED,
        GET_NEW_FRAME
    }

    public static VideoManager getInstance() {
        if (mVideoManagerInstance == null) {
            mVideoManagerInstance = new VideoManager();
        }
        return mVideoManagerInstance;
    }

    // not visible constructor - for singleton purposes
    private VideoManager() {
        mInputFrames = new BufferLinkedList<>(Config.inputFramesListLimit);
        mProcessedFrames = new BufferLinkedList<>(Config.inputFramesListLimit);
    }

    public void startDetectionAndRecognition(ImageView camIV, ImageView handIV) {
        mInputFrames = new BufferLinkedList<>(Config.inputFramesListLimit);
        mProcessedFrames = new BufferLinkedList<>(Config.inputFramesListLimit);

        captureTimer = new Timer();

        myVideoCaptureThread = new MyVideoCaptureThread();
        myFrameDisplayThread = new MyFrameDisplayThread(camIV, handIV);
        myHandDetectionThread = new MyHandDetectionThread();
        myProcessedFrameDisplayThread = new MyProcessedFrameDisplayThread();

        captureTimer.schedule(new TimerTask() {
            public void run() {
                if (myVideoCaptureThread != null && myVideoCaptureThread.threadMessages != null)
                    myVideoCaptureThread.threadMessages.offer(ThreadMessages.GET_NEW_FRAME);
            }
        }, 0, 1000 / Config.fps);
        myFrameDisplayThread.start();
        myVideoCaptureThread.start();
        myHandDetectionThread.start();
        myProcessedFrameDisplayThread.start();
    }

    public void stop() {
        captureTimer.cancel();
        myVideoCaptureThread.interrupt();
        myHandDetectionThread.interrupt();
        myFrameDisplayThread.interrupt();
        myGestureRecogitionThread.interrupt();

        mInputFrames.removeAll(mInputFrames);
        mProcessedFrames.removeAll(mProcessedFrames);

        isActive = false;
    }

    public boolean isActive() {
        return isActive;
    }

    ////////////////////////
    // Thread clases
    ////////////////////////
    private class MyVideoCaptureThread extends Thread {
        LinkedBlockingQueue<ThreadMessages> threadMessages = new LinkedBlockingQueue<>(128);

        @Override
        public void run() {
            WebCamVideoCapture vc = new WebCamVideoCapture();
            while (!isInterrupted()) {
                if (threadMessages != null && threadMessages.poll() == ThreadMessages.GET_NEW_FRAME) {
                    Mat mat = vc.getNextMatFrame();
                    if (mat != null && mInputFrames != null) {
                        mInputFrames.offerFirst(new InputFrame(mat));

                        if (myFrameDisplayThread != null && myFrameDisplayThread.threadMessages != null)
                            myFrameDisplayThread.threadMessages.offer(ThreadMessages.NEW_INPUT_FRAME);

                        if (myHandDetectionThread != null && myHandDetectionThread.threadMessages != null)
                            myHandDetectionThread.threadMessages.offer(ThreadMessages.PROCESS_INPUT_FRAME);
                    }
                }
            }
            vc.close();
        }
    }

    private class MyFrameDisplayThread extends Thread {
        LinkedBlockingQueue<ThreadMessages> threadMessages = new LinkedBlockingQueue<>(128);

        ImageView mCamImageView;


        long lastUpdatedCamImageViewMillis;
        long lastUpdatedHandImageViewMillis;

        public MyFrameDisplayThread(ImageView mImageView) {
            this.mCamImageView = mImageView;
        }

        private synchronized void updateImageViews() {
            if (threadMessages.poll() == ThreadMessages.NEW_INPUT_FRAME && mInputFrames != null && !mInputFrames.isEmpty() && mInputFrames.peek() != null && mInputFrames.peek().getFrame() != null) {
                if(Config.IS_DEBUG) System.out.println("Updating frame image view");
                mCamImageView.setImage(Utils.cvMatToImage(mInputFrames.peekFirst().getFrame()));
            } 
        }

        @Override
        public void run() {
            while (!isInterrupted()) {
                updateImageViews();
            }
        }
    }

    private class MyHandDetectionThread extends Thread {
        LinkedBlockingQueue<ThreadMessages> threadMessages = new LinkedBlockingQueue<>(128); //TODO if multiple threads, define it out of class
        HandDetector hd = new HandDetector();

        @Override
        public void run() {
            while (!isInterrupted()) {
                if (threadMessages.poll() == ThreadMessages.PROCESS_INPUT_FRAME && mInputFrames != null && mInputFrames.size() > 0 && mInputFrames.peek() != null) {
                    if(Config.IS_DEBUG) System.out.println("Detecting hand...");

                    mProcessedFrames.offerFirst(new ProcessedFrame(hd.detectHand(mInputFrames.peek()), null, null, null));

                    if (myGestureRecogitionThread != null && myGestureRecogitionThread.threadMessages != null)
                        myGestureRecogitionThread.threadMessages.offer(ThreadMessages.NEW_PROCESSED_FRAME_ARRIVED);

                    if(myFrameDisplayThread != null && myFrameDisplayThread.threadMessages != null)
                        myFrameDisplayThread.threadMessages.offer(ThreadMessages.NEW_PROCESSED_FRAME_ARRIVED);
                }
            }
        }
    }

    private class MyProcessedFrameDisplayThread extends Thread {
        LinkedBlockingQueue<ThreadMessages> threadMessages = new LinkedBlockingQueue<>(128);
        ImageView mHandImageView;
        public MyProcessedFrameDisplayThread(ImageView mHandImageView) {
            mHandImageView = mHandImageView;
        }

        private synchronized void updateImageViews() {
            if(threadMessages.poll() == ThreadMessages.NEW_PROCESSED_FRAME_ARRIVED && mProcessedFrames != null && !mProcessedFrames.isEmpty() && mProcessedFrames.peek() != null && mProcessedFrames.peek().getmHandMask() != null) {
                if(Config.IS_DEBUG) System.out.println("Updating hand image view");
                mHandImageView.setImage(Utils.cvMatToImage(mProcessedFrames.peekFirst().getmHandMask()));
            }
        }

        @Override
        public void run() {
            while (!isInterrupted())
                if (threadMessages.poll() == ThreadMessages.NEW_PROCESSED_FRAME_ARRIVED)
                    updateImageViews();
        }

    }
}

public class BufferLinkedList<E> extends LinkedList<E> {
    private int counter = 0;
    private int sizeLimit = 48;

    public BufferLinkedList(int sizeLimit) {
        this.sizeLimit = sizeLimit;
    }

    @Override
    public synchronized boolean offerFirst(E e) {
        while(size() > sizeLimit) {
            removeLast();
        }

        return super.offerFirst(e);
    }

    @Override
    public synchronized E peekFirst() {
        return super.peekFirst();
    }

    @Override
    public synchronized E peekLast() {
        return super.peekLast();
    }

    @Override
    public synchronized E pollFirst() {
        return super.pollFirst();
    }

    @Override
    public synchronized E pollLast() {
        return super.pollLast();
    }
}

My problems: The frames are not displayed smoothly. there are a irregular, 1-5 seconds breaks between methods updating imageviews are fired. However the MyHandDetectionThread's task runs preaty quickly. And sizes of message queues of Display Threads are increasing fast. Maybe this is because of some locks on lists storing the frames?

Question: Is my solution correct? Are there some design patterns describing this scenario? Do you have some suggestions for improvement?

html input regex pattern not working

<body>
    <form action="" method="post">
        <div>
            <label>First Name: <input type="text" name="firstname" value=" " pattern="[a-zA-Z ]+"></input> </label>
        </div>
        <div>
            <label>Last Name: <input type="text" name="lastname" value="" pattern="[a-zA-Z ]+"> </input> </label>
        </div>
        <div>
            <label>Voucher: <input type="text" name="voucher" value="" pattern="^[0-9]{5}+[-]+[0-9]{5}+[-]+[A-Z]{2}*"></input> </label>
        </div>
        <input type="submit" value="Submit"></input>
    </form>
</body>


^ the above code is my code, first name and last name are all working, the problem is the voucher input does not check the pattern i wanted, it should be like "12345-67890-AB".

PHP static vs reference

What is the difference? Singleton Why not use a reference to the corresponding variable in memory? Class static variable is not it still variable that takes care her class? The same principle of work you have?

event driven pattern for writing chunks to a file - JS

I'm trying to transfer a file over WebRTC, and I'm struggling to figure out a good pattern for writing data as it's coming in. Since file chunks will be coming in at an unknown rate, I need to be able to write each chunk as it becomes available; this means two things:

  1. if data is coming in too fast, then we need to queue each chunk to be written later after the current write task is finished
  2. if data is coming in too slow, then we need to wait for a chunk to become available

Ideally, I'd like to avoid having to rely on setTimeout() for waiting on chunks to arrive. What I have so far is close, but not exactly what I'm looking for:

// container to hold chunks as they come in
var chunkCollection = {};

// callback function for RTCDataChannel messages
function onData(data) {

  chunkCollection[data.chunkIndex] = data.chunk;
  writeToFile(data.chunkIndex);
}

function writeToFile(chunkIndexToWrite) {

  // if we have the next chunk, write it to the file
  if (chunkCollection[chunkIndexToWrite]) {
    var chunk = chunkCollection[chunkIndexToWrite];
    delete chunkCollection[chunkIndexToWrite];
    fileWriter.seek(chunk.offset);
    fileWriter.write(chunk.blob);
  }
  else {
    // we don't have the next chunk, so we have to wait
    setTimeout(function() {
      writeToFile(chunkIndexToWrite);
    }, 100);
  }
}

The problem with this is that if chunks come in too fast, fileWriter will not be ready to write the next chunk and will throw an exception. However, if chunks come in too slowly, setting the correct timeout will be extremely tricky.

It seems like an event-driven approach will work best here. One event is the data message coming in from RTCDataChannel. Another event is that fileWriter has finished writing, and is ready to write the next chunk. But the piece that I'm getting stuck on is how to properly wait for a chunk to come in...

If the browser is not busy writing to the file, and is just sitting waiting for a chunk to come in, then the browser should start writing the chunk as soon as the chunk is available. But I can't figure out how to do this without an ugly setTimeout loop; I can't figure out how to publish an event that says we don't need to wait anymore, and can continue writing.

What's a good pattern for doing this?

mardi 26 mai 2015

Create object which methods are deferred to a different object for execution [Python]

To explain it and for simplicity, I will use the power domain example.
Imagine that you have more than one equipment. All plugged in one power strip with multiple plugs. The power strip can be controlled via an Ethernet or some other means. Out of all these, there is one and only one which can actually turn power on and off. Nevertheless, I would like the rest of equipment pieces to "appear" as being capable to control the power switch, as well. Programmatically, such functions can look something like:

pwr.poweron()  # this instance can do the actual poweron/poweroff via remote control
eq1.poweron()
eq2.poweron()

where eq1, eq2 are instances of some class. eq1 and eq2 just appear as being able to control the power. In reality, they defer poweron/poweroff for execution to instance pwr. How would you design such class in Python?

Design pattern for Batllefield game in Java

I'm enrolled in a Java couse, and I need to develop a final project. I am willing to develop a Battlefield game using graphic interface, but I have some questions:

1) Which GoF Design Pattern could I use in this situation?

2) Is there a Java framework that could make this job easier?

Thanks! :-)

Generate CSV test data at random from template

I am going to have to generate many CSV files that will contain random-ish data. There will be rules about the fields, such as some will be integers, some should be names picked from a particular list, some will be text generated from a Markov chain with a given source, etc.

I would like to make this flexible, so the CSV specification/template could be changed without needing to make any coding changes. My first thought is to have the template itself also be a CSV which will map the field name to the rules for generating data, so a template might be something like the following:

device id,randint,unique
description,markov,tech.source
vendor,choice,vendors.txt

And from that I could generate a CSV with 3 fields, the first being an ID made of random ints with a "unique" constraint, the second being a narrative description from a Markov chain using "tech.source" as the chain definition, and the vendor being a random selection from those defined in another text file.

Since there could be 80 or so fields in a single generated CSV, and there might be many related CSV files that refer to elements in each other (e.g., there may be a list of people, and hardware may have an owner who must be in the list of people), I'm inclined to create an class that encapsulates each line of the CSV as generated.

That class will store a dict mapping field names to values, then those can be passed to a csv.DictWriter (this is likely to be implemented in Python) that was created with a list of the fields in the correct order. The classes will be able to implement comparison operators to help map the different types, and to track internal consistency about which software is on which host and who is responsible for it and such things.

The main visceral hangup is the mapping of field names to generation rules. Using a CSV and factory seems to the only option I can come up with, but there's just something nagging me that somehow all this can be done a bit more elegantly. Can anyone help me figure if there is a cleaner, easier to extend in the future, pattern or other structure that I should be considering?

Perhaps one thing that feels nagging about this is creating the CSV templates described above. Once I have a definition of how to implement "device id" it seems like it could become painful to have to copy and paste that or retype it every time I want to make another template. Perhaps, then, I should define the rules for generating everything in a common file, then each template just provides the field names.

Abstract Factory to factory

I am new to design patterns and just found one Abstract factory example in Pro .Net book. How can i change this example to Factory (just to trying learn factory and abstract factory)

Public MustInherit Class Greeter

Public Shared Function GetGreerer() As Greeter
    Dim now As DateTime = DateTime.Now
    Dim hour As Integer = now.Hour
    Dim currentGreeter As Greeter

    Select Case hour
        Case 0 To 6
            currentGreeter = New morningGreeter
        Case 7 To 24
            currentGreeter = New nightGreeter
    End Select

    Return currentGreeter
End Function

Public MustOverride Function Greet() As String
End Class

Public Class nightGreeter
Inherits Greeter

Public Overrides Function Greet() As String
    Return "its night time"
End Function
End Class

Public Class morningGreeter
Inherits Greeter

Public Overrides Function Greet() As String
    Return "its morning time"
End Function
End Class

Sub Main()
 Dim g As Greeter = Greeter.GetGreerer
 MsgBox(g.Greet)
End Sub

How to solve the issue. Do you use a design pattern here?

We have many institutions and users. The task here is that to generate a report for the institution.

Depending on user permissions is displayed in the window view option A and option B.

In the report window option A and option B have shared always two widgets: a ComboBox and the button "Create report". However, the operation of these buttons differs depending on the institution and of user rights (roles).

I add a picture to illustrate the problem.

enter image description here

Abstract factory design pattern will be here the best? Whether it is pointless and use only inheritance? What is the best way to approach this?

Multiple Dispatch: A conceptual necessity?

I wonder if the concept of multiple dispatch (that is, built-in support, as if the dynamic dispatch of virtual methods is extended to the method's arguments as well) should be included in an object-oriented language if its impact on performance would be negligible.

Problem

Consider the following scenario: I have a -- not necessarily flat -- class hierarchy containing types of animals. At different locations in my code, I want to perform some actions on an animal object. I do not care, nor can I control, how this object reference is obtained. I might encounter it by traversing a list of animals, or it might be given to me as one of a method's arguments. The action I want to perform should be specialized depending on the runtime type of the given animal. Examples of such actions would be:

  • Construct a view-model for the animal in order to present it in the GUI.
  • Construct a data object (to later store into the DB) representing this type of animal.
  • Feed the animal with some food, but give different kinds of food depending on the type of the animal (what is more healthy for it)

All of these examples operate on the public API of an animal object, but what they do is not the animal's own business, and therefore cannot be put into the animal itself.

Solutions

One "solution" would be to perform type checks. But this approach is error-prone and uses reflective features, which (in my opinion) is almost always an indication of bad design. Types should be a compile-time concept only.

Another solution would be to "abuse" (sort of) the visitor pattern to mimic double dispatch. But this would require that I change my animals to accept a visitor.

I am sure there are other approaches. Also, the problem of extension should be addressed: If new types of animals join the party, how many code locations need to be adapted, and how can I find them reliably?

The Question

So, in the light of these requirements, shouldn't multiple dispatch be an integral part of any well-designed object-oriented language?
Isn't it natural to make external (not just internal) actions dependent on the dynamic type of a given object?

Best regards!

Which class should depend on which class based on level of importance

I have a general question relating OOD, OOP, and Modeling and I am not sure how to ask it. The easiest way is with example. I am generaly using PHP but it can be in any other language. Let say I am a bank and I want to make a program that handles withdrawals. So I will be making 2 class Withdrawal and Account. now what is better to have the function that makes the withdrawal. I mean:

$account = getAccountById(1); //account->balance = 200.00
$withdrawal = new Withdrawal(50,'USD');
$withdrawal->setAccount($account); // $withdrawal->account_id=1
$withdrawal->make(); //SQL changes account where id=1 and set balance to 150
                     //Also save a row in withdrawal tables with withdraw details

or

$account = getAccountById(1); //account->balance = 200.00
$withdrawal = new Withdrawal(50,'USD');
$account->processesWithdraw($withdrawal); //SQL changes account where id=1 and set balance to 150
                                          //Also save a row in withdrawal tables with withdraw
                                          //$withdrawal->account_id=1

One thing known an account is more "important" than withdrawal and can "live" without it. There may also be deposits or other actions.

There are probably many other ways to do this action. Which way do you think is the best?

Conditional EventHandling

I believe I have a design question and I hope to get your input. I made a small program to illustrate my question. Basically, my program consists of a radio system that gets heard on every room in the building. The sound is conditional on the receiving end, depending if the room registers itself to the radio system.

My problem is that the message sent is triggered on every room, even if the room is not registered. I would prefer to do the condition before the message gets sent out, rather then on the receiving end. By doing this, I could save myself unnecessary traffic. Can anyone give me an idea or the correct way to resolve this type of situation?

Just for the record, I would prefer not to have multiple event handlers in the radio, since I don't know how many rooms there will be.

Thank you so much.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Radio
{
#region Speakers
public interface ISound
{
    string sound { get; set; }
}
public abstract class RoomSpeaker : ISound
{
    public string sound { get; set; }
}
public class Room1Speaker : RoomSpeaker
{
}
public class Room2Speaker : RoomSpeaker
{
}
public class BuildingSpeaker : RoomSpeaker
{
}
#endregion
#region Rooms
public abstract class Room
{
    public Radio radioPlayer;
    public string name;
    public HashSet<Type> registeredSpeakers = new HashSet<Type>();

    public virtual void RoomPlayer(string lyrics)
    {
        registeredSpeakers.Add(typeof(BuildingSpeaker));
        Console.WriteLine(lyrics);
    }
}
public class Room1 : Room
{
    public Room1(Radio radioPlayer)
    {
        this.radioPlayer = radioPlayer;
        name = "Room1";
        registeredSpeakers.Add(typeof(Room1Speaker));
        radioPlayer.onRadio += radioPlayer_onRadio;
    }

    // This is what I don't think I like.  It will only do something if it's registered. That's fine.
    // But on any radio message out, this room will get called regardless.  Should I NOT be doing this? Should I go back to
    // making an eventHandler for every room? rather then having one even handler for all the rooms and have a condition on the receiving end.

    void radioPlayer_onRadio(object sender, ISound e)
    {
        if (registeredSpeakers.Contains(e.GetType()))
            RoomPlayer(name + e.sound);
    }
}
public class Room2 : Room
{
    public Room2(Radio radioPlayer)
    {
        this.radioPlayer = radioPlayer;
        name = "Room2";
        registeredSpeakers.Add(typeof(Room2Speaker));
        radioPlayer.onRadio += radioPlayer_onRadio;
    }

    void radioPlayer_onRadio(object sender, ISound e)
    {
        // same problem as in Room1. 
        if (registeredSpeakers.Contains(e.GetType()))
            RoomPlayer(name + e.sound);
    }
}
#endregion

public class Radio
{
    public event EventHandler<ISound> onRadio;

    public void PlayRoom1()
    {
        onRadio(this, new Room1Speaker() { sound = "Test" });
    }
    public void PlayRoom2()
    {
        onRadio(this, new Room2Speaker() { sound = "Test" });
    }
    public void PlayAllRooms()
    {
        onRadio(this, new BuildingSpeaker() { sound = "Test All Rooms" });
    }
}

class Program
{
    static void Main(string[] args)
    {
        var radio = new Radio();
        var room1 = new Room1(radio);
        var room2 = new Room2(radio);

        radio.PlayRoom1();
        radio.PlayRoom2();
        radio.PlayAllRooms();
        Console.ReadLine();
    }
}

}

Sections for different types of users under MVC archetecture

I am writing an application using CakePHP 3 that has three different types of users. While these types of users are all looking at data from the same models, the data they have access to in each of these models is wildly different. They also have very different requirements for retrieving the information.

As a simple example, User Type 1 (U1) has access to addresses and metadata about certain entities, while User Type 2 (U2) only has access to their addresses.

How should I properly structure the views to be the most maintainable, and to conform to MVC best practices? U1 and U2 each have their own controller and homepage action (/U1/home, /U2/home). When they go to look at an entity, should there be a single action for the entity (/entity/view) that shows information based on user rights, multiple actions for the entity based on what it should show (/entity/address, /entity/all), or should each user type have an action for the entity and a corresponding view (/U1/entity, /U2/entity)?

Interface and UML / patterns

I'm preparing an oral presentation of the subject Interface in 'Software Construction'.

One of the keywords it's recomended I talk about are "UML - Use in Design - Patterns - Use in ADT".

All I can think of (or know of) is to show a hierachy of an interface as a superclass and show a "is-a" relationship between the superclass and the subclasses (in a diagram).

I'm not looking for answers, just a little help on how to deal with these keywords. What does Interface has to do with these patterns?

Unlimited undo / redo custom Control

I'm trying to add unlimited undo/redo functionality to my application. I'm making use of the Command Pattern. When I add an Ellipsein Form1, it's added to commandList. But when the user resizes/moves a shape, I also want to add that command to commandList, how can I do this because adding happens in Form1 and resizing/moving in Ellipse. How to fill in the Execute and UnExecute method of Ellipse? The 'walking' trough the list with the Redo/Undo button already works, you can see it in the picture. In panel_MouseUp you see a Box, this is also a custom Control almost identical to Ellipse, you can comment the case out to get a runnable example.

ICommand.cs

public interface ICommand
{
    void Execute();
    void UnExecute();
}

Ellipse.cs

class Ellipse : Control, ICommand
{
    private Point mDown { get; set; }

    public Ellipse()
    {
        SetStyle(ControlStyles.SupportsTransparentBackColor, true);
        this.BackColor = Color.Transparent;
        this.DoubleBuffered = true;
        this.ResizeRedraw = true;
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        // Draw a black ellipse in the rectangle represented by the control.
        e.Graphics.FillEllipse(Brushes.Black, 0, 0, Width, Height);

    }  

    protected override void OnMouseDown(MouseEventArgs e)
    {
        base.OnMouseDown(e);
        mDown = e.Location;
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        // Call MyBase.OnMouseMove to activate the delegate. 
        base.OnMouseMove(e);


        if (e.Button == MouseButtons.Left)
        {
            Location = new Point(e.X + Left - mDown.X, e.Y + Top - mDown.Y);          
        }
    }

    /* Allow resizing at the bottom right corner */
    protected override void WndProc(ref Message m)
    {
        const int wmNcHitTest = 0x84;
        const int htBottomLeft = 16;
        const int htBottomRight = 17;
        if (m.Msg == wmNcHitTest)
        {
            int x = (int)(m.LParam.ToInt64() & 0xFFFF);
            int y = (int)((m.LParam.ToInt64() & 0xFFFF0000) >> 16);
            Point pt = PointToClient(new Point(x, y));
            Size clientSize = ClientSize;
            if (pt.X >= clientSize.Width - 16 && pt.Y >= clientSize.Height - 16 && clientSize.Height >= 16)
            {
                m.Result = (IntPtr)(IsMirrored ? htBottomLeft : htBottomRight);
                return;
            }
        }
        base.WndProc(ref m);
    }

    public void Execute()
    {
        Console.WriteLine("Execute command");
    }

    public void UnExecute()
    {
        Console.WriteLine("Unexecute command");
    }
}

Form1.cs

public partial class Form1 : Form
{
    private bool draw;
    private int x, y, xe, ye;

    private List<ICommand> commandList = new List<ICommand>();
    int current = 0;


    public Form1()
    {
        InitializeComponent();

        menuComboBoxShape.ComboBox.DataSource = Enum.GetValues(typeof(Item));
    }

    public enum Item
    {
        Pencil,
        Rectangle,
        Ellipse,
    }


    private void panel_MouseDown(object sender, MouseEventArgs e)
    {
        draw = true;
        x = e.X;
        y = e.Y;
    }

    private void panel_MouseUp(object sender, MouseEventArgs e)
    {
        draw = false;
        xe = e.X;
        ye = e.Y;

        Item item;
        Enum.TryParse<Item>(menuComboBoxShape.ComboBox.SelectedValue.ToString(), out item);

        switch (item)
        {

            case Item.Pencil:
                using (Graphics g = panel.CreateGraphics())
                using (var pen = new Pen(System.Drawing.Color.Black))     //Create the pen used to draw the line (using statement makes sure the pen is disposed)
                {
                    g.DrawLine(pen, new Point(x, y), new Point(xe, ye));
                }
                break;
            case Item.Rectangle:
                var box = new Box();
                panel.Controls.Add(box);
                box.Location = new Point(x, y);
                box.Width = (xe - x);
                box.Height = (ye - y);
                break;
            case Item.Ellipse:
                var el = new Ellipse();
                panel.Controls.Add(el);
                el.Location = new Point(x, y);
                el.Width = (xe - x);
                el.Height = (ye - y);
                //command execute
                el.Execute();
                commandList.Add(el);
                current++;
                break;
            default:
                break;
        }
    }

    private void undoButton_Click(object sender, EventArgs e)
    {

        if (current > 0)
        {
            ICommand command = commandList[--current];
            //Command unexecute
            command.UnExecute();
        }
        panel.Invalidate();
    }

    private void redoButton_Click(object sender, EventArgs e)
    {
        if (current < commandList.Count)
        {
            ICommand command = commandList[current++];
            //Command execute
            command.Execute();

        }
        panel.Invalidate();
    }

    private void clearAllButton_Click(object sender, EventArgs e)
    {
        commandList.Clear();
        current = 0;
        panel.Controls.Clear();
    }
}

output

Design pattern for persisting and reading several different entities

My goal would be (working in Prestashop) obtain data from distinct webservices, representing several entities data and handle this data (validation, dependencies checks and persisting) having in mind that there're different behaviors for each entity.

Details: The context is Prestashop, in this case, I have to obtain entities data (categories, products, stocks) from a webservices datasource. And each class must have in it's behaviour their capabilities to validate, mapping, check and persist that info to Prestashop models.

I'm trying to do that work with my possible best design, so i've been researching for some design patterns and studyng the problem but it seems like it does not fit in my head.

I've notice that maybe a combination of repository pattern to get some abstraction from datasource to model, factory pattern for letting each class to implement it's behaviors (category must handle it's dependency checks different than products, for example) would do the job, but i cannot fit it together.

I've looking at examples like ' http://ift.tt/1p37PT9 ' which look like a good path but I don't see exactly how to adapt to my needs.

A posibility is: Every entity would implement, let's say "synchronizable", which would be composed by pieces like "validator", "persister" etc... To handle this several components and classes, i'd need to use a factory pattern to easily instantiate the correct class (avoiding these endless "ifs") but i'm afraid that these classes (let's say "ProductSynchronzable") would end with too much funcionality (even it's functionality is derived from different components).

As you can see, firstly my english is not so good, sorry about that. Secondly my head is a mess.

I'd only need a little guidance to focus this problem the right way.

Thank you in advance.

Seperating interfaces and making them more generic

I have an interface to define my records\models

public interface IStockItem
{
    string Code { get; set; }
    string Description { get; set; }
    decimal FreeStock { get; set; }
}

Is it best to put the actions into another interface?

public interface IStockExport
{
    IEnumerable<IStockItem> GetAll();
    IEnumerable<IStockItem> GetStockByCode(string code);
    decimal GetFreeStock(string code);
}

public interface IStockImport
{
    void CreateItem<IStockItem>;
}

Is there a better way to do this and make it more generic? so i can share the actions interfaces with other records\models?

Regex Pattern to match only first sign of a String

I want the pattern to match the exactly first sign of a String. The sign can be everything: whitespace, character, digit... but it should be only the first.

^.{1} was my guess, but ends in infite loop on string "123 void"

public CatchAll(String string) {
                pattern = Pattern.compile("^.");

Language is Java, ^. loops infitite.

Suggestions for such a pattern?

Pattern / best practice for accessing connection that has undeterministic set time

Below code attempts to get a connection every 5 seconds. The getConnection method returns true or false depending on random double and is for illustrative purposes. The time it takes to get a connection cannot be guaranteed so if fail to initially get connection, wait 5 seconds and try again. Once the connection is attained, then just exit.

Is there better/cleaner method of getting the connection instead of using if statements and Thread.sleep ? It seems wrong (im not sure why) sleeping the running thread for 5 seconds before trying again

public class TestAlive {

    public static void main(String args[]) {

        while (true) {
            try {
                if (getConnection()) {
                    System.out.println("Got connection, do some work.....");
                    System.exit(0);
                }
                else {
                    System.out.println("No connection, re-trying in 5 seconds");
                    Thread.sleep(5000);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static Boolean getConnection() {
        return Math.random() > 0.5;
    }
}

Decouple visualization methods and application

this is my first question on SO, so please bear with me.

We develop an application, which gathers data, and we have methods that let us visualize the data in various ways. With growing number of methods, we decided to separate the application and the visualization methods. I'm wondering what is the best way to accomplish this. I've come up with the following code, which somewhat tries to separate the two, but still ...

Is there a better way to do it?

// forward declaration
class App;

// Interface to all visualization methods
struct Methods {
    virtual void show(App * a) = 0;
};

// Some visualization method
struct Method0 : public Methods {
    void show(App * a) {
        a->getData();
    }
};

class App {
public:
    vector<Methods *> methods;

    void run() {
        // draw all registered methods
        for (auto m : methods)
            m->show(this);
    }

    int getData() {
        // parse and precompute data (time-consuming, thus do it only once)
        // return the required data (not just an int..)
        return 42;
    }
};

void main() {
    App a;

    // register some methods
    a.methods.push_back(new Method0());

    // run the application
    a.run();

    // clean up
    for (auto m : a.methods) delete(m);
}

lundi 25 mai 2015

Visitor Pattern for two arguments

Here is a problem statement: We have interfaces/super classes Student and Teacher

Student has two implementations/sub clasees, ScienceStudent and PhysicalEducationStudent

Teacher has ScienceTeacher and PhysicalEducationTeacher.

We want to implement a method getMeetingPoint(Student s, Teacher t) which returns a place where they meet based on the type of Student and Teacher.

For example, if its a ScienceStudent and ScienceTeacher they meet at Lab if PEStudent and PETeacher they meet on the Ground and if its a ScienceStudent and PETeacher or vice versa, they meet at cafeteria

We can write a naive method, which checks using instanceof. But the problem is, this becomes complex when Teacher or Student gets extended, and tough to maintain. something like this:

public class MeetingPointDecider {

    getMeetingPoint(Student s,Teacher t) {
        if(s instanceof ScienceStudent && t instanceof ScienceTeacher) {
            return "Lab";
        } else if (s instanceof PhysicalEducationTeacher && t instanceof PhysicalEducationTeacher) {
            return "GRound";
        }
        .
        .
        .
    }
}

Another option is writing a factory, which accepts a Student and a Teacher and returns something like MeetingPointDecision [Ground or Lab], but the problem persists. Is there any good pattern we can use, where we do not have to modify existing classes (or minimal modification) when a new class is added, Say instanceof ScienceStudent we have ChemistryStudent, PhysicsStudent and ChemistryLab, PhysicsLab. There is also a chance of adding more actions, which differs in implementation based on the Student and Teacher type ( Where Visitor is an option, but not sure how to implement with two deciding classes)

Can someone please suggest a good way to implement this?

Thanks!

Bounded Contexts Rules Orchestration

My banking core domain has divided into 2 distincts bounded contexts BC1 and BC2. These BCs deal with very specific business rules and processes (custom agreement for debt recovery, and administrative indebtedness with legal obligations). BC1 and BC2 are accessed through WebServices from a CRM. A client can't have both a custom agreement and an indebtedness plan, and each situation exclude the other one. So we need to orchestrate both types of processes (more precisely we need to enforce in each BC that actions are permitted, on both sides).

How would you orchestrate them ? Would you inject a bit of knowledge of BC1 in BC2 domain model, and vice-versa, or do you think we should rely on a third BC (BC3) that could orchestrate the system, and would be aware of both business knowledges, and through a third WebService for instance ? We just need to know if the client has an agreement with the company, or if it is officially and legaly indebted.

Do you think having BC1 to know "a little" of BC2 business is violating DDD principles ? In case of an orchestrator or a proxy, would you use WebServices, or SharedKernel ? What are the pros and cons of SharedKernel versus WebServices ?

Design pattern for translating multiple data-formats from multiple sources to a single format

I work for a company that has multiple websites, and the existing infrastructure is...well, awful.

Right now, each store has its own table that varies in structure. This is rapidly becoming a problem (if it wasn't already).

So I need to find a way to take orders from multiple channels, format them into a single, unified way, store them in our end, and translate them back to the format expected by the store APIs (which can be everything from RESTful JSON to SOAP).

My initial gut-reaction was a mixture of factory, visitor, and builder patterns (plus some smart polymorphism), but it got a little bit too complex too quickly. Before I go and code myself into a corner with a solution that may not be optimal, maintainable or extensible, is there a pattern or set of patterns that would be more efficient?

Basically, I'm thinking it would be something like:

Source -> Translator -> Our Format
Our Format -> Translator -> Source

I don't need the translator to actually act on the data. All it should be responsible for is getting it in the right format, and we can get it from point A to point B (and vice versa).

A few assumptions about the system:

  1. The format on our end is unlikely to change, and therefore our objects are unlikely to change
  2. When the data is translated back to the original source, we can assume that everything that's required will be there. The actual behavior for out-bound requests is small, focused and well-defined

Java factory pattern creating objects

I am designing a solution in Java, and I have to create n objects, based on property values. I am using factory design pattern.

Using the classic example of shape and shape types

String myShapes="circle,square,circle,rectangle"  // This is from a property file
for ( shapeType : myShapes.split("," ) {
   ShapeFactory shapeFactory = new ShapeFactory();
   Shape shape1 = shapeFactory.getShape(shapeType ); 
   shape1.doSomething(); 
}

Can someone tell me whether the following is right approach in creating the objects? I don't know how many objects I will have to create during compile time.

Need to write a java program to sort file content [on hold]

Write a java program to list the customer and his details in a sorted order based on input field.

Input values 1. File name & file with fields(customername|Gender|Age|DateArrived) Gender m/f Age- 1 to 99 Date Format - yymmdd

Sort by field (Value 1 for customerName, 2 for Gender, 3 for Age, 4 for DateArrived)

Output Values: 1. File name 2. New sorted file with fields(CustomerName|Gender|Age|Date Arribed)

Expectations: 1. Output should be correct 2. Identify the suitable design pattern and use 3. Code should be optimized for performance.It should work even if the input file is huge 4. Check the maintainability issues in the code and fix. 5 All the applicable Exceptions/Error handling should be done proper error message to be displayed..

Please suggest implementation its urgent

RegExp Validation (email validation)

can anyone help me? I'm using a validation on Field validation that calls a Business Service(BS). In this BS it is performed an email validation with RegExp.

I'm using the following pattern: ^(.+)@([^();:,<>]+.[a-zA-Z]{2,10})

It is expected that the the email termination has between 2 and 10 characters. With 1 character I get the expected error but the same do not happens with 11 or more characters, I do not get any error. Someone can help me?

Thank you, Luis

Boolean multireturn refactoring

What do you think will be the best way to refactor this kind of boolean method?

if (someService.isTrue(importantArg)) {
    return true;
} else if (someService.isSomeTrue(anotherArg)) {
    return isAnotherCondition(entry);
} else {
    return super.thisMethod();
}

JavaScript. Universal function to extract deep (probably non-existent) object property safely

I want to design a helper function which would try to execute passed as parameter deep property path and to return value extracted by it.

For example consider following code

var foo = {
        bar: [
            {
                baz: "someValue"
            }
        ]
};

function getByPath(path) {
    var val;
    try {
        val = eval(path);    
    } catch(e) {
        console.error(e);
    }
    return val;
}

var path1 = "foo.bar[2].baz";
var path2 = "foo.bar[0].baz";
var path3 = "foo.bar.baz";

console.log(path1 + ": " + getByPath(path1));
console.log(path2 + ": " + getByPath(path2));
console.log(path3 + ": " + getByPath(path3));
console.log("done.");

output

TypeError: Cannot read property 'baz' of undefined
    at eval (eval at getByPath (unknown source), <anonymous>:1:11)
    at getByPath (<anonymous>:13:15)
    at <anonymous>:24:28
    at Object.InjectedScript._evaluateOn (<anonymous>:895:140)
    at Object.InjectedScript._evaluateAndWrap (<anonymous>:828:34)
    at Object.InjectedScript.evaluate (<anonymous>:694:21)getByPath @ VM317:15(anonymous function) @ VM317:24InjectedScript._evaluateOn @ VM212:895InjectedScript._evaluateAndWrap @ VM212:828InjectedScript.evaluate @ VM212:694
VM317:24 foo.bar[2].baz: undefined
VM317:25 foo.bar[0].baz: someValue
VM317:26 foo.bar.baz: undefined
VM331:7 done.

So everything is good here: an existent property is extracted, undefined is returned for non-existent and an exception is caught and stacktrace is printed in case of attempt to read a property of undefined.

But this function is not reliable in case javascript code is compressed on a server because object/property names can be shortened by a compressor and path like "foo.bar[0].baz" won't exist anymore (proper one will look like "a.b[0].c").

Is there a good solution except playing with compressor settings?

What is the functional analogue of a Strategy pattern?

Disclaimer: I do not use functional languages; only trying to comprehend some parts of FP.

Google suggest the articles where first order functions with lambdas can offer the similar functionality which Strategy pattern gives.

Yet we somehow need to match data and corresponding lambda. With OO-design this is done automatically with VMT, that is the type itself carries the important information needed to reason about execution flow making further addition of a new behavior easy (open closed principle): inherit and override. Old code simply stays unchanged. Functional pattern matching seems to be static in this regard and does not allow such kind of dynamics.

Sure, it is possible to code a configurable matching behavior for selecting lambda based on given data, but it isn't it what we have in OOP out of the box?

Remove "factory"<->"concrete implementation" dependency

I have a "provider factory" which creates an implementation of a concrete provider. To create correct implementation it needs, among other parameters, typeId. The problem is that in order to pass the correct typeId to the factory, I need to validate and, if necessary, change it. And in order to do that, among other parameters, I need an instance of a particular provider. Which is where the problem is - the provider should be singleton (I really don't want to make it a Singleton with a capital S), because it queries a database and caches the result in the internal property.

So my question is - is there a more suitable pattern to use or another way to achieve something similar?

class ProviderFactory
{

    public function createProvider($typeId)
    {
        if ($typeId == 2) {
            return new Provider2($arg1, $arg5);
        } elseif ($typeId == 4) {
            return new Provider4();
        } else {
            return new ProviderDefault($typeId, $arg1, $arg2, $arg3, $arg4);
        }
    }
}


interface ProviderInterface
{
    public function getCost();
}

class ProviderDefault implements ProviderInterface
{
    public function __construct($arg1, $arg2, $arg3, $arg4) {}

    public function getCost() { /*implementation*/ }
}

class Provider2 implements ProviderInterface
{
    public function __construct($arg1, $arg5) {}

    public function getCost() { /*implementation*/ }
}

// this call can be implemented with the following condition
// if ($typeId == 2) {
//      if ($provider2->getCost() !== null)
//          $typeId = 1;
// }
//
$typeId = fixAndValidateTypeId($typeId, new Provider2($arg1, $arg5));


$factory = new ProviderFactory();
$provider = $factory->createProvider($typeId);