samedi 28 février 2015

Object in Business layer same as DTO with logic?

Let's say I have a Spring MVC project, in which I'm using DTO to get data from a database and to pass data to the UI. Let's suppose that I have a UserDTO and in my business layer I have to do something with that, but I need to put logic in the User and the DTO pattern says that no logic is allowed (or just simple logic).


Should I transform this UserDTO to a User object in order to have the logic and then make a UserDTO to give it to the UI? Or just use the UserDTO and process it in the business layer?


May a BO help?


Thanks


Should entity hold reference to repository?

Suppose we have class Home and we want to have collection of all Cats inside this home, but also we want to have general repository of Cats that has all the cats available in the world. Should Home hold the reference to specific repository (or maybe collection) of Cats, or should I just make another lookup in general repo?


Design Patterns - One public class utilizing many hidden classes

I have gone through http://ift.tt/1tmzBcW in trying to find out the most efficient to create a design pattern in which "one visible class utilizes many hidden classes" to create a fluent API. Below is the code I currently have:



public class VisibleClass {
Private OrderClass order;
private ReceiptClass receipt;

public VisibleClass makeOrder() {
if (!(order instanceof OrderClass))
order = new OrderClass();

order.make();
return this;
}

public VisibleClass printReceipt() {
if (!(receipt instanceof ReceiptClass))
receipt = new ReceiptClass();

receipt.print();
return this;
}
}

class OrderClass implements IOrder {
public void make() {}
}

class ReceiptClass implements IReceipt {
public void print() {}
}

interface IOrder { void make(); }
interface IReceipt { void print(); }


Here is how I am currently using the API:



public static void main(String[] args) {
VisibleClass x = new VisibleClass();
x.makeOrder().printReceipt();
}


It this a good approach? Can a better approach be used for it?


*EDIT: Also, I should add that the VisibleClass will implement all methods of the hidden classes.


Is inheritance over composition that unpreferrable when using abstract classes as parents?

I mean, does the fact that parent class alone is never used anywhere compensate the potential flaws for the critics of the pattern?


What is the best "pattern" to use for Android settings flow?

I have an application which has a few settings, with dependencies.


So you need to enter a username, password. These may or not be invalid - they are on a remote server. There are other values for possible settings that can be retrieved. I'm having a problem sorting everything out with PostChanged handlers and network threads needing to be async - it makes it hard to have a robust way to handle settings.




  • Need username/password.




  • Needs to be valid (check server - network call)




  • If valid, need to populate a ListPreference with some possible values (network call, AND update ListPreference)




Right now things are very hack-ish, thrown together, AsyncTasks everywhere.


There's got to be a better way?


Object creation in swift / two stage object creation in swift

I wonder how allocation and instantiations works (On The Hood) in swift.


Being a beginner of swift language concepts, I wonder how the object creation works.


Does the 2 stage object creation (As in Objective C) is given a bye bye or it is hidden inside.


Best pattern for strong typing of class relations

I'm looking for a way to allow relation between instances at compile time. In an abstract way, that means that several subtypes of an interface are related to multiple properties of the same type, but not all of them compatible in a logical way. I'd like to check it at compile time.


The scenario is such as:



  • An Anmimal instance receives a country instance in the constructor (country where it lives).


Solutions:



  • Runtime checking trhough XML for instance and validation




<Animal>
<Type>Lion</Type>
<Countries>
<Country>Zimbabwe</Country>
<Country>Kenya</Country>
</Countries>
</Animal>

<Animal>
<Type>Gorilla</Type>
<Countries>
<Country>Zimbabwe</Country>
<Country>Botswana</Country>
</Countries>
</Animal>


But this could only fail at runtime



  • Create a GorillaCountry, BotswanCountry and KenyaCountry Country subinterface for each combination of properties, but this is a bit unmantainable if there is 200 mappings.


What I look for is some kind of pattern that approaches in a nice and scalable way this type checking at compile time:



if (animal instanceOf Lion){
if (country instanceOf Botswana) throw new UnsupportedMApping("There are no lions in botswana")
}Kenya
else if (animal instanceOf Gorilla){
if (country instanceOf Kenya) throw new UnsupportedMapping("There are no gorillas in kenya")
}


Perhaps a tricky way with generics or maps...


Is it design pattern: create object with identifier or return if already exists?

main principles:




  • object could be created through class method by providing unique identifier (whatever)




  • if object with given identifier doesn't exists, returned new object otherwise returned existing one




So main point in keeping objects with unique filed (f.e id) for future using, since they might have own states (f.e loading, loaded so on) we are allowed to use it everywhere we need it without re-creating.


Is it design pattern?


F.e:


Advirtisement.h



@interface Advertisment : NSObject

+ (instancetype)adWithID:(NSString *)adID;
+ (NSMutableArray *)sharedAds;


Advertisement.m



+ (instancetype)adWithID:(NSString *)adID {

NSMutableArray *ads = [[self class] sharedAds];
// Look for existing ad based on the id
Advertisement *returnableAd = nil;
for (Advertisement *currentAd in ads) {
if ([currentAd.adID isEqualToString:adID]) {
returnableAd = currentAd;
break;
}
}
// Create a new ad instance for this id if one doesn't already exist.
if (!returnableAd) {
returnableAd = [[[self class] alloc] initWithID:adID];
[ads addObject:returnableAd];
}
return returnableAd;
}
}

+ (NSMutableArray *)sharedAds
{
static NSMutableArray *sharedAds;

@synchronized(self) {
if (!sharedAds) {
sharedAds = [NSMutableArray array];
}
}
return sharedAds;
}

vendredi 27 février 2015

Data Centric Programming - Pattern, Best Practice?

While ditching the Object Oriented Programming model, I need more information about Data Centric (is it really that way) programming. Are there any resources or information? Is Data Centric really the right term?


Observer Pattern For Different Observables

I was wondering what the appropriate way of dealing with Observables that may contain different data. To use the weather data analogy:


suppose I have different weather stations that record data. Let's say humidity, temperature and pressure. One station might only have the capability of recording temperature, while others all three etc..


What I am trying to do is the following:



  • An observer specifies what data they want to record. Say, only temperature.

  • An observable specifies what data they have available.

  • If both the observer and observable match up, the data is processed by the observable.


Here are a few things: There are a lot more parameters than 3. Something like 30, and this can grow. I thought of implementing getTemperature(), getPressure(), getHumidity(), etc.. in my base observable and overriding them in the relevant classes. Otherwise it returns nothing. I also created a Flags anonymous struct that is specified for both the Observable and Observer, and only when they match data is recorded.


I wanted to know the following: Is this the best design? Should the responsibility of matching Flags be on the Observer? Is there a more elegant solution?


I'm not necessarily looking for code handouts. Just thoughts on a good implementation.


Thanks!


Best Practice to add a model from the form of a different model in Laravel 4

I am working on a Laravel 4 project where I have several models. Some of them are related to others.


For example I have a tour model with several properties and a peak model with several properties which is related to the tour model (m:n).


I created resource controllers to manage each model according to CRUD, which works fine. So every model has its own form to edit and store its own properties as well as relations to existing peaks.


As there is a "main" model (the tour model) I want to give the user the ability to create a peak out of the "create-a-tour"-form if the actually created tour has a peak, which is not yet in the database.


I am thinking about three solutions:



  1. Open a modal with the peak-form and append the new peak to the select-peak element in the tour-form

  2. Add the peak-form elements dynamically via AJAX to the tour-form and post the filled data via AJAX to the PeaksController and append the new peak to the select-peak element in the tour-form.

  3. Add a link to the peaks-form and save the filled information of the tour-form in a session variable, so that the user can add a new peak and then come back to the tour-form where the script fills the data from the session.


What is best practice to solve this? Is there another (better) way to do this? I think that's a common problem, but I didn't find any tutorial or information regarding this question (might be a problem, that I really don't know what to search for in this case).


I appreciate any answer and discussion!


split a string by the last patterns

I have some data like this:



vtab = read.table(textConnection("uid=123455,ou=usuarios,ou=gm,dc=intra,dc=planej,dc=gov,dc=de
uid=123456,ou=bsa,dc=plant,dc=gov,dc=de
uid=123457,ou=reg,ou=regfns,dc=sero,dc=gov,dc=de
uid=123458,ou=reg,ou=regbhe,dc=sero,dc=gov,dc=de
uid=123459,ou=sede,ou=regbsa,dc=sero,dc=gov,dc=de
uid=123450,ou=reg,ou=regbhe,dc=sero,dc=gov,dc=de"))


I would like split this data. Firstly split the data in two groups including just the uid= number and the third last description in dc=. Like thus:



[,1] [,2]
[1,] "123455" "plant"
[2,] "123456" "planej"
[3,] "123457" "sero"
[4,] "123458" "sero"
[5,] "123459" "sero"


Any helps are enjoyed :-)


Merging Multiple Objects to Multiple Formats

I'm looking for the best design to apply to a situation with multiple DataObjects and multiple output formats (ReportGenerators).


The current setup is something like this: there's a Formattable interface that has various methods used by a ReportGenerator. Each DataObject (DataObject could be any of several different unrelated classes) implements Formattable -- ie, it knows how to organize its particular data for the report, and the ReportGenerator is simply fed Formattable objects from which it accesses String arrays and pretties them up.


1) So here is my first question: is this advisable? Because the result is that the process of organizing data for the report is strewn throughout all the DataObjects. The alternative is an intermediary class with a whole bunch of instanceof checks on what kind of DataObject to format, but at least then it's all in one place.


2) And then my new problem is that I need to introduce a secondary ReportGenerator which will need DataObject data organized slightly differently. In the current setup, I could introduce a parameter on Formattable methods to specify what kind of ReportGenerator the DataObject should format itself for, but again, not sure if this is advisable.


Factory Method pattern vs composition

From GoF chapter about the Factory Method pattern:



Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.



The idea is to let subclasses decided which class to instantiate, and GoF's implementation of the idea, is to provide an abstract method in the superclass, that subclasses need to override, and thus providing their own instantiation logic.


What I don't understand is, why implementing it using an abstract method, and not using a class member which is the factory. I'll explain.


This is the GoF way:



public abstract class Creator {
public void doStuff() {
Product product = createProduct();
/* etc. */
}

public abstract Product createProduct();
}


Usage:



MyCreator myCreator = new Creator() {
@Override
public Product createProduct() {
return new MyProduct();
}
}

myCreator.doStuff();


But why bother with the subclassing, etc.? I suggest this approach:



public class Creator {
private Factory factory;

/* constructor */
public Creator(Factory factory) {
this.factory = factory;
}

public void doStuff() {
Product product = factory.createProduct();
/* etc. */
}
}


And this is how you use it:



MyFactory myFactory = new MyFactory();
Creator creator = new Creator(myFactory);
creator.doStuff();


So what is the benefit in GoF's approach? Why not composing the Factory into the Creator class instead of expressing it using an abstract method?


Model Driven Engineering paradigm step by step

Anyone knows where to find documents or articles on internet explaining step by step how to propose a software architecture design based on Model Driven Engineering paradigm? I have already searched here on stackoverflow and on Google as well. Thanks.


What is the best way to perhaps call a function, every time, inside a class?

I have a class that has an optional function as a parameter. Sometimes I create instances of this class with a function, sometimes not.


The function is called every time when some methods of the instance are called. Of course if the function was not given, nothing happens there.


My question is, what is the best way to achieve this ? I tried a couple of things. Can you judge my solutions, by performance, scalability and readability ? Do you have better solutions ?


The class looks like this



class MyClass(...):
def __init__(self, function=None):
self.function = function

def method_a(self, ...)
...
self.function(a,b,c)
...

def method_b(self, ...)
...
self.function(a,b,c)
...

def method_c(self, ...)
...
#not every method bothers with the function
...


Of course this produces



TypeError: 'NoneType' object is not callable


The most naive solution is to change the class itself with defensive ifs or trials:



class MyClass(...):
def __init__(self, function=None):
self.function = function

def method_a(self, ...)
...
if self.function:
self.function(a,b,c)
...

def method_b(self, ...)
...
if self.function:
self.function(a,b,c)
...


second solution is to create a do nothing function and perhaps store it in self.function:



def do_nothing(*x):
pass

class MyClass(...):
def __init__(self, function=None):
if function is None:
function = do_nothing
self.function = function

def method_a(self, ...)
...
self.function(a,b,c)
...

def method_b(self, ...)
...
self.function(a,b,c)
...


the third solution is to create a function wrapper with defensive ifs inside it:



class Maybe(object):
def __init__(self, function=None):
self.function = function

def __call__(self, *args):
if self.function is None:
return
# else
return self.function(args)

class MyClass(...):
def __init__(self, function=None):
self.function = Maybe(function)

def method_a(self, ...)
...
self.function(a,b,c)
...

def method_b(self, ...)
...
self.function(a,b,c)
...

Is clone method an example of Prototype pattern in Java?


  • If someone asks me what is the example of prototype pattern in Java which is already implemented in Java APIs , can I say clone() method ?

  • I feel clone() method in itself doesn't exemplify prototype pattern , it's just a means to achieve prototype pattern. Am I right ?

  • Though some answers on stackoverflow says that clone() method is an example of Prototype pattern in Java e.g. Examples of GoF Design Patterns Are they right ?


jeudi 26 février 2015

Adding a parameter to a method that's used called from 100 different places in my project - What's the proper approach?

So I'm working on a codebase, and there's a utility class that deals with generating excel documents for users.


It has a method called putDataInRowColumn(row, column, data)


It has quite a few methods like putObjectsIntoExcel(myBigClass blah) and putObjectsIntoSpecialExcelType(myBigClass blah)


which calls a load of methods like putObjectIntoSpecialRowType(blah.foo(), rowIndex, specialConditions) and putObjectIntoTotallydifferentRowType(blah.bar(), rowIndex, specialConditions)


The point of all this is that the method putDataInRowColumn(row, column, data) gets called a metric buttload, from a bunch of different places. like 100+.


Now, given this legacy code, I needed to modify the method to take additional parameters - styling information. 99% of the methods will now take 'null' as a fourth argument, and 1% will receive an object which contains styling information.


I modified the method signature, to receive the additional parameter, but I found myself having to write a regex to find/replace all of the method calls. it worked, but this felt like the wrong way to go about this.


How should I have done it?


decorator pattern in drawing program

yep, Hi everybody I'm a newbie in design pattern and I want to ask something about decorator pattern


I'm trying to make software about drawing shape like : line, rectangle.... and I want to apply decorator pattern to make effect when I click on "line" in form ....This is my Implement Decorator



class Composite
{}
class line, rect...: Composite
{}

interface UserCommand
{
void Excute();
}

class ClickStyle: UserCommand
{
Composite Concrete;
.....
}

class MoveStyle: UserCommand
{
Composite Concrete;
...
}

Composite Line = new Line();
if(LineClick)
Line = new BorderStyle(Line);
if(LineMove)
Line = new MoveStyle(Line);
....
To add Effect


But how to remove this Effect when User NotClick, and NotMove?


Exp: I Have Line have both Click and Move Effect And I Click Rect ...How to Remove Effect from Line?


I'm not good in English, Sorry For That. Thanks For View this Post... :)


Derive properties as per the requirement...?

So, I have 3 fields/properties. Say, they are, paramA, paramB, paramC. And I’ve three classes as Class A, Class B, Class C.

Requirement is to use:



• paramA, paramB in Class A
• paramA, paramC in Class B
• paramB, paramC in Class D


Is there any way to declare all these 3 properties in a common place and derive in the A,B,C classes as per the requirement....?


Thank you,


Rails need advise on controller practices

I try to follow RESTfull approach in controllers, but sometimes I need action which won't fit into default ones. E.g. I have an index action rendering all articles which is



def index
@articles = Article.all


but what if I also want search them? should I create separate actions for it, or should I bloat existing controller, like:



def index
if params[:search]
@articles = Article.where(id: params[:search_id])
else
@articles = Article.all


What is the right way?


mercredi 25 février 2015

Java Singleton Design Pattern implementation

Can the implementation for a Singleton class can be as simple as below :



public class MyClass {
private final static MyClass myClass = new MyClass();
public static MyClass getInstance() {
return myClass;
}
}


Over :



public class MyClass {
private final static MyClass myClass;
public static MyClass getInstance() {
if(null == myClass) {
myClass = new MyClass();
}
return myClass;
}
}


Which is the better of the above implementations & why?


One thing that I observed is for the first implementation above the object constructor gets called before the static block if any.


Also if there is a thread-safe version of the 2nd implementation (may be a double null check and synchronized block), which should be preferred ?


Facade or Decorator

Context :


I have a REST Service let's say CustomerService which for now has one method getCustomer(id, country). Now requirement is that depending upon country I have to perform different business logic like access different database or some custom rules and then report that I received such a request.


Firstly to solve different implementations depending upon country I used Factory pattern as shown below :


Common interface for all country based implementations



public Interface CustomerServiceHandler{
Cusomer getCustomer(String id, String country);
}


Then factory as



public class CustomerServiceHandlerFactory{
public CustomerServiceHandler getHandler(String country){...};
}


Implementation Detail using Facade


Note this facade is called from REST class i.e.CustomerService



public CustomerServiceFacade{
public Customer getCustomer(String id, String country){
//use factory to get handler and then handler.getCustomer
Customer customer = factory.getHandler(country).getCustomer(id,country);
//report the request
reportingService.report('fetch-customer',....);
return customer;
}
}


Going by the SRP(Single Responsibility Principle), this facade is not achieving a single objective. It is fetcing customer as well as reporting that such request was received. So I thought of decorator pattern as follow.


Implementation using Decorator Pattern:



//this is called from Rest layer
public ReportingCustomerHandler implements CustomerServiceHandler{
//this delegate is basically the default implementation and has factory too
private CustomerServiceHandler delegate;
private ReportingService reporting;
public Customer getCustomer(String id, String country){
Customer customer = delegate.getCustomer(id, country);
reporting.report(....);
return customer;
}
}


//this is called from ReportingCustomerHandler
public DefaultCustomerServiceHandler implements CustomerServiceHandler{
private CustomerServiceHandlerFactory factory;

public Customer getCustomer(String id, String country){
//get factory object else use itself, even default implementation is provided by factory
CustomerServiceHandler handler = factory.getHandler(country);
return handler.getCustomer(id,country);

}
}


Note: In second approach I am reusing the interface CustomerServiceHandler(shown in factory code) for Reporting and Default implementations also.


So what is the correct way, or what is the alternative to this if something more suitable is present.


Second part of the question


What if I have to maintain two different interfaces i.e. one CustomerServiceHandler to implement different countries' implementation and one to serve REST Layer. Then what can be the design or alternative. In this case i think facade would fit.


Node.JS Job / Background Process and high availability

I’m working on the design of a new Node.JS application. I see a lot of options and possibilities on getting a high availability production environment: load balanced apps and reverse proxies, Redis clusters, MongoDB replicas and sharding deployments, etc.


The solution I’m planning have the need of a background process, doing some processing on specific MongoDB tables, and in-memory Redis data. The job needs to run every minute, and I can’t be run in parallel with another instance of the same job.


I know how to build that kind of job in Node using timers. In the other hand, i know I can have some monitoring process probing the job process, but I can see a clear solution on how to replace a failing app in another host.


I found some blog posts about “HA Singleton” (a sort of pattern in the Java world), and database based locks for resolving this situation. May be I can implement a locking mechanism using a lock stored on a Redis replicated data store, with several jobs pooling the lock state, but I guess it will be hard to implement some “extreme” situations (a job pooling the lock state a few milliseconds after a previous job).


There is any pattern of best practice about how to resolve this king of situation?.


Node.JS Job / Background Process and high availability

I’m working on the design of a new Node.JS application. I see a lot of options and possibilities on getting a high availability production environment: load balanced apps and reverse proxies, Redis clusters, MongoDB replicas and sharding deployments, etc.


The solution I’m planning have the need of a background process, doing some processing on specific MongoDB tables, and in-memory Redis data. The job needs to run every minute, and I can’t be run in parallel with another instance of the same job.


I know how to build that kind of job in Node using timers. In the other hand, i know I can have some monitoring process probing the job process, but I can see a clear solution on how to replace a failing app in another host.


I found some blog posts about “HA Singleton” (a sort of pattern in the Java world), and database based locks for resolving this situation. May be I can implement a locking mechanism using a lock stored on a Redis replicated data store, with several jobs pooling the lock state, but I guess it will be hard to implement some “extreme” situations (a job pooling the lock state a few milliseconds after a previous job).


There is any pattern of best practice about how to resolve this king of situation?.


Passing an iterative object reference to the factory in PHP?

I have a class that takes some basic HTML5 and with some DOM magic turns it into a class which is an extension simpleXMLElement.


Thus we might have



<?php
$MyPage = new XPage($HTML);


So far so good. What I now need to do is select some parts of the XML doc so that they can be "bookmarked" (I am sure that there is a better name for it) so one can go like this



$MyPage->ThatBit("foo")->addChild('p',$MyParagraph);


Ideally I would like to be able to go



$MyPage->page()->body->header->RememberThisBitAs("foo");


Or something intuitively similar. The idea being that the most commonly access areas can be gotten to more smoothly.


However it is the XPage class that holds the array of "bookmarks" which would leave me doing nasty things like



$MyPage->addBookmark("foo",
$MyPage->page()->body->header->getChildren() );


Which just does not seem right.


or



$MyPage->page()->body->header->RememberThisBitAs("foo",$MyPage);


which is not so bad but still "feels" wrong.


How do I approach this without excessive object coupling or ugly self referencing?


Compare two images of the same pattern

I need to write a python script that will determine whether two images contain the same pattern. If the patterns are the same, it should result in a match whether the colors or anything else may be different. What is the best way to do this?


OOD Questions: Furniture Wood Metal Chair Table

A furniture can be made of Wood, metal or may be something material (in future). The furniture can be of different types like chair, table etc Now a wooden furniture must be tested against charcoal properties. A metal furniture must be testes against electricity conductivity. How will we design it's OOD.


I don't know whether following approach is correct or not.



Interface MaterialTesting { Testing ();}

Public class WoodTesting implements MaterialTesting
{ // define body for wood testing method testing(); // }
Public class MetalTesting implements MaterialTesting
{ // define body for metal testing method testing(); // }

Public Class Furniture
{
WoodTesting woodtestObject;
MetalTesting metaltestObject;

Furniture(MaterialType material)
{
if material isInstanceOf(WoodTesting)
woodtestObject = new WoodTesting ();

if material isInstanceOf(MetalTesting)
metaltestObject= new MetalTesting ();
}
}
Public Class Chair extends Furniture
{
Chair(MaterialType material)
{
super();
}
}

Class DriverClass{
PSVM()
{
Furniture woodchair = new Chair(wood);
Furniture metaltable = new Table(metal);

woodchair.Testing();
}


And we have to declare another MaterialType class.


Also, please tell how it can be implemented using Factory design pattern.


Design patterns - adapter and proxy

I need to realize a connection between two design patterns - adapter and proxy - on the chosen issue. The problem is I do not even have an idea on what topic to choose. I will use Java.


Could You suggest me a topic that will be not-so-hard to complete?


I googled a bit but without an effect.


Problems with OO design for application with pluggable components

I'm trying to refactor an ugly code and make it easly extendable in the future.


The application should be nothing else but a series of components that have input(s) and output(s). The components are chained in such manner that the current component's input is the output of one (or more) previous components.


Here's a quick overview of what I have so far:




  1. Reader



    • Denotes a data source

    • Can be a file on HDD, online resource, database, etc.




  2. Splitter



    • Input is Reader(s)

    • Splits the contents of what reader delivers into parts

    • Outputs are split contents of Reader(s)




  3. Model



    • Input is Splitter(s)

    • Creates a model of something based on Splitter(s) outputs

    • Output is silent, but you can say that the output is an internal state that can be queried for individual inputs




  4. Tester



    • Input is a model

    • It can query a model for a result on some data

    • Output is optional, but in case it is used, it's a stream of (queryInput, queryOutput) data




  5. Writer



    • Input is practiacally anything that produces a collection of objects

    • Writes that collection to wherever

    • I dunno what the output should be right now




So, I want to do have the ability to plug them in the following manner:


-->Reader-->Splitter-->Model-->Tester-->Writer-->


However, this would also be a valid combination (it obviously does nothing more but a simply data transfer)


-->Reader-->Writer-->


Now, since I'd like to be able to plug (almost) everything to everything and (possibly) create quite long chains, I'd assume I'd have to have some sort of Pluggable interface.


Also, when creating such big chain, I'd probably want to wrap it behind a Facade. And since I'd want each pluggable component (class) to be replaced by some other, then Strategy pattern comes to mind.


Now, since I've already mentioned the term chain here, Chain of Responsibility pattern comes to my mind, in the following (or similar way):



public interface Pluggable<InputType, OutputType> {
public void consume(Pluggable<?, InputType> previous);
public Collection<OutputType> produce();
}


For example, if I wanted to have my Splitter to split a list of Files provided by Reader, it might looks something like this:



public class Splitter<InputType, OutputType> implements Pluggable<?, InputType> {
public void consume(Pluggable<?, InputType> previous) {
// retrieves for example a list of InputType objects
}

public Collection<OutputType> produce() {
// filters the collection it got and returns a sublist for example
}
}


In the end, the components might look something like this:


Reader<File, Foo> --> Splitter<Foo, Foo> --> Model<Foo, Void> --> Test<Model, Bar> --> Writer<Bar, DAO>


I don't know how else to describe the problem I'm having, but I'm sure something like this is quite achieveable. For visual example, here's the image of RapidMiner's process


RapidMinerChainExample


Note that I'm not trying to replicate or copy Rapid Miner, it's just that the project I was assigned looks like it can be implemented in simiar way.


I'd appreciate any help regarding how to design such application.


Implement MVC in webservice based Android app

I have to develop an application which is webservices-based. We have to call soap methods, parse the result and use it. Now I want to follow MVC architecture for this project. Please guide me how I should distributes Activity, Service, Fragment, BroadcastReceiver, SoapHelpers(classes to call the SOAP methods and parse the same), View, data and Adapter class in this architecture.


Pattern to communicate with a thread

I have a class OuterClass that contains a List and there is a thread ListWorker that is started in OuterClass that is adding some elements to the list. Based on a function call to OuterClass , it should be able to inform the thread to delete elements. What is the best practise? The intention is not to have a blocking data structure (no synchronization) and therefore having a single thread work on List.



Class OuterClass {
List<String> list = new ArrayList<String>();
ListWorker worker = new ListWorker(list);

deleteLastElement() {
worker.setDeleteLastElement(true);
}
}


The worker



ListWorker implements Runnable {

private List<String> list;
private volatile boolean deleteLastElement;

public void setDeleteLastElement(boolean deleteLastElement) {
this.deleteLastElement = deleteLastElement;
}

public ListWorker(List<String> list) {
this.list = list;
}

public void run() {
while(true) {
//add random elements

if(deleteLastElement) {
//delete last element
//set the boolean now to false
}
}
}

Sed Range of Patterns only if it contains Pattern

What i would like to know is how to print a Range of Patterns but only if it contains a specific Pattern.


For example:


I have a file that contains:



HEADER 1
AAA
BBBBBBB
MSG:testing
CCCCCC
DDD
PAGE 1

HEADER 2
EEE
FFFFFF
GGG
HHH
PAGE 2


I want to print from any HEADER to any PAGE but only if it contains the pattern MSG


The result i want is to print only these section:



HEADER 1
AAA
BBBBBBB
MSG:testing
CCCCCC
DDD
PAGE 1


What i have so far is: sed -n -e '/HEADER /,/PAGE /p' inputfile.txt > outputfile.txt


I'm open to any suggestions including the usage of Awk or Grep.


Thanks in advance.


Can I use Unicode characters as regex patterns when using re2 library?

I want to know if the re2 library can handle all kind of special characters. I have to mention that I've done a lot of research on the net but didn't find anything that can make me understand. Thank you!


Creating a Singleton class with builder capabilities

Consider the following hypothetical Singleton class DateSingleton which currently looks like the following:



public class DateSingleton {

private static DateSingleton instance = new DateSingleton();

private String year;
private String month;
private String day;

private DateSingleton() {
}

public static DateSingleton getInstance(){
return instance;
}
}


This Singleton can be thought of as a date keeper, and only one of them will exist for my entire web application. I would like to be able to make the following type of builder-style call to assign my state:



DateSingleton.getInstance().year("2015").month("February").day("25");


Can someone suggest what code I would need to add to the DateSingleton class in order to make this possible? Is it considered bad practice to make a Singleton a builder?


I realize that I could just add getters and setters to accomplish the same funtionality. But I want to move away from this, as there may be many properties in this Singleton and the builder pattern makes the code much easier to use and read.


What is a better more testable way for Repository based on tenants

I have a repository that receives a data layer as parameter and a tenantID like this. (Code is simplefied)



public class MyRepsitory{

private readonly IDataAccess _dataAccess;
private readonly string _tenantID;

public MyRepsitory(IDataAccess dataAccess, string tenantID)
{
_dataAccess = dataAccess;
_tenantID = tenantID;

}
}
}


This repository has also a method GetClientsForTenantID which is private and this is basically my point because every method relies on GetClientsForTenantID and this not ideal for unit testing because I cannot stub or mock GetClientsForTenantID in my current design. This is my current signature of the GetClientsForTenantID method at the moment. private IEnumerable<string> GetClientsForTenant(string tenantID) I want the repository to take care of it as internal behavior, that's why it is private. I do not want it as public member because then it is mutable for other developer and my api would not be reliable. I could have made it virtual so that a Mocking Framework could proxy it, but that didn't feel right, either.


It would need to have some fakeClients injected only for testing, or something else...


This shows the issue I am having in code. For example I cannot test my GetProducts() -Method



public IEnumerable<Product> GetProducts(string someParameter){

var clients = GetClientsForTenant(this._tenantId);

//do some logic that needs to be tested
}


The other thought that I had was Injecting an ITenantStore basically a class that takes care of resolving the clients base on the tenantID. But this would also needs to get the IDataAccess passed in and would do things that should do the repository.


Like this:



TenantStore(IDataAccess dataAccess, string tenantID)

MyRepository(IDataAccess dataAccess, ITenantStore tenantStore)


does also not feel right because of the IDataAccess all over the place...


What would be you recommended way to solve this? Any hints tips?


parameter based different result format

My task is to write a program to store files in object store. One of the subtasks requires to send json or xml format response to the file uploader/downloader as requested by client. The following rules must be followed:



entry
+-------------------------+
v v
upload download
+-----------+ +--------------+
v v v v
succ err succ err
+-----+ +-----+ +-----+
v v v v v v
json1 xml1 json2 xml2 josn2 xml2



  1. if user uploads file with success, return json/xml type 1

  2. if user uploads file with error, return json/xml type 2

  3. if user downloads file with success, do nothing

  4. if user downloads file with error, return json/xml type 2


I've managed to solve the task but I'm not satisfied with the class dependencies I got. I think mixture of abstract factory and strategy are suitable for the issue. Can you give me a hint how to deal with the problem?


Camel RabbitMQ Request Response Pattern Example

I'm looking for a sample code wich use the Camel RabbitMQ Request Response Pattern.


My use case : - A request message is depose in a RabbitMQ Queue - A Camel route consume the message, invoke an external Web Service, and reply the response based on the reply-to properties of the message


I also implement this use case using Spring AMQP but I want to do it with Camel RabbitMQ too.


Camel Documentation : http://ift.tt/1ihKfd4


Thanks for your help.


Arnaud


Looking for a loader design pattern

Let's say I have the following classes whose instances store their property somewhere for e.x. in a JSON file or a database:


Class Foo



abstract class Foo
{
protected $ID;
protected $title;

// getters and setters
}


Class Bar (extends Foo)



class Bar extends Foo
{
protected $text;

// getters and setters
}


Class Baz (extends also Foo)



class Baz extends Foo
{
protected $tabs = array();

// getters and setters
}


What's the best way to load them from the data source?


How I do it now (not satisfying)


My abstract class Foo has a method load($ID, PDO $pdo). This method is overwritten by Bar and Baz which extends the general loading of the title property in Foo class with their own properties which have to be loaded.


So in code this would look something like this:


Class Foo



abstract class Foo
{
protected $ID;
protected $title;

public static function load($ID, PDO $pdo)
{
$result = null;

// SQL query for getting $title property into $result

return $result;
}

// getters and setters
}


In the class Bar I do this:



class Bar extends Foo
{
protected $text;

public function __construct(stdClass $data)
{
$this->ID = $data->ID;
$this->text = $data->text;
}

public static function load($ID, $pdo)
{
$generalInfo = parent::load($ID, $pdo);

$result = null;

// PDO query for getting $text property into $result

$generalInfo->text = $result;

return $generalInfo;
}

// getters and setters
}


So this let me call $dataToCreateInstance = Bar::load(4, $pdoInstance) and returns the needed information to instanciate the specific Bar object with ID 4.


The probleme here is (as you can see) my classes are bound to PDO also it's really ugly to implement a load method for each data source so it's not generic at all.


What I want to achieve


I'm looking now for a pattern which let me load those classes from any source. I thought about a Loader class which looks like this:



class LoaderManager
{
/**
* @var Loader[]
*/
protected $loaders = array();

public function registerLoader($className, $loaderClass)
{
$this->loaders[$className] = $loaderClass;
}

public function loadClass($class, $ID)
{
return $this->loaders[$class]->load($ID);
}
}


and with an abstract Loader class



abstract class Loader
{
public abstract function load($ID);
}


So now I have decoupled the thing. The problem with this attempt is that I have always to provide an additional Loader for the class itselfs. So for the class Bar I have to provide at least one of BarLoaderPDO or BarLoaderJSON. Which is somehow not that elegant and feels a bit "wrong".


Also there is the problem that I have to store somewhere the mapping which class in the current application has to use which loader.


But it is the only attempt I can think of which leads me to that what I want to achieve.


I like now to discuss and hear if there are other (better) attempts and how to realize them.


mardi 24 février 2015

Mvc Application Cache

how can i build data cache for my Application with Repository Pattern? With lock object and persist for each session...



public sealed class NewsCache
{
List<int> _tagsIds = null;
static NewsCache _instance = new NewsCache();
private static readonly object LockObject = new object();
private readonly NewsManager _newsManager = new NewsManager();
public static NewsCache Instance
{
get
{
lock (LockObject)
{
if (_instance == null)
{
_instance = new NewsCache();
}
return _instance;
}

}
}

private NewsCache()
{

}
}

MVC Mapping between View Model and Request-Response messaging pattern

I have the following MVC design pattern issue and confused which way to go.


In the UI layer, a View Model is used in a Controller action method. Cool.


The Service layer uses the Request-Response message pattern, so the service class method has a Request object as a parameter (in), and the method returns a Response object (out). This method calls a Repository method with a Domain object parameter. In other words, to call the service method, you need to populate the Request object with your data, and the method returns results in the Response object, i.e. request-response messaging.


To pass your data in your View Model to the Domain object in the Service method, you have two options AFAIK:



  1. Ensure the Request object contains the same properties as the View Model properties, then you can map (manually or automatically) values from the View Model to the Request object.

  2. The Request object contains a property of the View Model, i.e. instance of the View Model now lives in the Request object (different from above option - only one property). Now you can simply assign the View Model to the property in the Request object.


I see flaws in either approach...


In option 1, if the View Model has many properties, and you are using a mapper (e.g. AutoMapper), in the Controller method you need to automap the properties from the View Model to the Request object. Then in the Service layer, in the service method you need to automap the properties in the Request object to the Domain object. Two levels of mapping - very wrong!


In option 2, the Request object contains a property containing the View Model. You can then automap the Request.vm (property) to the Domain object easily and efficiently, but this for some reason look like poor design to me! I'm concerned about this design.


Which is the best approach? Or is there another better approach to mapping between VM and R-R pattern?


How to save memory space using JavaScript Prototype [duplicate]


Take this as an example.



function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;

this.toString = function() {
return this.model + "has done " + this.miles + " miles";
};
}


And we have this:



function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
}

Car.prototype.toString = function() {
return this.model + "has done " + this.miles + " miles";
};


And we declare two objects:



var civic = new Car("Honda Civic", 2009, 20000);
var mondeo = new Car("Ford Mondeo", 2010, 5000);


My question is : if we declare function toString inside Car(), or declare function toString outside the Car(), will this make a difference in memory space?


My thought is: the later one, declare function using prototype, outside its constructor, will save memory space, am I right? Why?


Dependency inversion principle: trying to understand

I'm learning design patterns and things around it (like SOLID and Dependency inversion principle in particular) and it looks like I'm loosing something:


Following the DIP rule I should be able to make classes less fragile by not creating an object in the class (composition) but sending the object reference/pointer to the class constructor (aggregation). But this means that I have to make an instance somewhere else: so the more flexible one class with aggregation is, the more fragile the other.


Please explain me where am I wrong.


Pattern matching in VBS

Using this as a reference: http://ift.tt/18idBeX


I've been trying to figure out how to create a pattern to pull this:


LicenseDetail.asp?SID=&id=F1A32D21A83C2BB2BBF227E5443A6023


Out of this:



height='40'><td colspan='1' width='20%' align='center'bgcolor='#e9edf2'><font face=verdana color=#000000 size=-1>Real Estate Broker or Sales</font></td><td colspan='1' align='center' bgcolor='#e9edf2'><font face=verdana color=#000000 size=-1><a href='LicenseDetail.asp?SID=&id=F5A76372AAA358B9CD869630255FA424'>ALMEIDA, JOHN SOBRAL</a></font></td


I've tried a number of different combos, but I'm not even close...


For example, based on what I'm reading, seems like the () should grab literal and the \alphanumeric should grab the trailing numbers and letters and stop before the ' (since it's not a number or letter)...fail: "(LicenseDetail.asp?SID=&id=)\alphanumeric"


Thanks in advance.


Java - Efficient JComponent updating design pattern

I have a single-threaded program (essentially a character generator) that I'm writing. I have a model class which houses pretty much all of the character's information. I want this to be represented in the GUI. I want the GUI to update every component anytime a value is changed for any field.


I currently have the GUI class set up as an Observer to the Character class, so anytime updates to the Character are performed, the GUI is updated. But, this is only part of the functionality I want, as I want each GUI field updated each time a GUI field is changed.


Would it be bad form to write a single changelistener class that updates every field and add it to every JComponent in the GUI class. This seems kind of hacky/potentially buggy to me. Any suggestions for a better design pattern?


Currently I have around 50 JComponents that display data and will be adding at least as many as development goes on. So, I kind of wanted to keep from screwing myself in the long run. Thanks for insight in advance!


Is using images as buttons a good design principle for winforms? [on hold]

I'm developing a windows forms application in C#. Is it a good practice to design all the buttons, background and the entire UI using images rather than using custom user controls or third party user controls like Telerik or Devexpress?


Ofcourse I understand I can't do this for certain controls like grids.


But, other than that, Is it ok to do it this way in terms of best practices and performance?


Thanks.


P.S : I'd love to use HTML5 for the design if that were possible and I don't currently use WPF since my project requires winforms.


how represent type/status like array in entity

In symfony2 I have an entity Foo which has a field named $kind that can have some(at most about 10) different values(one at each time) something like this:



$kindArray('1' => 'type1', '2'=> 'type2');


and $kind field can get one of $kindArray indices.


I want one location that have $kindArray and use it for choiceType values when creating FooFormType.


how can I show it in entity? should I use array or something like value object?


C++ Dimensional Analysis (Barnes and Nackman) with Scale

I was recently reading the series on the C++ Source, “A Pause to Reflect: Five Lists of Five”. In Part V, Scott Meyers discusses the Barton and Nackman solution to the units problem. As an embedded software engineer for the aerospace industry, this particular Aha! Moment got me excited. Up until this point I’ve not heard of this approach (nor these authors).


I have done research trying to find more information regarding the solution. I came across this presentation here: http://ift.tt/18hs4rz


I think I understand everything that I have read on this solution. But I feel like there is a piece of the puzzle missing. Nowhere does this beautiful, elegant solution address scale. Specifically I am interested in conversions that are more than just a multiplication factor. For example, Temperature converting between Kelvin, Celsius, and Fahrenheit. I would like to be able to use these temperatures interchangeably.


My Questions:




  1. Did I miss something? Is scale discussed somewhere in reference to the Units solution discussion that I have overlooked?




  2. If not, How could I approach this problem further? Is there an existing pattern that could be used in combination with the B&N approach to complete the solution?




Note: I have seen the BOOST UNITS solution to the problem and I don’t like it. To me it is very unreadable. Nor am I, typically allowed to use external libraries such as boost.


Backup Data:


The Units Class as described:



template<class T, // Precision
int m, // Mass
int l, // Length
int t, // Time
int q, // Charge
int k, // Temperature
int i, // Luminous Intensity
int a> // Angle

class Units
{
public:
// ------------------------------------------------------
explicit
Units (T initVal = 0)
: val (initVal)
{
}

// --------------------------------------------------------------------
// Operator: Assignment from type T
Units<T, m, l, t, q, k, i, a>&
operator= (const T rhs)
{
val = rhs;
return *this;
}

// --------------------------------------------------------------------
// Operator: Type Converstion to T
operator T () const
{
return val;
}

// --------------------------------------------------------------------
// Operator: +=
Units<T, m, l, t, q, k, i, a>&
operator+= (const Units<T, m, l, t, q, k, i, a>& rhs)
{
val += rhs.val;
return *this;
}

// --------------------------------------------------------------------
Units<T, m, l, t, q, k, i, a>&
operator-= (const Units<T, m, l, t, q, k, i, a>& rhs)
{
val -= rhs.val;
return *this;
}

// --------------------------------------------------------------------
Units<T, m, l, t, q, k, i, a>&
operator*= (T rhs)
{
val *= rhs;
return *this;
}

// --------------------------------------------------------------------
Units<T, m, l, t, q, k, i, a>&
operator/= (T rhs)
{
val /= rhs;
return *this;
}

// --------------------------------------------------------------------
// Get Reference
T&
Val ()
{
return val;
}

// --------------------------------------------------------------------
// Get Value
const T&
Val () const
{
return val;
}

private:
T val;
};

// ----------------------------------------------------------------------------
// Operator: Addition
template<class T, int m, int d, int t, int q, int k, int i, int a>
const Units<T, m, d, t, q, k, i, a>
operator+ (const Units<T, m, d, t, q, k, i, a> & lhs,
const Units<T, m, d, t, q, k, i, a> & rhs)
{
Units<T, m, d, t, q, k, i, a> result (lhs);
return result += rhs;
}

// ----------------------------------------------------------------------------
// Operator: Subtraction
template<class T, int m, int d, int t, int q, int k, int i, int a>
const Units<T, m, d, t, q, k, i, a>
operator- (const Units<T, m, d, t, q, k, i, a> & lhs,
const Units<T, m, d, t, q, k, i, a> & rhs)
{
Units<T, m, d, t, q, k, i, a> result (lhs);
return result -= rhs;
}

// ----------------------------------------------------------------------------
// Operator: Multiplication
template<class T, int m, int d, int t, int q, int k, int i, int a>
const Units<T, m, d, t, q, k, i, a>
operator* (const Units<T, m, d, t, q, k, i, a> & lhs,
const Units<T, m, d, t, q, k, i, a> & rhs)
{
Units<T, m, d, t, q, k, i, a> result (lhs);
return result *= rhs;
}

// ----------------------------------------------------------------------------
// Operator: Division
template<class T, int m, int d, int t, int q, int k, int i, int a>
const Units<T, m, d, t, q, k, i, a>
operator/ (const Units<T, m, d, t, q, k, i, a> & lhs,
const Units<T, m, d, t, q, k, i, a> & rhs)
{
Units<T, m, d, t, q, k, i, a> result (lhs);
return result /= rhs;
}

// ----------------------------------------------------------------------------
// Operator: Multiplication (Creates New Type)
template<class T,
int m1, int d1, int t1, int q1, int k1, int i1, int a1,
int m2, int d2, int t2, int q2, int k2, int i2, int a2>

// Return Type
Units<T, m1 + m2, d1 + d2, t1 + t2, q1 + q2, k1 + k2, i1 + i2, a1 + a2>
operator* (const Units<T, m1, d1, t1, q1, k1, i1, a1>& lhs,
const Units<T, m2, d2, t2, q2, k2, i2, a2>& rhs)
{
// New Return type
typedef Units<T,
m1 + m2,
d1 + d2,
t1 + t2,
q1 + q2,
k1 + k2,
i1 + i2,
a1 + a2> ResultType;

return ResultType (lhs.Val() * rhs.Val());
}

// ----------------------------------------------------------------------------
// Operator: Division (Creates New Type)
template<class T,
int m1, int d1, int t1, int q1, int k1, int i1, int a1,
int m2, int d2, int t2, int q2, int k2, int i2, int a2>

// Return Type
Units<T, m1 - m2, d1 - d2, t1 - t2, q1 - q2, k1 - k2, i1 - i2, a1 - a2>
operator/ (const Units<T, m1, d1, t1, q1, k1, i1, a1>& lhs,
const Units<T, m2, d2, t2, q2, k2, i2, a2>& rhs)
{
// New Return type
typedef Units<
T,
m1 - m2,
d1 - d2,
t1 - t2,
q1 - q2,
k1 - k2,
i1 - i2,
a1 - a2> ResultType;

return ResultType (lhs.Val() / rhs.Val());
}


This class allows us to write code that looks like this:



// Base Types
typedef Units<double, 1,0,0,0,0,0,0> uMass;
typedef Units<double, 0,1,0,0,0,0,0> uLength;
typedef Units<double, 0,0,1,0,0,0,0> uTime;
typedef Units<double, 0,0,0,1,0,0,0> uCharge;
typedef Units<double, 0,0,0,0,1,0,0> uTemperature;
typedef Units<double, 0,0,0,0,0,1,0> uIntensity;
typedef Units<double, 0,0,0,0,0,0,1> uAngle;

// Derived Types
typedef Units<double, 0,2, 0,0,0,0,0> uArea;
typedef Units<double, 0,3, 0,0,0,0,0> uVolume;
typedef Units<double, 0,1,-1,0,0,0,0> uVelocity;
typedef Units<double, 0,1,-2,0,0,0,0> uAcceleration;
typedef Units<double, 1,1,-2,0,0,0,0> uForce;


uMass mass;
uTime time;
uForce force;
uLength length;
uVelocity velocity;
uAcceleration acceleration;

// This will compile
mass = 7.2;
acceleration = 3.5;
force = mass * acceleration;

// These will not compile ** Enforcing Dimensional Unit Correctness
force = 7.2 * acceleration;
force = mass;
force *= acceleration;

Invoke a function if it has a defined Decorator Pattern

I don't know if I'm using the wrong pattern or what. I'm have a standard class and 3 decorators:



MyClass, Dec1, Dec2, Dec3.


everyone implements MyClassInterface { getDescription(), addDescription(String t) }. But Dec2 has also the function { specialFunction() }.


I create an instance:



MyClassInterface instance = new Dec1(new Dec2(new Dec3(new MyClass())));


then I would call the specialFunction, but I can't! If I would have done this with Dec1 that extends Dec2, that extends Dec3, that extends MyClass, would have been possible.


It would be nice having a function like



decoratorInstance = instance.hasDecorator(Dec2)
decoratorInstance.specialFunction()


But I don't know if it is possible without making a huge pattern mistake.


Dependency injection on data objects

I started writing tests for my (python) application and I found dependency injection very helpful. I refactored lot of my code, and it was so easy to write tests. But some classes was tricky.


I have class Application which is data structure containing attributes like name, type, etc. It have also few methods returning somehow modified those attributes. No problem with that, but there is an method instances (obviously) returning instances of the application in a form of list of Process objects.



class Application(object):
...
def instances(self):
return Processes.all().filtered(lambda process: process.name() == self.name)


You can see the dependency on Processes class. What should I do?


I have implemented it this way, because when I got an Application object from somewhere, I can simply call a.instances(), got the list of processes and don't care.


But from testing point of view, I would like to say "hey application, don't search for real processes in the system, look in this mocked processes list".


First possible solution which comes to my mind, was



def instances(self, processes=None):
processes = processes if processes else Processes.all()
return processes.filtered(...)


but it kind of means that probably all of my calls will have specified that argument. And a.instances(some_processes_list) is not that pretty as a.instances() and may be confusing. Would you consider it as confusing?


What approach or pattern would you recommend please?


Thank you, FrostyX


PHP object oriented form generator

I am trying to create an object oriented form generator. Please keep in mind it will be used only by a handful of people in our company to solve a specific problem.


I am currently facing two little caveats.


Syntax of creating elements


There are few approaches I can take.


Setting everything in constructor. As a drawback this could result in inconsitent constructor usage



Input::create('text', 'name', array('maxlength' => 10));


Limit constructor to type and expose only the most used attributes as methods (keep one method for mass attribute setting)



Input::create('text')->name('name')->value('value')->attribute('max_length', 10);


Expose every attribute as method with either creating a method for every attribute or with __call magic method which will result in no autocomplete support in an IDE. And even now, I can keep the attribute method.



Input::create()->type('text')->name('name')->value('value')->max_length(10)->id('id'); //etc.


At the moment, I consider the second approach as the best one, since it keeps "good" stuff from both worlds. As still provides a way to abstract some of the work, since e.g. method required would not only set the required attribute, but also mark this field for validation object as required.


Code duplication with approach 2 and 3


Since there are attributes that can be used by every element, but also attributes that are only usable by 3 or 4 elements, e.g. HTML5 attribute form.


Every element can inherit from base element which has methods for attributes that are universal for every element (e.g. name). Partially usable attributes can be solved with interfaces, but this leads to code duplication as they cant contain method body.


Traits would be the solution, but sadly, I am stuck at PHP 5.3 with no way to upgrade. That leaves me with either implementing Mixin or Composition pattern, which again, might lead to no autocomplete support. This would be partially mitigated when using second approach.


So to my actual question:


Which approach can end as most suitable? (suitable as in minimal code duplication, solid code reuse and easiness of implementation)


I realize this might very well spawn opinion based answers so I apologize in advance if it does.


Good name for object that creates and updates another object

I have a scene containing scene objects, which represent space objects. When the space object gets modified or deleted, the corresponding scene object gets updated or erased from the scene as well.


I use a third class, currently called scene object updater which creates and owns the scene object, adds and erases it from the scene, and recreates a new one when the space object has changed.


What would be a good name for this class? For example scene object updater, creator, manager, holder, wrapper, ...


Scala : constructor cannot be instantiated to expected type found

I tried to pattern match against the simple class below



case class Name(first : String, second : String)


with



val n = Name("John","Doe")
n match{case Name(x,y) => x + y}


But I got this error



error: constructor cannot be instantiated to expected type;
found: Name
required: Name


I don't understand why it is so since both found and required are of the same type.


Any help?


MVVM dependency on javascript libraries?

I am familiar with MVC but not MVVM. I checked various posts related to difference between MVC/MVVM/MVP.


Even I checked Microsoft's office link http://ift.tt/1D6PpDV but each time I found a common thing among these links is that, they explained implementation of MVVM using third party JavaScript libraries (Angular, knocknout, Ember etc).


Does it means that MVVM is dependent on these type of libraries ? Is it possible to implement MVVM using simple jquery? Please clarify about this concept.


Thank you.


How to use "Composite Design Pattern" with Ninject

Validation Rule Contract:



public interface IValidationRule
{
bool IsValid();
}


Concrete Validation Rule:



public class MyClass : IValidationRule
{
public bool IsValid()
{
return true;
}
}


Composite:



public class ValidationRuleComposite : IValidationRule
{
private readonly IEnumerable<IValidationRule> _validationRules;

public ValidationRuleComposite(IEnumerable<IValidationRule> validationRules)
{
_validationRules = validationRules;
}

public bool IsValid()
{
return _validationRules.All(x => x.IsValid());
}
}


When I ask the containter for IValidationRule I want to get ValidationRuleComposite. If I ask the container for a list of IValidationRule I want to get all implementations of IValidationRule except of the ValidationRuleComposite.


How can I achieve this with Ninject?


Convert a Composite Pattern to a new one with additional behavior

I'm running a little problem with our design. We have an internal framework in whcih we are using the composite pattern to represent a hierarchical data structure (sorry I cannot post images due to reputation...):



  • IEntity: with a "Name" property"

  • LeafEntity (abstract): "Name" is virtual

    • LeafEntityA

    • LeafEntityB

    • ....



  • ContainerEntity (abstract): "Name" is virtual, "Children" is IList

    • ContainerEntityA

    • ContainerEntityB

    • ....




This hierarchical data structure is returned by a "Read file" method from the framework to our application and is also used by other application.


Now in our application, we need exactly the same data structure (a composite pattern) but with additional behavior: we need an extra GetCompareText() method for each entity. And this method should be definable in each entity:



  • ContainerEntity should implement the default behavior for the GetCompareText method for "Containers"

  • LeafEntity should implements the default behavior for the GetCompareText method for "Leaves"

  • Some leaf entities can ovveride the behavior (For example, LeafEntityA must override the behavior, but LeafEntityB must have the default behavior)

  • Some Container entities can override the default behavior (ContainerEntityA uses default behavior, when ContainerEntityB overrides it).


How can we achieve this ? Do we need another Composite Pattern in our Application? Is Decorator pattern an option ?


I hope I was clear enougth


Thanks for your assistance!


Benoît


lundi 23 février 2015

Handler Vs Adapter Vs Controller

I often come across the three design jargon Handler, Adapter(Adaptor) and Controller classes. The definition of these three classes that is providing implementation for internal and external triggers appears to be ambiguous. Can somebody help me understand the contexts in which these class types can be used?


Composition class; using super or sub?

Let's consider two classes, super and sup extending super:



Class SuperClass{
int superDataMember;
}

Class SubClass extends SuperClass{
int subDataMember;
}


I need to have another CompositeClass class that may use super or sub composition depending on some criteria. My question is: Should I use




  1. An instance of SuperClass inside CompositeClass



    • Thus, I can use either SuperClass instance or SubClass instance.

    • But how will methods accessing subDataMember behave if the accessed instance is of SuperClass?


    • Maybe an instanceOf check may work at the beginning of each method?



      Class CompositeClass {
      private SuperClass sc;

      public getSuperDataMember () {// some code}
      public getSubDataMember () {
      if (this.sc instanceOf SubClass)
      // some code
      }
      }





  2. An instance of SubClass inside CompositeClass




    • Thus, I will lose the ability to access SuperClass instances!



      Class CompositeClass {
      private SubClass sc;

      public getSuperDataMember () {// some code}
      public getSubDataMember () {// some code
      }
      }





  3. Implement two versions of CompositeClass, the first is SuperCompositeClass with an instance of SuperClass and the second SubCompositeClass that extends the first with an instance of SubClass!




How can I combine Identity and Application DataContext classes?

When you create a EF6 project you get an out of the box implimentation of a datacontext specifically for managing your identities:



public class IdentityContext : IdentityDbContext<ApplicationUser>
{
public IdentityContext()
: base("DefaultConntection", throwIfV1Schema: false)
{
}

public static IdentityContext Create()
{
return new IdentityContext();
}
}


Being a bit pedantic myself I would like to seperate my application datacontext into a seperate Dat project that ONLY deals with the data access, so this project would reference EF dlls but not ASP Identity components.


It would be as simple as



public class AppContext: DbContext
{
public AppContext(): base("DefaultConntection"){}

public DbSet<Customer> Customers { get; set; }
}


Of course this means I can't put the IdentityContext into this Data project, because I don't want to pollute my Data dlls, at the same time I don't want TWO Data access points.


How can I combine these two without polluting my Data project with Identity references? Is there a way I can use composition, partial classes or similar?


Design: Object with single use?

Context


I have a class called ImageLoader.


When I call ImageLoader's getPicture( pictureID ), if the picture is not cached, I store pictureID in an instance variable, create a new thread which eventually calls my callback() function in this same ImageLoader class. callback() then uses this pictureID as the key to cache the picture.


Problem


Do you see the pickle? If I call getPicture( somePictureID ) twice in a row, and the callback() function for the first call hasn't happened yet, I will overwrite the previous pictureID which the callback() function will use.


Now I know you're thinking, why don't I just add a little synchronization on the variable to make it thread-safe?


Because who knows how long the thread querying the picture will take, and that could really slow down the whole process of loading multiple images.


How I'm Thinking of Solving It


So my bright idea is to create in inner class that servers as a slave and only has a single use. I execute some function in this slave class once, and I never reuse the object.


Question


Is this an appropriate approach to solving this kind of problem? I feel like this might fall into some pattern I'm not aware of. If I'm totally off the mark with this one, can you suggest another solution?


Architecture tip on how to deal with Premium accounts, plan duration and renewal

I'm creating a website which has a premium user feature. I'm thinking on how to design the database to store the premium user plan, and how to check it..


My main idea so far is:



  • Having 2 fields on the user table: premium (boolean) and expires (date)

  • When user does payment, it will calculate the plan duration, set premium to 1, and the expire date to the end of the duration

  • Every time I check if user->isPremium(), it will also check if it's expired.. if so, set it back to zero and offer a renewal

  • Aside from this, all payments /transactions will be recorded in a logs table for record keeping.


This is a simple design I thought, but since this is a common feature on many websites, I thought of asking you guys.. how do the pros do this?


This probably won't make much difference on the design but I'll use Stripe for handling payments.


Triggering events with EPL

I have to define e query to select events that flows in this way:


let's imagine a tunnel with several videocameras within (let's say 3 videocameras) and two exits (Exit_A and Exit_B). Moreover, let's imagine that Exit_A is checked by all videocameras (3) and Exit_B is checked by 2 (excluding the last one).


To consider all people exiting from Exit_A I wrote the following EPL:


"select * from pattern [every camera1=Videocamera-> (camera2=Videocamera(id=camera1.id) -> camera3=Videocamera(id=camera2.id) ->exit=Exit(id=camera3.id))]"


Where Videocamera and Exit are beans I defined.


I considered that a person who exits from Exit_A must pass under videocamera1, then videocamera2 and finally under videocamera3, so I defined a pattern "every A->(B->C->Exit)" where I considered the id of person passed. I understand that person exit from Exit_A as it passed all 3 videocameras.


But if I want to check also all people exiting from Exit_B how can I enrich my EPL? How can I understand where does a flow of people exit in an EPL query?


Is there a name for this design pattern (dynamically wrapping around another class)?

Suppose I have a class uicontrolWrapper, which is a wrapper for a uicontrol (but does not subclass it). The uicontrol stuff is kept in a private property for uicontrolWrapper. Basically, I want to be able to do set/get against the wrapper, and calls would feed into uicontrol.


I could do this:



classdef uicontrolWrapper < handle
properties (Access = private)
uic
end
properties (Dependent)
Style
String
Value
...
end
methods
function set.Style(obj, val)
obj.uic.Style = val;
end
function val = get.Style(obj)
val = obj.uic.Style;
end
...
end


but hardcoding like this is obviously pretty ugly.


Or, I could do dynamically generate properties dependent on what I'm trying to wrap:



classdef uicontrolWrapper < dynamicprops
properties (Access = private)
uic
end
methods
function obj = uicontrolWrapper(hObj)
obj.uic = hObj;
cellfun(@(prop) obj.createProperty(prop, fields(get(hObj));
end
function createProperty(obj, prop)
p = addprop(obj, prop);
p.Dependent = true;
p.SetMethod = @setUicontrolProp;
p.GetMethod = @getUicontrolProp;

function setUicontrolProp(obj, val)
obj.uic.(prop) = value;
end
function val = getUicontrolProp(obj)
val = obj.uic.(prop);
end
end
end
end


The whole point is to avoid violating the Law of Demeter by not "reaching into" the property we're trying to adjust.


I don't know if this is a design pattern, but I've used this type of thing to wrap objects of different types when subclassing is for some reason or another inappropriate. (For instance, the matlab.ui.control.UIControl class is Sealed and cannot be subclassed.) Does this have an actual name and intended typical use?


where factory pattern shuould be in nodejs project structure

How abstract factory pattern should be inside node.js project structure? i have tried to make an idea following the links:



but have nothing concrete.


Thanks,


Segmentation fault when using a shared_ptr

I am making a particle system and I'm struggling with how to structure my code. The idea is that a user can create one or several ParticleEmitter objects that are passed to a ParticleManager object via the ofxCurlNoise object.


Now, I want that when the user updates the ParticleEmitters objects, the ParticleManager object sees the changes made. So I used shared pointers but I have segmentation faults at different times, whether I use one ParticleEmitter (segmentation fault when the program starts) or a vector<ParticleEmitter> (segmentation fault when the program exits).


What is wrong with this? Is there a design pattern for doing what I'm trying to do?


ofApp.h



#include "ofxCurlNoise.h"

class ofApp : public ofBaseApp{

// ParticleEmitter particleEmitter;
vector<ParticleEmitter> particleEmitters;
ofxCurlNoise curlNoise;

public:
void setup();

};


ofApp.cpp



#include "ofApp.h"

void ofApp::setup(){
// This produces a segfault as soon as the program starts
// particleEmitter.setup();
// curlNoise.setup(particleEmitter, 1024*256);

// This produces a segfault when the program exits
ParticleEmitter emitter;
emitter.setup();
particleEmitters.push_back(emitter);
curlNoise.setup(particleEmitters, 1024*256);

}


ofxCurlNoise.h



#include "ParticleManager.h"

class ofxCurlNoise {

ParticleManager particleManager;

public:
void setup(ParticleEmitter& emitter, int n);
void setup(vector<ParticleEmitter>& emitters, int n);

private:
void setup(int n);

};


ofxCurlNoise.cpp



#include "ofxCurlNoise.h"

void ofxCurlNoise::setup(ParticleEmitter& emitter, int n){
particleManager.addEmitter(shared_ptr<ParticleEmitter>(&emitter));
setup(n);
}

void ofxCurlNoise::setup(vector<ParticleEmitter>& emitters, int n){
for(auto& e : emitters){
particleManager.addEmitter(shared_ptr<ParticleEmitter>(&e));
}
setup(n);
}

void ofxCurlNoise::setup(int n){
particleManager.setup(n);
}


ParticleManager.h



#include "ParticleEmitter.h"

class ParticleManager{

vector<shared_ptr<ParticleEmitter>> emitters;

public:
void addEmitter(const shared_ptr<ParticleEmitter>& emitter);
void setup(int n);
};


ParticleManager.cpp



#include "ParticleManager.h"

void ParticleManager::setup(int n){
//...
}

void ParticleManager::addEmitter(const shared_ptr<ParticleEmitter>& emitter){
emitters.push_back(emitter);
}

What is the difference between Flyweight design pattern and Java cache

I read about Flyweight design pattern and got to know that it stores the objects that can be shared so as to save on heap usage. Java cache also saves the objects that can be reused later so as to save memory. Then what is the real difference between Flyweight design pattern and java cache ?


Adding new commands with Command Design Pattern

I'm having a dilemma regarding Command Design Pattern. Receiver is the interface for a class that knows how to perform operations.


In the example case given in the link, receiver class Stock Trade knows how to perform 2 operations, StockTrade#buy and StockTrade#sell. Those operations correspond to 2 existing commands, BuyStockOrder and SellStockOrder.


However, what if additional commands would need to be added, for example FooStockOrder and BarStockOrder? Then, the Receiver interface would have to be changed (and all existing implementations), therefore violating the Open-Closed principle.


How to tackle that problem in a way that Receiver is (almost) never changed?


dimanche 22 février 2015

Saving a Backbone model where i've created a collection inside

I have a model called 'Playlist' I got back from the server which has an array of objects called 'videos'. When i fetch the 'Playlist' data from the server I need to turn 'videos' into a Collection. I update the models in the 'videos' collection sometimes. Now when I go to save 'Playlist' model, will there be a problem because I've set the 'videos' attribute to a Collection? Will I need to turn it back into a raw array of items before saving it?


If anyone can give me any tips on the best pattern for this situation that would be good. Perhaps I should create a separate collection and leave the Playlist's 'video' attribute alone and when I go to save the Playlist model I can override the Playlist's video attribute with a raw copy of the Collection.


C# Pattern for aggregating interface methods into one generic method

I'm searching for a pattern to aggregating interface methods into one generic method.


Better to make an example of what I'm trying to do


Consider that I have an interface with 20 methods



interface MultiMethod{
public TypeA A (p1,p2);
public TypeA B (p1);
public TypeC C (p5,p3,p2);
.
.
.
}


Implementation Class



class MultiMethodeService : MultiMethod


In the MultiMethodeService I need to Implement all Interface methods, but the implementation of the methods is not real different.


Like:



public TypeA A (p1,p2){
proxy.call("remoteA").params(p1,p2);
}
public TypeB B (p1){
proxy.call("remoteB").params(p1);
}


I want to replace the implementation of the methods with one generic method that uses reflection.


The generic method derives



  • the parameters form the MultiMethod interface the method name from

  • the MultiMethode interface to invoke a proxy call


But how is it possible, when I have a generic method to also have the equal semantic like without a generic implementation. When I afterwords want to use the service object of MultiMethodService like :



var service = new MultiMethodService()
service.A(p1,p2)


Some naive idea was to implement an enum{"A","B"}



service.callGeneric(enum.A, p1,p2);
service.callGeneric(enum.B, p1);


which is not really nice.


If you could provide any pattern or idea, your help is highly appreciated.