lundi 31 août 2015

Parse data and share it in different modules

I wnat to use the following code from other so post and I wanted to know if its good practice to use it like following since I used a global field cacheObj I need to parse the data and share it between other modules,any module can take any property but only the first module which called to this parser is responsible to provide the data to parse(I need to do this parse just once and share properties in different modules)

var Parser = require('myParser'),
    _ = require('lodash');

var cacheObj; // <-- singleton, will hold value and will not be reinitialized on myParser function call

function myParser(data) {
    if (!(this instanceof myParser)) return new myParser(data);
    if (!_.isEmpty(cacheObj)) { 
        this.parsedData = cacheObj; 
    } else {
        this.parsedData = Parser.parse(data);
        cacheObj = this.parsedData; 
    }
}

myParser.prototype = {
    //remove `this.cacheObj`
    getPropOne: function () {
        return this.parsedData.propOne;
    },

    getPropTwo: function () {
        return this.parsedData.propTwo;
    }
};

module.exports = myParser;

Java, Maven: Models and Utils Circular Dependency

We have a project that has several war files that reference one-another. I've recently realized that there is a circular-dependency between two, in particular, the utils and the models. Other services use both of these, and the utils was created for operations that would be performed on the models by other services. I was just curious what is best-practice here. Utils and models sound like they are companions to the main project, but I've never heard of a war file being called 'utils and models'... just seems strange.

Additional Info (not necessarily needed to answer the question): To be more specific, the model uses the utils for it's type adapters, which allows MyBatis to convert timestamps to joda time. The utils uses the models, which I think is more acceptable, to do common operations on model objects.

Should I just combine both into the models war? What are some other options I would have. Sadly, it was my idea to create the utility war, but now I'm thinking that they should be one. Any ideas are appreciated.

Change persistence layer dynamically (upon runtime) with as few changes as possible

I am searching for a design pattern/way to exchange a (persistence) layer of my application dynamically (preferably even at runtime).

Why?

I'd like to be able to decide whether to save certain data to XML or a database on a "per instance"-basis. So I may decide that one project uses XML as a backend and another uses a database. I want to be flexible here and to be able to easily add another "driver" for e.g. Json or whatever.

Now assume the following setup:

We have a controller and we want to manage some data. We can choose between a SQL and XML implementation.

One possible (working) solution:

BasicController.scala

val myPersistenceLayer: PersistenceLayer = SQLPersistenceLayer

val apples: Seq[Apple] = myPersistenceLayer.getApples()

trait PersistenceLayer
{
    def getApples(): Seq[Apple]
    def getBananas(): Seq[Banana]
}

object SQLPersistenceLayer extends PersistenceLayer
{
    override def getApples(): Seq[Apple] = {...}
    override def getBananas(): Seq[Banana] = {...}
}

This is a rather nasty solution as one would have to add methods for each new Model (think fruit! ;)) not only in the trait, but also in every implementation. I like my single responsibility so I'd rather delegate that to the models instead, like:

trait PersistenceLayer
{
    def getAll(model: Model): Seq[Model] = { model.getAll() }
}

trait Model
{
    def getAll(): Seq[Model]
}

package "SQL"

class Apple extends Model
{
    def getAll(): Seq[Apple] = { // do some SQL magic here }
}

package "XML"

class Apple extends Model
{
    def getAll(): Seq[Apple] = { // do some XML magic here instead }
}

Now the big problem here is, even if I implement a concrete PersistenceLayer, like so:

object SQLPersistenceLayer extends PersistenceLayer {}

how could I tell the application to use the model of the right package?

If I use the SQLPersistenceLayer upon:

val apples = myPersistenceLayer.get(Apple) 

I would need to import the right "Apple" class, which defeats the whole purpose because then I could just remove all other classes, import the right one and just use a generic "getAll()" method on it.

So again I would need to change the implementation at multiple lines, which is what I want to avoid.

I thought about something like giving a string with the package-name, like

val package = "sql" and in the controller to import it from the right package, but this is not really feasible and not really easy to accomplish and it's a rather nasty hack for something I'm obviously missing.

To make a long story short: I want to be able to switch the package to use for my persistence needs dynamically. In some dynamically typed languages I could come up with a solution, but not in Scala or any statically typed language, so I guess I'm not knowing a certain design pattern here

Multiple Entity update in a single PUT method in Rest Service

order item table

order_item_id
order_id
quantity
unit_price
shipping_price
business_id
workflow_id
delivery_id
item_id

Orders table

billing_address_id
shipping_address_id
payment_mode
total_price
shipping_price
customer_id 
order_id

Logistics

   `id` 
  `tracking_id` 
  `partner_id`  
  `tracking_status` 
  `create_TS`  
  `update_TS`  
  `order_item_id` 

order status history

 `order_item_id` 
  `workflow_id`  
  `partner_status` 
  `create_TS`  
  `update_TS` 

There are 3 types of users in my system. Admin, Merchant and Customer. Each one of them can update the status of an item in a order. Each status update triggers updates to multiple tables and different logic.

Eg: Order life cycle is as follows pending -> approved -> cancel/shipped -> Delivered -> returned/exchanged

When the admin approves an order( after stock verification as our inventory is not yet real time) I will have to update the above 4 tables.

In some scenarios , I don't have to update one or two tables. eg, If the customer cancels the order before the admin can approve, then nothing to update in the logistics table.

In some scenarios, eg: if the admin approves one item in the order and cancels the other item, then the update logic varies.

Currently I have a method called updateOrder for all the three roles in their corresponding implementation classes.

But the logic makes me to put a lot of if..else conditions and loops. Is there a design pattern I can follow?

Or how in general are the PUT methods handled involving update to multiple tables

Java String - parsing out Strings containing Alpha Characters

In my Code I am trying to seperate out two different types of Strings, IP addresses and DNS addresses. I am having trouble figuring out how to split it. My initial thought is:

String stringIP = "123.345.12.1234";
String stringDNS = "iam.adns234.address.com";

if(!Pattern.matches("^[a-zA-Z0-9.]*$",stringDNS)){
  //I only want to get IP type strings here, so I am trying to separate out anything containing alpha characters. stringDNS should not be allowed into the if statement.
}

Any suggestions would be appreciated!

How to implement catalog / registry while obeying immutability and "rules" of functional programming?

Folks,

what is the most appropriate way to implement a registry like

trait Registry {
  def registerComponent( name: String, obj : Any ) : Unit
  def getComponent( name: String ) : Any
  def unregisterComponent( name: String ) : Unit
}

following functional patterns. ( E.g. immutability, etc. )

What comes to my mind here is

  • State-Monad: where the state of the monad represents the registered objects (as Seq or similar)
  • Builder-(like)-Pattern but with copying the current registry context from one builder step to the next.

E.g.: A registry following builder-like pattern:

case class Registry(registered: Map[String, Any]) {
  def register( name: String, obj: Any ) : Registry = {
    copy( registered = this.registered + ( name -> obj) )
  }
  def unregister( name : String ) : Registry = {
    copy (registered = this.registered.filterKeys( !_.equals(name)))
  }
  // How to deal with return values????
  // Tuple return is quite ugly
  // 
  def getComponent( name: String ) : (Registry, Option[Any]) = {
    (this, registered.get( name ) )
  }
}

Which other solutions / patterns are reasonable or available?

Cheers,

Martin

Implement web Service in my Architecture

I'm really really new programing with an architecture, so I hope someone here can help me.

I have a solution on C# .Net with the next architecture:

  • Data: Contains the UoW, Repositories, Entity Framework mapping and context.
  • Design: It'll contain the WPF and Web projects.
  • Domain: Contains entities that all the other projects will be using.
  • Service: HERE IS MI PROBLEM!! I have no idea what to do here.

I need to implement a web service that will be consumed by WPF and WEB projects but I don´t know if it really goes here and how it needs to be (Web API or WCF).

dimanche 30 août 2015

Can DAO use an object that itself incapsulates a dataSource object?

I have a DAO, (call it PlayerDao) having the following method:

public interface PlayerDao{
    //Other methods
    public Collection<Integer> getPlayerRegisteredIds();
}

Now I need to provide two implementation for that method:

I. Executing a select query on a dataSource directly like the following:

public class PlayerDaoImpl implements PlayerDao{

    private DataSource dataSource; //javax.sql.DataSource
    //Other methods
    public Collection<Integer> getPlayerRegisteredIds(){
        Collection<Integer> result = new ArrayList<Integer>();
        String query = "SELECT id FROM player WHERE registered_today = true";
        //Executing the query with the dataSource

        return result;
}

II. Execute this query by parts. I mean split the query into 4 disjoint parts and execute each part into a separate thread (For improving performance).

 public class ConcurrentPlayerDaoImpl implements PlayerDao{
    private static final NUMBER_OF_THREADS = 4;
    private DataSource dataSource; //javax.sql.DataSource
    //Other methods
    public Collection<Integer> getPlayerRegisteredIds(){
        final Set<Integer> set = Collections.synchronizedSet(new HashSet<Integer>());
        //It's going to consist of 4 queries 
        List<String> queriesToConcurrentExecution = new ArrayList<String>();     
        ExecutorService executor = Executors.newFixedThreadPool(NUMBER_OF_THREADS);
        for(final String sql : queriesToConcurrentExecution){
            executor.execute(new Runnable() {
                @SuppressWarnings("unchecked")
                @Override
                public void run() {
                    List<Integer> l = new JdbcTemplate(dataSource).queryForList(sql, Integer.class);
                    set.addAll(l);
                }
            });
        }
        executor.shutdown();

        return set;
}

The thing is that implementation of //Other methods is the same in both cases. So I tend to wrap the getPlayerRegisteredIds() into some interface and then provide two different implementation of it for the same Dao class thorugh its constructor. Is that correct?

In the official DAO-pattern's description said that the DAO acts like an adapter between a bussines object and DataSource, but in my case it uses an object that itself uses dataSource.

QUESTION: Should we always adhere to using the dataSource object directly in DAO? Is that the necessary requirement?

Ruby on rails 4 - Best architectural solution for the following?

Ce résumé n'est pas disponible. Veuillez cliquer ici pour afficher l'article.

Minimalist framework

I've read somewhere the Inversion of Control (IoC) is (kind of) a principle of a framework.

Is it correct to (taking advantage of that) say I designed a framework for X just because the IoC pattern is employed?

May I ask for a minimal framework example (C++ code please)?

Design issues and ideas

I have problems with dealing with derived classes that inherit from the same base class.

Supose i have 2 types of songs:

  • songs with lyrics that have: Title, Tags (sad,happy etc), lyrics (one line), writer
  • instrumental song: Title, Tags (same as lyric songs), instrumentals (a string), performer, BPM.

I thought it would be a good idea to implement a base class Song , since Title and Tags are fields that are common to the both types of the songs. Then, implement the class LyricSong and ImplementSong that inherit from Song

The code i wrote:

class Song
{

public:
    Song(std::string title, std::string tags);

    std::string getTitle() const { return this->_title; }
    std::string getTags() const { return this->_tags; }

    // Since i had the need in virtual functions and since all virtual functions have to be 
    // implemented, i used default string and int to be returned.
    virtual std::string getLyrics() const { return std::string(); }
    virtual std::string getLyricsBy() const { return std::string(); }
    virtual std::string getInstruments() const { return std::string(); }
    virtual std::string getPerformer() const { return std::string(); }
    virtual int getBPM() const { return 0; }

    static songContainer readSongsFromFile(std::string songsFileName);

private:
    std::string _title;
    std::string _tags;

};

//---------------------------------------------------------------------------//

class LyricSong : public Song
{

public:
    LyricSong(std::string title, std::string tags, std::string lyrics, std::string lyricsBy);

    std::string getLyrics() const { return this->_lyrics; }
    std::string getLyricsBy() const { return this->_lyricsBy; } 

private:
    std::string _lyrics;
    std::string _lyricsBy;
};

//---------------------------------------------------------------------------//    
class InstrumentalSong : public Song
{

public:
    InstrumentalSong(std::string title, std::string tags,\
                     std::string instruments, std::string performer, int BPM);

    std::string getInstruments() const { return this->_instruments; }
    std::string getPerformer() const { return this->_performer; }
    int getBPM() const { return this->_BPM; }


private:
    std::string _instruments;
    std::string _performer;
    int _BPM;
};

Issues have arised:

  • The code is cumbersome and messy.
  • Every time i'll need to add new song types , it'll force me to modify Song (add more functions and make them virtual - Polymorphic issues).
  • Will there be a way to know what type of Song i work with, in case of iterating over an array of Song pointer that point to various song types?

Are there any common design principles that can help me with this ?

Throw exceptions with self-defined constants: best practice

I want to throw exceptions with self-defined constants so that I will be able to decide if to quit the program/retry/log the error and so on. Is there some best practice guide? Do I have to mind other library codes (they simply might have the same code number). Consider this:

<?php
class Foo {
    const FATALERROR = 1;
    const NOTFATAL = 2;

    function bar() {
        try {
            // some code
            throw Exception("This is a fatal error.", self::FATALERROR);
        } catch(Exception $e) {
            if ($e->getCode() === self::FATALERROR)
                die($e->getMessage());
            else
                // do some other stuff here
        }
    }
}
?>

Most efficient singleton pattern?

I am reading about singletons, and don't understand why this

public class BillPughSingleton {
    private BillPughSingleton(){}

    private static class SingletonHelper{
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance(){
        return SingletonHelper.INSTANCE;
    }
}

is more efficient than this

public static ThreadSafeSingleton getInstanceUsingDoubleLocking(){
    if(instance == null){
        synchronized (ThreadSafeSingleton.class) {
            if(instance == null){
                instance = new ThreadSafeSingleton();
            }
        }
    }
    return instance;
}

How to get data from different modules

im having node JS application and I build some module which is responsible to parse data and provide access to its property,Now I need to access to this parser from different module but I want that If I access in the first time and I sent the data ,in second time and after don't parse the data again since it already parsed...I try to save the object in some cache which doesn't work(when I access from different(for example in second time) module the cacheObj is empty,what am I doing wrong here?

"use strict";
var Parser = require('myParser'),
    _ = require('lodash');

function myParser(data) {
    if (!(this instanceof myParser)) return new myParser(data);
    if (!_.isEmpty(this.cacheObj)) {
        this.parsedData = this.cacheObj;
    } else {
        this.parsedData = Parser.parse(data);
        this.cacheObj = this.parsedData;
    }
}

myParser.prototype = {
    cacheObj: {},
    getPropOne: function () {
        return this.parsedData.propOne;
    },

    getPropTwo: function () {
        return this.parsedData.propTwo;
    }
};

module.exports = myParser; 

In short Lets say that I need to parse the data and I want to share this parsed properties in different modules.the first module which call to this is responsible to pass the data and other modules doesn't need to send the data since I already store the parsedData.

samedi 29 août 2015

Find if long string of chars contains any patterns

So I have a long string of chars for example - "wdllwdwwwlldd" The string just contains the same chars -wld (try and guess what I'm doing ;))

The string will be quite long, approx 420 chars long.

I want to find, if they exist, any patterns in the string. For example if the string was - "wllddwllddwlldd" then it "wlldd" would be the pattern that was found.

So i kind of want to find Any repeated sequences in the string.

Having done a bit of research, suffix trees and suffix arrays seem to get mentioned a lot on these problems.

Is thst correct or is there another way to do this?

I can tell that this is quite a large task and could potentially take a long time.

Thanks in advance.

Java Rest API for order management for a ecommerce platform

order item table

order_id
order_item_id
quantity
unit_price
shipping_price
business_id
workflow_id
delivery_id
item_id

Orders table

order_id
billing_address_id
shipping_address_id
payment_mode
total_price
shipping_price
customer_id 
business_id

If the order contains multiple items from multiple seller, I have to group items by seller and create one order each for each seller.

eg:

item 1 => Seller 1

item 2 => Seller 1

item 3 => seller 2

item 4 => seller 3

I should now create three orders

order1 => Seller 1 => item 1 and item 2

order2 => Seller 2 => item 3

order3 => Seller 3 => item 4

The client sends a single request in the following format

Order details (such as payment mode, total cart value etc...)

List of items in the order (this list consists of items from all 3 sellers)

Order Processing system is a java rest API.

I do the following to create an order.

  1. Segregate items based on seller.
  2. In transaction mode , create 3 orders in batch mode(using jdbc) This query returns the order ids that were just created using PreparedStatement.RETURN_GENERATED_KEYS
  3. Query the table again to find which order id is mapped to which business id.
  4. Finally inserting into the order items table (after mapping the item to the order id got from step 3) and update as a batch.

This process is pretty complex. And I am wondering if there is a better way to handle this scenario.

Is there a way to use Hydrators with CakePHP?

Is there a way to use Hydrators with CakePHP?

I mean, create strategy classes, bind each strategy to class properties and hydrate classes with strategies.

The Model-to-View communication in MVC?

I'm learning MVC now and I just got that when the model is modified by the controller, it can notify the view to update the data from model. While I'm quite confused about it. Since the model is modified by the controller rather than itself or something else, it should be the controller that sends the update notification to the view. Also I haven't found any example of such Model-to-View communication, please give me one to make it clear if anyone understands this idea well.

Promises as way of controlling state

I would like your comments on the use of promises in a part of my code.

I have a View, lets call it Foo. Foo implements Interface EmbeddableView. I have Foo embedded in view Bar. Foo is unaware that it is embedded anywhere and Bar does not care about the content of Foo, only if it's valid or not. The way this happends is the interface EmbeddableView has a function like getValidationPromise returning a promise.

When view Foo resolves the promise, bar is notified that its content either rendered invalid or valid.

However, that validation state change is not a one time thing. It will jump back and forth. It is no longer a promise on the completion of an operation. It can fail, re-fail, success and maybe fail again. Would you say promises is still a meaningful way of implementing this?

Any comments about how this could be implemented in typescript/javascript in a meaningful way is appreciated.

MVVM Design Hickups and grey area

I have for the last few month been trying to familiate myself with the mvvm pattern in wpf. This is a topic that is widely discussed and i have come across articels which in places contradict one another. I know mvvm is a pattern and not a universal truth however do in certain case find thesse grey area of deciding what goes where, and what does what. 99% of the time it is between the viewmodel and view these problem arises.

my current mindset for deciding what belongs where:

Model: it only contains data which is to be saved to a file. Nothing More, nothing less.

ViewModel: is a communication bridge between a view and one or more models associated with that view.

View: handles visual representation, visual popups and visual modifications

first of af simple question concerning the Model: (Case 1)

In every implementation i have seen so far the model object is class implementing the INotifpropertyChanged. Why should the model be a class and not just simply an interface describing what the data should be and let the viewmodel implement this interface? The model should not deal with the ui even if it is decoupled and therfore giving a model class the INotifyPropertyChanged is just as wrong as making the viewmodel inherit from a DependencyObject (even though i understand its importance in that type of model implementation)?

Grey area example of what the ViewModel should handle vs the View: (Case 2)

Say i am creating a Uml editor where there are Nodes and Connectors Created in a viewModel and kept in thier own ObservableCollection.

<SomePageView.DataContext>
    <vm:SomePageViewModel/>
</SomePageView.DataContext>
<Grid>
    <ItemsControl ItemsSource="{Binding Nodes}" DataTemplate="{Binding SomeNodeUserControl}"/>
    <ItemsControl ItemsSource="{Binding Connectors}" DataTemplate="{Binding SomeConnectorUserControl}"/>
</Grid>

When a node is dragged around the grid any attached Connector endpoints will follow the node around as it is moved. I personally see this as Comunication between the UiElements, but there are 2 fundamentally different ways of implementing this type of behavior. Update the Connector by keeping a complete reference to the NodeviwModel and use its position members to update the position of the Connector. It is a pretty simple approach however do not like it as i believe it should be the ConnectorView that update the postion of The ConnectorVm. this requires that the Connector View know something about a specific NodeView. However this approach more complicated and i havent found a valid solution for it yet ( currently looking into the EventAgregator pattern). The Reason why i like the last aproach is that if select a connector it should be the view that dictates how the connector can be moved around and not the ViewModel. Any comments or advice on my observations?

in the mvvm pattern were should ui patterns be kept: (Case 3)

in mvvm where should the eventAgregator, Mediator be used. in the ViewModel or the CodeBehind? My current belief is they belong in the code behind, but i have a shred of uncertainty regarding this matter. If kept in the codeBehind i csn imagine a cleaner aproach by using the The VisualTree with the loadedevent instead of using constructors taking arguments of Eventagregator and likewise. Similar i can implement an UndoRedoController which would not require to be a singleton. should be easier to test, possible to have more UndoRedoControllers existing. An example could be a document program that allow mutiple documents to opened at once in tabs and therfore should have thier own UndoController.

Clean Architecture - How to go from "Database Driven" to "Independent of Database"

I am looking for some clarity and hopefully some advice on writing clean architecture for a large system. My Companies "Web Solution" is +-10 years old, my job is to rewrite it. It is written across a few thousand asp classic pages all with their own sql queries with absolutely zero consistency (I spend the vast amount of my maintenance/debugging time fixing these since products may appear in one search and not another etc.). To put it bluntly its tangled knot of code straight out of my worst nightmares to deal with.

Up until yesterday I had a pretty straight forward plan for the re-development and to solve my inconsistency issues...

  1. Choose a user case.
  2. Write one or two stored procs/sql functions to control the dataflow for the selected case i.e. save user, add user, edit user etc.
  3. Update the relevant asp pages on the current system to use the above procs/functions.

End goal - end up with an entirely database driven application, while achieving much needed stability & integrity during development. Once this is achieved I was planning to write a web API (using the same database procedures) and then implement a web UI,Mobile App and anything else needed on top of this API. While daunting this seemed like a pretty decent solution to me, even with its flaws it’s exponentially better than what we currently have to work with.

Then I came across Uncle Bobs Guide to Clean Architecture.

I understand the concept and it seems awesome, all most too good to be true from my current position but the deeper I delved into it the trickier it became in terms of "This is great! Now how would I implement it?” One of the rules the guide calls for is that the application be completely database independent. Meaning what I had planned would never make the cut. I had to admit the cold hard fact that this is a completely foreign concept to me, right from the first day I started learning to program the heart and soul of the application was the DB so it’s very hard for me to adjust my thought process and not treat it as such.

I have done some further reading and was hoping for some feedback to whether or not I’m on the right track, or if there is a cleaner cut, cleaner approach.

PHP is my primary go to language for most web applications so this is the language my theory would most likely be implemented in...

  1. Break the system down to its core use cases and entities. Write Independent objects for each of these.
  2. Write a data interface model, which abstracts from the database (since the database currently is primary source for use cases and entity logic the above objects would likely based of their current table). This would allow me to keep anything DB related in one location and provide the same result of integrity and consistency that implementing stored procs/sql functions would, although this would still not make the application "database independent" since I would have to modify the abstraction layer if I changed providers i.e. from SQL Server to Oracle. This is where my uncertainty comes in, is this a good approach? It’s highly unlikely I would change data sources but who knows? Also If I am going to follow the guide’s architecture I want to do it as closely as possible and I know that if this step is not implemented correctly it would defeat the purpose since the database layer would slowly start seeping back into the primary application model.
  3. Implement a web API using the core objects written in step 1.
  4. Implement API driven UI's for whatever platforms necessary.

I apologise for the essay but I wanted to be as clear as possible in the hopes that this will help get me the best guidance. I would really love to learn and one day be highly proficient in this type of architecture and while there is a ton of online information about its structure and concept there is extremely little on how to implement it, or more on how to change your mind set when developing an application when you are used to the database being the absolute core of the application.

Any kind of feedback will be highly valued and appreciated. Thanks

vendredi 28 août 2015

Pattern to seprate DAO layer from Service layer

I am working on a project where we are currently using hibernate. I want to find a way to code the project so as we can easily remove the hibernate and replace it with something else (e.g. jdbc) in future.

I found bits and pieces about a using a mapper but did not completely grasp the foundation . Does anyone know of a good example implementing a design pattern(to show my boss) that does something like this currently.

We are currently coding in java so a java example would be amazing.

Why is the factory method declared as protected?

I'm reading the Head First Design Patterns book and on the "Declaring a factory method" section in Chapter 4, the method is declared as protected:

public abstract class PizzaStore {

    public Pizza orderPizza(String type) {
        Pizza pizza;
        pizza = createPizza(type);
        pizza.prepare(); // other methods follow

        return pizza;
    }

    protected abstract class Pizza createPizza(String type);

}

This confuses me because I initially thought, in fact it is also stated in the book, that having a factory (method) allows you to have a single place that creates an instance for you, not just for acting on later but also for "querying". By "acting on" I mean pizza.cut() etc, and by "querying" I mean pizza.isSpicy().

Wouldn't the protected keyword limit the querying to only the subclasses and same-package classes? What if a 3rd-party class needed to know that the pizza is spicy before ordering?

I may be overthinking this, because the highlight box does not say it HAS to be protected but it's there in the sample code.

Using a map to fill a case class

Generic problem: I have a JSON-representation of a datastructure (which will be represented as a Map[String, Any] from now on) and a (case) class with some (!) of the key-value pairs as fields, but not all of them. I want to fill them in, with default values where the map has no pair (e.g. with constructor based default values for simplicity).

This would allow something like:

case clase User(id : Int, name : String, vegan : Boolean = false)
val map = Map("id" -> 42, "name" -> "tom")
val user = map.as[User] //User {42, "tom", false}

Coding it manually would be easy, but takes time and makes the code larger/harder to maintain/inspect (especially for >20 fields per class).

I feel like this needs to be possible by reflection, and more specifically at compile-time, without any performance detriment or problem with bytecode representation.

I know there are many questions (and answers) related to mapping maps to and from case classes, but most use deprecated apis, and the state of the art probably has progressed as well.

struggling with asynchronous patterns using NSURLSession

I'm using Xcode 7 and Swift 2 but my question isn't necessarily code specific, I'll gladly take help of any variety.

In my app I have a list of favorites. Due to API TOS I can't store any data, so I just keep a stub I can use to lookup when the user opens the app. I also have to look up each favorite one by one as there is no batch method. Right now I have something like this:

 self.api.loadFavorite(id, completion: { (event, errorMessage) -> Void in
     if errorMessage == "" {
         if let rc = self.refreshControl {
             dispatch_async(dispatch_get_main_queue()) { () -> Void in
                 rc.endRefreshing()
             }
         }
         dispatch_async(dispatch_get_main_queue()) { () -> Void in
         self.viewData.append(event)
             self.viewData.sortInPlace({ $0.eventDate.compare($1.eventDate) == NSComparisonResult.OrderedDescending })
             self.tableView.reloadData()
         }
     } else {
         // some more error handling here

     }
 })

in api.loadFavorite I'm making a typical urlSession.dataTaskWithURL which is itself asynchronous.

You can see what happens here is that the results are loaded in one by one and after each one the view refreshes. This does work but its not optimal, for long lists you get a noticeable "flickering" as the view sorts and refreshes.

I want to be able to get all the results then just refresh once. I tried putting a dispatch group around the api.loadFavorites but the async calls in dataTaskWith URL don't seem to be bound by that group. I also tried putting the dispatch group around just the dataTaskWithURL but didn't have any better luck. The dispatch_group_notify always fires before all the data tasks are done.

Am I going at this all wrong? (probably) I considered switching to synchronous calls in the background thread since the api only allows one connection per client anyway but that just feels like the wrong approach.

I'd love to know how to get async calls that make other async calls grouped up so that I can get a single notification to update my UI.

For the record I've read about every dispatch group thread I could find here and I haven't been able to make any of them work. Most examples on the web are very simple, a series of print's in a dispatch group with a sleep to prove the case.

Thanks in advance.

prevent an explosion of classes

I am working on a project where I have to monitor the status of an elevator. So far, my design looks like this : Class diagram

We are using a third party library to read and monitor realtime values from the elevator's logic controller. A tag is an integer value in a memory register of the logic controller. For example, DM140 contains the elevator direction.

I use an adapters layer in order to keep my application domain isolated from the third party library.

In the domain, the ElevatorDirectionMonitor takes the ElevatorTag integer value and extrapolate the elevator's current direction and then notify its clients that the elevator's direction has changed. So far, so good.

Here's my problem. There will be a lot (a hundred or more) of informations to monitor from the elevator, like the current floor, the doors are opened/closed, etc. If I continue this way, I will have to do one monitor class for each information I want to monitor (i.e. an ElevatorFrontDoorStatusMonitor, ElevatorRearDoorStatusMonitor) and each of them associated with its own Observer interface. This means a lot of work. I've been trying to find another way to structure my application, but didn't found anything more "elegant".

The basic logic in each monitor class would be pretty much the same in all of them : listening for value change on an ElevatorTag instance, extrapolate the information from the new tag value and then notify the observers. The problem seems to come from the fact that each observer must have a different interface signature.

Does someone could suggest me patterns I should use or anything that could help me to simplify my design.

Thanks!

Avoid dependencies between modules

For the sake of the question let's say I have a cryptographic module opensslCryptographicModule that have the following methods:

public String encrypt(String content, String key);
public String decrypt(String encrypted, String key);

And an other module, let's call it MainModule that needs a cryptographic module to work.

Since the cryptographic module used in MainModule may change I created an interface as follow:

public interface CryptographicModule {
    public String encrypt(String content, String key);
    public String decrypt(String encrypted, String key);
}

And the MainModule takes a CryptographicModule in its constructor.

My question is how do I keep the cryptographic module totally independant ?

If I put the interface in the MainModule then the opensslCryptographicModule will need to implements an interface declared in an other project and therefore will become dependant of that project.

But if I put the interface in the opensslCryptographicModule then the other cryptographic modules will need opensslCryptographicModule to get the interface.


The only solution that I can see is a third module that will make the link between both of the modules.

It will implements the interface (that will be in the MainModule) using the adapter pattern to provides the functionalities of the cryptographic module:

public class OpenSSLCryptographicModuleAdapter implements CryptographicModule  {

    private OpensslCryptographicModule module;    

    public OpenSSLCryptographicModuleAdapter(OpensslCryptographicModule module) {
        this.module = module 
    }

    @Override
    public String encrypt(String content, String key) {
        //...
    }

    @Override
    public String decrypt(String encrypted, String key) {
        //...
    }
}

And the MainModule will rely on this third module to work.

But I find it a bit overkill especially when we have control of all the modules. This design pattern is great when using a third party library or if we want to works with some old code, but not when the whole project is been written.

Adding encryption layer in existing application architechture

I have asked to add data encryption and decryption for existing data in database.

right now i am using .dbml file for data access.

My problem is that where i will implement encryption layer so that i dont need to change much part of app as my application has many ways to read and write data.

I want to minimize the effort and make it centrally the things.

Any help and idea would be appreciated.

Using singleton pattern with Entity Framework context - The underlying provider failed on open

I'm trying to add a singleton pattern to my DbContext with Entity Framework. I've always used the singleton pattern for this, and never experienced this error before. I know that singleton is best practice, but if any of you have the time to spare, could you please explain why singleton is best practice?

Problem

Other than that, I get this error:

The underlying provider failed on open

Let's have a look on my code

DAO.cs

public class DAO
{
    private static HourRegistrationEntities hourRegInstance;

    public static HourRegistrationEntities HourRegInstance { get { return hourRegInstance = hourRegInstance ?? new HourRegistrationEntities(); } }
}

Service.cs (example method)

/// <summary>
/// Return a list of all denied Hour Registration for the Login with the given stringId
/// </summary>
/// <param name="stringId"></param>
/// <returns>A list of HourRegistrationDTO</returns>
public List<HourRegistrationDTO> GetAllDeniedHoursForLogin(string stringId)
{
    var id = Int32.Parse(stringId);
    using (var db = new HourRegistrationEntities())
    {
        var dbHours = db.HourRegistration.Where(x => x.LoginProject.Login.ID == id && x.Denied == true).ToList();
        var returnList = new List<HourRegistrationDTO>();
        foreach (var item in dbHours)
        {
            returnList.Add(new HourRegistrationDTO()
            {
                Id = item.ID,
                Hours = item.Hours,
                Date = item.Date.ToShortDateString(),
                Comment = item.Comment,
                CommentDeny = item.CommentDeny,
                LoginProject = new LoginProjectDTO()
                {
                    Project = new ProjectDTO()
                    {
                        Title = item.LoginProject.Project.Title
                    }
                }
            });
        }
         return returnList;
    }            
}

As mentioned, I've ALWAYS used the singleton pattern but NEVER had this error before. What's causing this, as why?

jeudi 27 août 2015

Ruby - Method Factory

I have being reading about Factory Method Pattern and I still having trouble to understand how to use in practical cases even after reading examples and questions about it.

For example suppose a case where there is two ways to getting data into my class i.e the user input can be either:

Name Surname

Surname, Name

This is something that I would solve more or less like this:

class Name
  attr_accessor :name
  attr_accessor :surname
  def initialize(rawname)
    if(rawname.include? ',')
      @name = rawname.split(', ').last
      @surname = rawname.split(', ').first
    else
      @name = rawname.split(' ').first
      @surname = rawname.split(' ').last
    end
  end
  def print
    puts "#{@name} #{@surname}"
  end
end

How should I implement Factory method on this example? Or in general, how should my though process be in order to use such design patterns?

Design pattern validation in subclass or superclass

I have following structure.

DynamoDBDao{

public get(String hashKey,String rangeKey){
 //validation rule
}

}

T1DynamoDBDao extends DynamoDBDao{
public get(String name,String surname){
 // same validation rule
 super.get(name,surname);
}
}

Does it make sense to duplicate validation rule in T1DynamoDBDao?

Why is this always evaluating to false?

I have a piece of code I made

abstract class WorkTypes
{
    const Portfolio = 0;
    const Study = 1;
}

function get_our_work ( $atts )
{

   // see http://ift.tt/1u7MYRt

    $work_type = (strcmp($atts['workType'],'ports') === 0) ?  WorkTypes::Portfolio : WorkTypes::Study;

    include "page-content/our_work.php";
}

and for reason $work_type is always evaluating to be WorkTypes::Study even when I'm 100% sure that $atts['workType'] is equal to 'ports'. So I know that (strcmp($atts['workType'],'ports') === 0) is always evaluating to false. Why?

New Project - Architeture questions

I am building an web application in C# using MVC for the presentation.

In this project I will need to connect to two different databases and integrate their data. I am wondering how I can do it using unit of work pattern.

As well I would like to know a good way to architeture my code. Should I separate into layers? Which layer should I have?

Could someone help me please? Thanks!

Is there a design pattern to handle when code depends on the subtype of two objects

I'll try to be as explicit as possible, in case there is a better solution for my problem than answering my question.

I'm working in C#.

I have a report template that can include any number of 'features' turned on. A feature might be a table of information, a pie/bar chart, a list, etc. I am generating the report as a text file, or a PDF (possibly other options in the future).

So far I have an IFeature interface, and some feature types implementing it: ChartFeature, ListFeature, etc. I read the list of features enabled from the database and pass each one to a method along with the data id and the method returns a populated IFeature of the proper type.

I also have an IReportWriter interface that TextReportWriter and PdfReportWriter implement. That interface has a method: AddFeature(IFeature).

The problem is that AddFeature in each writer ends up looking like:

public void AddFeature(IFeature)
{
    if(IFeature is ChartFeature)
    {
        ...
    }
    else if(IFeature is ListFeature)
    {
        ...
    }
    ...
    else
    {
        throw new NotImplementedException();
    }
}

This feels ugly. I like it somewhat better as AddFeature(ListFeature){...}, AddFeature(ChartFeature) because at least then it's compile time checked, but in practice it just moves the problem so now outside if the IReportWriter I'm calling if(feature is ...).

Moving the display code into the feature just reverses the problem because it would need to know whether it should be writing plain text or a PDF.

Any suggestions, or am I best just using what I have and ignoring my feelings?

What are Design Patterns are used on iOS? [on hold]

What Design Patterns are used on iOS other than MVC . i m just new to in ios development and so i want to know the various design pattern in ios and how to use.

Which one is commonly adopted by developers and easy to understand ?

Structure to run x first vs y first on 2d array

I want to have a flag passed to a function that runs an algorithm by either col-scanning or row-scanning:

if run-on-x
  for 1..x
    for 1..y
      do something with ary[x][y]

else
  for 1..y
    for 1..x
      do something with ary[x][y]

But I don't want to duplicate all the loops and logic.

I've come up with this:

let numPx = width * height;
for (let px = 0; px < numPx; px++) {
  let [x, y] = yAxis ? [px % width, 0 | px / width] : [0 | px / height, px % height];

But I think all the math is rather heavy, especially when I'm running it on fairly large arrays.

Is there a better way to do this?

A Pattern Naming Curiosity: Why ActiveRecord and not ActionRecord?

I am really curious about this naming convention: ActiveRecord, not ActionRecord ActionMailer, not ActiveMailer ActionController, not ActiveController

Basically, what I am asking is if there is a difference between using Active and Action?

How to best publish files to multiple sftp targets

I have the following sftp bean Id configured in my spring application-context file. It defines two sftp targets which my application is to send different types of files to:

<bean id="targetA" 

class="com.sftp.Sender">
        <constructor-arg value="${A.host}"/>
        <constructor-arg value="${A.username}"/>
        <constructor-arg value="${A.remoteDir}"/>
        <constructor-arg value="${A.notificationDir}"/>
    </bean>

    <bean id="targetB" class="com.sftp.Sender">
        <constructor-arg value="${B.host}"/>
        <constructor-arg value="${B.username}"/>
        <constructor-arg value="${B.remoteDir}"/>
    </bean>

My main class looks something like this:

public class Main {

    Occ occ= ctx.getBean("occ", Occ.class);

    public static void main(String[] args) {
            if (args != null && args.length >= 1) {
                String target = args[0];
                occ.rePublish(target);

            } else {
                    String target = "Both";
                   orc.processReports(target);

                } 
}

My Occ class something like this:

public class Occ {

                 public void rePublish(String target) {
                     processReports(target);
                }

                public void processReports(String target) {
                    // determines who the target is and prepare the appropriate 
                    // file to send to that target

                    if (target.equal("Both")) {
                        // prepare both target A and B files 
                    }
                }

            }

Generally, when the program is executed, it should prepare both sets of files for both target A and target B. In certain scenarios, one transfer may fail and I want to be able to prepare and distribute files for just that target. I can only think of passing in the resend target as arguments in main method. But is this the best way to do this? What are your thoughts and how would you do it? Can I restructure the above code in other better ways?

Multiple JPanel or JFrame with MVC

I have read a number of articles/explanations on implementing MVC (Model View Controller) design pattern with Java such as:

http://ift.tt/1LCIID0

GUI not working after rewriting to MVC

and have visited several few more (including those in SO).

I am clear on what was explained in those links. However how should we implement a MVC when we have several JPanels/JFrames? So let say I want to implement a program which may display several JFrames at the same time.

Question: Should we try to only have 3 classes (Model, View, Controller) despite having multiple JFrames or should we have a separate View class for each JFrame?

I am aware that we could use the observer pattern to let various Frames communicate.


As for this link from SO, there is only 1 solution which does not address my question above: Java MVC multiple JFrame

I am also aware of The Use of Multiple JFrames, Good/Bad Practice?. But let's assume I will be having multiple JFrames which may display at the same time. I am more concern how would it be implemented with MVC.

Dependency Injection in ViewModelBase - Best practice

I am using a LoggerService in my ViewModelBase, which is injected in constructor:

public abstract class ViewModelBase : INotifyPropertyChanged
{
    private ILoggerService _loggerService;

    public ViewModelBase(ILoggerService loggerService)
    {
       _loggerService = loggerService;
    }

    ...
    ...

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

But in my ViewModelOne, which inherits from ViewModelBase, I need to use this service, what should I do?

  • To do public the _loggerService in ViewModelBase and use it from ViewModelOne.
  • To inject again the interface in the constructor of ViewModelOne.

In your opinion, which would be the best approach? Or...what would you do?

pattern for saving newline-delimited json with python

With Python, I'm saving json documents onto separate lines like this:

from bson import json_util # pymongo

with open('test.json', 'ab') as f:
    for document in documents:
       f.write(json_util.dumps(document)+'\n')

and then reading like this:

with open('test.json') as f:
    for line in f:
        document = json_util.loads(line)

The ease and simplicity make me think that there must be a gotcha? Is this all there is to linejson, aka jsonlines?

mercredi 26 août 2015

Why is it good practice to use String.empty? [duplicate]

From what I've seen on several Stack Overflow posts, something like

if (str == "") 

should instead be

if (str == String.empty)

which is of course more descriptive and, I guess, maintanable. But what is the chance that the definition of an empty string is going to change at some point in the future? Some day in the future, is an empty string going to be defined as something other than a string with zero characters in it, so that we can all recompile our code and it'll work with our society in which an empty string is not the same as "" ????

pattern for saving many small json files to filesystem

tl;dr: Is there a pattern for dynamically saving lots of small json files to a file system?

I am hitting a REST API once a minute, looking for results from a form submission. Each form result is turned into a JSON document and saved to a database.

Often there's nothing coming back, and sometimes there are a few 10s of documents per hit. The documents end up being very small, like 10-50K each.

I've been asked to also save each document to a separate gzip on the filesystem (of a different server) as well. The files do not need to be organized; accessing via os.walk is fine. (I'm using Python.)

Plan is to create a main directory manually, and then, add subdirectories as necessary by checking to see if the last one created has more than 999 files in it:

# will manually create '~/data/poll/0000000000' just before running
# will run from ''~/data/poll'
def create_poll_dir():
    starting_path = os.path.join(os.path.expanduser('~'), 'data', 'poll')
    all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
    latest_subdir = max(all_subdirs, key=os.path.getmtime)
    path = os.path.join(starting_path, latest_subdir)
    if len(os.listdir(path)) > 999:
        new_dir = str(int(latest_subdir) + 1).zfill(10)
        path = ckmkdirs(os.path.join(starting_path, new_dir))
    return path

  1. Since this is simply for backup, with ease and speed of access not an issue, and the documents are so small, is appending everything to a log-like file, using jsonlines, a better approach (i.e. less filesystem strain, just as much data integrity)?
  2. If I stay with this approach (which would eventually throw an exception, as is, I know), should I be using a less-flat organization scheme? And does 1000 seem like a happy medium for number-of-small-files in a directory?

Unit of Work with Generic Repository for different dbContext

Is it possible to implement Unit of Work with Generic Repository if my application is having multiple contexts and each context referring to different database. If So? Could you please provide an example.Any help will be highly appreciated.

public class GenericRepository<TEntity> where TEntity : class
{
    internal SchoolContext context;
    internal DbSet<TEntity> dbSet;

    public GenericRepository(SchoolContext context)
    {
        this.context = context;
        this.dbSet = context.Set<TEntity>();
    }

I am doing as above. My question is can I generalize the context to be able to use different contexts for the same GenericRepository Class.

use template to instead preprocessor?

There are 2 classes, most code is same.

template<typename T>
class A1 {
f1(){common code... do_with(_m) ... common code}
f2();
fn();
T _m;
};

template<typename T>
class A2 {
f1(){common code... do_with(_m, _b) ... common code}
f2();
fn();
B _b;
std::atomic<T*> _m;
};

Because 95% code is same, I want to make those 2 class into one, but I can not use preprocessor due to both of them will be used in one project. And because these 2 class is template, so I can not use "template method" design pattern to extract same code into a base class and leave some private virtual function to derived class to override.

Is it possible to avoid code duplication? For example:

A<T, type_a1> a1;
A<T, type_a2> a2;

I have considered template specialization, but it can not support "extract the common part of code", a specialized class have to rewrite whole function

Instantiating objects that need to be injected with Bridge (pattern) objects. How should I do it?

The context is the following:

I have Job class that represents a Job that is sent to a Job Queue. Currently we only use SQS for that purpose, but in the future we might migrate to Redis or another MQ solution. So currently, I have a AbstractJob that can be extended into ConcreteJobOne and ConcreteJobTwo, and can be consumed by AbstractQueueClient (which can be SqsQueueClient). I need a way of getting the payload from a Job object, what I came up was using the bridge pattern.

$parameters = [];
$sqsClient = new AbstractQueueClient();
$jobOne = new ConcreteJobOne($parameters, new SqsPayloadBridge());
$sqsClient->queueSingleJob($jobOne);

With that, I'm able to change the way I can build the payload for a specific client.

But the Controller that takes care of queueing that job has to know about SqsPayloadBridge and all the other bridges that might come in the future. I thought about using the Factory pattern to solve this but seems like overkill.

Any thoughts?

Design pattern for use case

I wonder how would model this:

There are medical tests, such tests have a name, description, and may have one or more components.

Each component has a maximum value and a minimum reference value

Example, blood pressure is a test, and consists with systolic blood pressure and diastolic blood pressure.

There are also patients that perform these tests.

The form of modeling that comes to mind is this, but not convince me. enter image description here

Design patter for create specific view elements

Suppose we have an Abstract factory that creates for us some products. We know that the abstract factory can provide us some specific subclasses of the product but we don't want to check the type (this is the main reason for this pattern). Now we need to create a specific view for each type of object, how can we do this without know the specific type? Should the same factory create the different views?

How can an Entity Framework model be like an enum?

Currently I have some code that looks like this:

IsAuthenticated(string userName, Groups.Accounting)

Groups is obviously a enumeration.

The problem is that Groups is also a table in a database that can have values added, changed, or removed. When the above line of code ultimately resolves it is looking in a database to see if the provided user name has access to data only members of the provided group can see.

This creates a situation where I have to change code to match a database. It's not something that happens very often... but it's always going to be a problem.

Is there a design pattern I should be following to help resolve this scenario?

Using constructor declaration as a virtual function

I am not sure whether the question title is appropriate with respect to the details below.

I am working with a number of datasets which are widely different. So, I conceptualised that I would create a Base class "Dataset", from which "Dataset1", "Dataset2" etc would inherit. Now the situation is as follows:-

I want to have a uniform constructor as follows :-

Dataset(std::string category, )

So, for each dataset class I want to initialize them with category as the first argument and other variable arguments (which depend upon specific dataset).

My question is :-

Can I have a virtual constructor function in Dataset class, which can be inherited by "Dataset1", "Dataset2" and so on ? Is this the right design choice ? How do I implement it (variable arguments etc ) ?

Extract data before and after matching (BIG FILE )

I have got a big file ( arounf 80K lines ) my main goal is to find the patterns and pring for example 10 lines before and 10 lines after the pattern . the pattern accures multiple times across the file . using the grep command :

grep -i <my_pattern>* -B 10 -A 10 <my_file>

i get only some of the data , i think it must be something related to the buffer size ....

i need a command ( grep , sed , awk ) that will handle all the matching and will print 10 line before and after the pattern ...

Design pattern choice for a car configurator

The task is to design a database-assisted car configurator. The user can configure the car in multiple sub windows of the application, i.e. color, engine size, optional accesorries, etc. In a central overview window the essential configuration of the car is being shown (including the total price).

It's a task from university and I'm supposed to draw a class diagram and choose a central design pattern. But which pattern? I can kinda only think of a singleton for the car, to keep one state for in the whole application. Of course there are most likely many solutions to this.

Difference between MVP and MVVM

I read a lot of articles about MVC, MVP and MVVM. Most of the articles mentions MVP and MVVM in the same way. But only in some, it is mentioned that core part of MVVM is binding. WPF is a good example.

Is there any difference between MVP and MVVM other than binding ?

Some Object of a class can have a particular behavior but others doesn't

How can i design this particular Situation.

Basic Diagram of my problem.

Problem is :

  1. if i implement Swim in Bird and add diveNow() behaviour to "fly high" but it is not desired since all birds can't fly.

in other words "Some objects can do that and some can't and both belongs to the same class.

Can i use Strategy Pattern. How? What if i have a huge set of behaviors [Interfaces] having same kind of problem.

Best approach for storing changes to an object

Currently I am using Core-Data to store data that I receive via JSON from an external API.

Each 'record' contains a bunch of relationships and other associated data.

While the app is offline the user will make some changes, perhaps adding some images etc....

Then when the app is online the user can choose to 'sync' their changes.

What is the best approach to achieving this? I can write any changes to core data and then send back the record and its related objects but this seems like a waste of bandwidth, say if the user changes one aspect of one record, like editing its title for example, then when I press sync I'm essentially sending back all the records, irregardless of wether anything has changed.

I currently have a fetch request that queries wether I have an existing record and if so updates it..is that a possible approach to this problem? but in reverse..?

I apologise if this is seemingly vague, but I don't doubt someone has comes across this problem before, I'm struggling with the design pattern aspect of it

ways of using ninject properly in asp.net mvc

One of the definition of ninject in internet is;

"Somewhere in the middle of your application, you're creating a class inside another class. That means you're creating a dependency. Dependency Injection is about passing in those dependencies, usually through the constructor, instead of embedding them."

what i want to learn is, where ever we see a creation of a class inside another class should we use ninject or just we should use in some part of program that we want/need to apply loosely coupling for design purposes because maybe we would like to use different approaches in the future?

Sorry if this is a silly question.

How to get this simplified copy of FullCalendar working and understand the applied patterns?

I'm trying to get my head around the 11,000+ lines of JavaScript code in FullCalendar in order to be able to build new features into it, and so I am trying to understand the various patterns that are being used, especially the beginning here:

FullCalendar v2.4.0:

(function(factory) {
    if (typeof define === 'function' && define.amd) {
        define([ 'jquery', 'moment' ], factory);
    }
    else if (typeof exports === 'object') { // Node/CommonJS
        module.exports = factory(require('jquery'), require('moment'));
    }
    else {
        factory(jQuery, moment);
    }
})(function($, moment) {

;;

var fc = $.fullCalendar = { version: "2.4.0" };
var fcViews = fc.views = {};


$.fn.fullCalendar = function(options) {
    var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
    var res = this; // what this function will return (this jQuery object by default)

    this.each(function(i, _element) { // loop each DOM element involved
        var element = $(_element);
        var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
        var singleRes; // the returned value of this single method call

        // a method call
        if (typeof options === 'string') {
            if (calendar && $.isFunction(calendar[options])) {
                singleRes = calendar[options].apply(calendar, args);
                if (!i) {
                    res = singleRes; // record the first method call result
                }
                if (options === 'destroy') { // for the destroy method, must remove Calendar object data
                    element.removeData('fullCalendar');
                }
            }
        }
        // a new calendar initialization
        else if (!calendar) { // don't initialize twice
            calendar = new Calendar(element, options);
            element.data('fullCalendar', calendar);
            calendar.render();
        }
    });

    return res;
};
...

In order to understand what each line of this code is for, I'm trying to build a simplified copy of the it here:

http://ift.tt/1V9zW0U

What do I need to change to this jsfiddle to get it to the point that it is functioning as FullCalendar where I <div id='calendar'></div> produces HTML text in the same way that the FullCalendar module does?

I need to get it to this point so that I can begin building on it and thus coming into an understanding of how the FullCalendar module works in detail.

I've added questions regarding specific lines of code which are not clear.

// where exactly is factory being passed in?
(function(factory) {
    // I understand this code to be part of the 
    // JavaScript specification "Asynchronous Module Definition"
    // and seems to be defining jQuery and moment.js as dependencies
    // but they are available anyway so why do they need to be defined as dependencies here?

    // where is the variable "define" coming from?
    if (typeof define === 'function' && define.amd) {
        define([ 'jquery', 'moment' ], factory);
    }
    // where is is the variable "exports" being defined
    else if (typeof exports === 'object') { // Node/CommonJS
        module.exports = factory(require('jquery'), require('moment'));
    }
    else {
        factory(jQuery, moment);
    }
})(function($, moment) {

    // this I understand as simply defining an object "fullCalendar" in the jQuery scope
    // but what does it have to do with the $.fn.fullCalendar below?
    var fc = $.fullCalendar = { version: "2.4.0" };

    $.fn.fullCalendar = function() {
        return 'calendar test works';
    };
});


$(function() {
    $('#calendar').html('jquery works');    
    $('#calendar').fullCalendar();    
});

Should service layer return entity model that isn't mapped to an actual database table?

I have a web app with following design.

View -> Controller -> Service || Repository -> DB

For example :

Entity Model

public class Customer
{
    [Key]
    public int CustomerID { get; set; }
    public char Gender { get; set; }
    //rest of property here..
}

Context

public class TestContext : DbContext
{
    public DbSet<Customer> Customers { get; set; } //register entity class as DbSet
    ...

Repository

public IEnumerable<Customer> List()
{
    return _customer.AsEnumerable();
}

public void Insert()
{
    //...
}

public void Update()
{
    //...
}

Service

public IEnumerable<Customer> MaleCustomerList()
{
    return _repo.Customer.List().Where(w => w.Gender == "M");
}

public IEnumerable<Customer> FemaleCustomerList()
{
    return _repo.Customer.List().Where(w => w.Gender == "F");
}

So far we have no problem because service is returning entity model which is mapped to an actual database table. But what if I need to do some complex queries that return a completely different object, for example I need to group certain customer and calculate their percentage. I will need to return something like IEnumerable<CustomerGroup> where CustomerGroup is completely different with Customer, but it is not an actual table (because I don't need it) in the database.

So my question is, is it okay to make a new Entity model

public class CustomerGroup
{
    public int GroupName { get; set; }
    public decimal Percentage { get; set; }
}

but the different is that it's not registered in the Database Context DbSet so my service can return this type?

User definable object filters

I have many large collections of objects that need to be filtered. I need the filters to be flexible and user definable.

Hard coded, it might look something like:

selected = set()

for o in objects:
    if o.someproperty == 'ab':
        selected.add(o)

    if o.a == 'a' and 'something' in o.b:
        selected.add(o)

But I need something I can store in the db.

I've seen something referring to this is the Criteria (or Filter) pattern http://ift.tt/1a3MKTK but I can't find much information on it.

I'd like the rules to be flexible and serializable in a simple format.

Maybe the above could look something like:

someproperty == 'ab'
a == 'a', 'something' in b

With each line of the rule being a different set of things that need to meet. If any line in the ruleset matches then the object is included. But should the boolean logic be the other way around (with and between the lines and or within them)? Does this give the flexibility to handle various negations? How would I parse it?

What simple approaches are there to this problem?

mardi 25 août 2015

Null object design pattern Vs null object check

Why Null object Design pattern is better then null object check. If we look at memory footprint in Null object design pattern we create a new dummy object of same type.which show if we have object of big size and large number of nullable objects in search query ,this pattern will create that much number of null object which will occupy more memory then a simple check which for null which my cost ignore-able delay in performance.Null Object design pattern

Can I use something other than dynamic_cast in this design?

In our system, we have

  • multiple deviceTypes
  • each deviceType can have a different configuration type
  • each deviceType will be a library of its own

I'm in a situation where I am forced to use dynamic_cast. I'm wondering if there is a better way to design this.

what I have is:

// in common code
class Config {public: virtual ~Config(){} }; 

    class Device {
     protected:
        Config* devConfig;
    protected:
        virtual void createDevConfig() = 0;
    public:
        virtual void display() = 0;
    };

    // Device specific Code
    class A0Device : public Device {
    protected:
        virtual void createDevConfig() { this->devConfig = new A0Config(); }
    public:
        A0Device() { this->createDevConfig(); }

        virtual void display(){
        A0Config* config = dynamic_cast<A0Config*>(this->devConfig);

        if(!config) std::cout << "Null object\n";

        std::cout << config->getpConfig()->getA();
        }
    };

    class BlockAConfig {}; // in /common

    class A0PConfig {
    int a;
    public:
    A0PConfig():a(50){}

    int getA() { return a; }
    };
    class A0TConfig {};

    class A0Config : public Config {
    protected:
        BlockAConfig* blockAConfig;
        A0PConfig* pConfig;
        A0TConfig* tConfig; 

    public:
        A0Config(){
        this->blockAConfig = new BlockAConfig();
        this->pConfig = new A0PConfig();
        this->tConfig = new A0TConfig();
        }

        inline A0PConfig* getpConfig() { return this->pConfig; }
    };

    int main() {
        Device* dev = new A0Device();
        dev->display();
        return 0;
    }

Essentially A0Device has its own config type: A0Config, which is composed of other members. A0Device has devConfig defined as Config* in base class. In A0Device::display() - I need to access the devConfig object (as A0Config type). The virtual createDevConfig() ensures the config object will always be of type A0Config in A0Device => Is it safe to use dynamic_cast here ? Is there a better way of designing this ?

Design pattern for data lookups in JSON objects

So writing an application which uses a lot of user generated data. And in most cases I just use the mongodb id to look up whatever it is. So a typical example for this app is icons for categories. They are stored as a data set that gets passed around the application from the api that speaks to the mongodb to the api to a factory and then to the controller, and quite often I need to make a simple lookup. Lets say that the category looks as follows:

[
   {
       "_id":"55dc79efed0fcf4a58d4a68d",
       "categoryName":"Sport",
       "categoryDescription":"Sport and more sports",
       "categoryIcon":"55dc79b2ed0fcf4a58d4a68c",
       "__v":0
   }
]

categoryIcon is a reference to another table, at the time loaded in a factory, data looks as follows.

[
   {
       "_id":"55dc79b2ed0fcf4a58d4a68c",
       "iconName":"Sport",
       "cssString":"fa fa-futbol-o",
        "__v":0
    },
    {
       "_id":"55dc79b2ed0fcf4a58d4a69d",
       "iconName":"Travel",
       "cssString":
       "fa fa-plane",
       "__v":0
    }
]

So the way I have been resolving this is along the lines of

for (var i in icons){
    if( icons[i]._id == category.categoryIcon ){
        console.log("Found the Icon");
        category.cssString=icons[i].cssString;
    }
}

Easy, relatively fast, but seems a bit wasteful, so is there a smoother way. Made a simple jfiddle if anyone wants to test.

http://ift.tt/1PQYB7u

Thread safety with decorator pattern

This is rather long but I will try to be as clear as I can.

I have an interface, lets call it IFoo

class IFoo
{
public:
    virtual void reset(const Bar* bar) = 0;
    virtual int calculate(int i) const = 0;
};

a basic implementation

class FooBasic : public IFoo
{
private:
    int _value;
public:
    FooBasic(int value) : _value(value) {}

    virtual void reset(const Bar* bar) override {}
    virtual int calculate(int i) const override { return _value; }
};

and I have a base decorator for the interface

class FooDecorator : public IFoo
{
protected:
    IFoo* _foo;
public:
    FooDecorator(IFoo* foo) : _foo(foo) {}

    virtual void reset(const Bar* bar) override { _foo->reset(bar); }
    virtual int calculate(int i) const override { return _foo->calculate(i); }
};

and I have a tonne of implementations of the decorator which take pretty much the same form

class FooInt : public FooDecorator
{
private:
    int _y;
    int _z;
public:
    FooInt(IFoo* foo) : FooDecorator(foo), _y(0), _z(0) {}

    virtual void reset(const Bar* bar) override
    {
        _foo->reset(bar);
        _y = bar->expensiveIntFunction(15);
        _z = bar->expensiveIntFunction(10);
    }
    virtual int calculate(int i) const override { return _y*_foo->calculate(i) + _z; }
};

class FooIntStar : public FooDecorator
{
private:
    const int* _z;
public:
    FooIntStar(IFoo* foo) : FooDecorator(foo), _z(nullptr) {}

    virtual void reset(const Bar* bar) override
    {
        _foo->reset(bar);
        _z = bar->expensiveIntStarFunction();
    }
    virtual int calculate(int i) const override { return _foo->calculate(i)*_z[i]; }
};

The idea here is that clients of the IFoo interface will first call the reset() method passing in their Bar object. Then they will call the calculate() method millions of times with different integer parameters. The IFoo implementations will on the call to reset() extract some information from the Bar object and use it to set some internal members which they will then use to decorate the result from the underlying IFoo object. What they extract from the bar object depends on the implementation and could be different types/values.

This all works OK as long as there is a single client using the IFoo implementation. I am now trying to introduce some threading where I have different clients using the IFoo implementations concurrently. Each client has its own Bar object but I would like them to use the same instances of the IFoo objects (if possible). In the current state this will not work because the call to reset() sets member variables i.e. the reset() method is not const.

My plan it to create a workspace object which then gets passed around. Each client will own its own instance of the workspace to avoid conflict when several clients use the same object. On the call to reset, the IFoo implementations will set the temporary data in the workspace and not use internal members. However, since the type of data required for the different implementations is different it is tricky designing this workspace in advance.

One idea I have come up with is to make this workspace abstract and have the implementations extend it. So I'm thinking of changing the interface to

// Totally undefined object
struct IFooWorkspace
{
    virtual ~IFooWorkspace(){}
};

class IFoo
{
public:
    virtual IFooWorkspace* createWorkspace() const = 0;
    virtual void reset(IFooWorkspace* workspace, const Bar* bar) const = 0;
    virtual int calculate(IFooWorkspace* workspace, int i) const = 0;
};

and for instance the FooInt implementation

class FooInt : public FooDecorator
{
private:
    // Struct definition instead of member variables
    struct WorkSpace : IFooWorkspace
    {
        WorkSpace() : _y(0), _z(0), _ws(nullptr) {}
        virtual ~WorkSpace(){ delete _ws; }
        int _y;
        int _z;
        IFooWorkspace* _ws;
    };
public:
    FooInt(IFoo* foo) : FooDecorator(foo), _y(0), _z(0) {}

    virtual IFooWorkspace* createWorkspace() const override
    {
        WorkSpace* ws = new WorkSpace;
        ws->_ws = _foo->createWorkspace();
        return ws;
    }

    virtual void reset(IFooWorkspace* workspace, const Bar* bar) const override
    {
        WorkSpace& ws = dynamic_cast<WorkSpace&>(*workspace);
        ws._y = bar->expensiveIntFunction(15);
        ws._z = bar->expensiveIntFunction(10);
        _foo->reset(ws._ws, bar);
    }

    virtual int calculate(IFooWorkspace* workspace, int i) const override
    {
        const WorkSpace& ws = dynamic_cast<WorkSpace&>(*workspace);
        return ws._y*_foo->calculate(ws._ws, i) + ws._z;
    }
};

So the new plan is that clients will call createWorkspace() first and own the IFooWorkspace object returned. Then subsequent calls to reset() and calculate() should pass this workspace.

My problem is that it all looks rather convoluted and I'm not sure about the dynamic_cast in terms of safety and performance. So the question is: is there a simpler, cleaner way to achieve thread safety here? Ideally I would like to avoid creating new instances for the IFoo objects.

Correct MySQL structure for storing user-based data

So I have a question, I'm hoping it isn't too subjective.

I have a blog-style website, so on the homepage articles are loaded alongside the date published, the user that posted it, etc. Basic data like this.

I store it in MySQL like so:

article_id     username      date                     content          etc.
1              user1         2015-05-14 01:35:14      my content a  
2              user2         2015-05-16 02:33:15      my content b

This way, I can display it using one query, where I retrieve the username, date, content, etc.

My question is. I want to allow users the option to change their username. There are two options I see for this.

Either I continue storing data as I do now, and manually update tables like this with user-related data to the new username. Or I store data by a user_id rather than username, and have an extra query for each article loaded to get the associated username from another user table.

Which is the correct approach?

I ask this because I assume there's a recommended practice for this situation? Is it normal to store data by username and update it, or to store by id to avoid having to do this - but at the cost of the overhead when querying data. I'm guessing it's possible to display the username for id-based data in just one query, but that would still take significantly longer?

UML pattern for inherited object structure composition

The following situation:

I have: a) a super office has n or more main offices has none or more small offices b) all are offices c) the whole structure is twice (preserving the structure) for two business lines d) every office can be a legal representation e) each office can be in a different country

which UML pattern would you suggest

I tried: Composite pattern with leaf office and composite legal rep specializing in main office, super office, small office. Issue: how to represent business line?

Office with self reference (is super of, is main of, is small of) Issue: how to preserve structure for business line?

Composition (three objects super, main, small) Issue: how to preserve structure, and having three non inherited objects for the same seems ugly.

What is your view?

Design Pattern for perodic calculations

I need to get an idea for a design pattern to use in my context. I have a simple concept as follows:

There are 12 months in the year and every month has a different amount of days in it. Every month I have a bunch of different stock groups that need to have calculations done on them. Lets assume I have an array of different stock item groups. I now need to calculate the area used for all stock groups over the year.

So to simplify:

Each stock group has a method 'calculateArea' which will return a value. This calculation needs to be run every month to get an updated area for the stock group.

My idea was to use the iterator pattern to simply loop over each month and inside that iterate each stock group and run the calculate method for all. The implementation there would pretty much just boil down to 2 nested for loops. I know it's not the right OO approach just by looking at the above sentence.

What was suggested to me was the visitor pattern. This is something I have not used before so I'm trying to put it into context here.

I see this as setting up the 12 months as separate objects and then I would iterate over each month and each period would visit each stock group and do the calculations??? This is where it goes pear-shaped in my thinking.

The reason for the visitor pattern usage would also be that at some future point we would be calculating something completely different over the same month increments and would like to simply extend the existing framework/architecture.

To clarify, I have time for implementation so I'm trying to spend time up front to give it the best up-front design.

Any ideas/suggestions appreciated.

Customize ProgressBar Color Android

I want to change the color of my progressbar(circular style). The code for that seems to be controlled by the accent color attribute.

Moreover, i have a viewpager whose current tab indicator color is also controlled by the same accent color attribute.

How do i change the color of the current tab indicator to white without using the accent color?

How to get data from a database by user's role?

I'm using Hibernate ORM (with MySQL) and JavaServer Faces (PrimeFaces). Here is project structure:

              .//////////////////-                      
           `++:`                 -+o-                   
           d`                       h`                  
           do.                    `+d                   
           d`:+///-..`    ``.-://+/`d                   
           d    ``.-::////::-.``   `h                   
           h        MySQL DB       `h                   
           y.     .===========     `h                   
           y.`:///:..```````.:/+/:``y                   
           ys+.`                `./ys                   
           y:   `....`             :y                   
           :s`  s:--++       /y-  `o/                   
            .//:h`  :o      /+`s//+.                    
              `.h`  :y::::/s+  `s:                      
                y`  :o````++    `s-                     
              /os`  -os: `oo+   y+o                     
              `s-    :s`   -s   d                       
          s////+y.  -y+////os   d/////s`                
          d     .y.-s`     -s   d     y.                
          d      .ss`      .s///y     y.                
          d       ``        ````      y.                
          d           DAOs            y.                
          d         =======           y.                
          d     .s//+o       ++       y.                
          d-----/s  .h------o//o------h.                
          ------/s  .h-----s+  /y------                 
                -s  .y    +s`  `s+                      
              `so+  `ss:  -/o  o/-                      
          `+///so    -h////+s  s+///////-               
          `h````/+  -s`````-s  s-``````:o               
          `y     /+-y`     .s::y.      :o               
          `y      +s`       ....       :o               
          `y        Services           :o               
          `y       =========           :o               
          `y    .---:         -        :o               
          `y    o/..d       `os+       :o               
          `h    o:  h`     `o: /o`     :o               
          `s////y:  h/////+h-   :h/////+:               
              `oy-  y+/   +oo   ss/                     
               o:   `s-     d   d                       
      `+///////+d: `ys//////d   m/////////////          
      .y         s:s:       h```h            h          
      .y          o:        :::::            h          
      .y                                     h          
      .y                                     h          
      .y               Beans                 h          
      .y              =======                h          
      .y                                     h          
      .y                                     h          
      .h/////////////////////////////////////h          
       ```````````````````````````````````````          

(I'm a novice here and haven't enought rights to post imeges :D)
I have a method "getAllDevices()" that returns all devices from DB. Users-Devices relations are many-to-many. An User has an role either "ADMIN" or "USER". I want to get devices relatively user's role: if "ADMIN" - all devices in the DB, else only user's devices. How do I make it clear and avoid swelling code in beans or services? May be I should use some pattern here?

Specific instance/Non Singleton

How to instantiate java class with parameters and use the same instance through out the application?

What i want to do is when a tibco esb requests a web service call to my application,i will capture user information(user name) in one pojo class so that I can use this pojo class and user information at other places in application also for this particular tibco request.

This question might sounds crazy but I would like to implement something like this in my application.Waiting for your thoughts guys.

Design Pattern when using Entity Framework

I have confusion on Design pattern when working with Entity Framework. My current project has following pattern.

Pattern1: Each box represents a separate class library projects

Pattern1

Now a team member wants to introduce Entity Framework and suggests this:

Pattern2

Pattern2

I have seen several ASP.NET MVC web application samples where they keep DataContext and POCO classes in the same folders and no concept of logical service layer.

Patter1 Argument: Want to keep POCO classes and low level DataAccess call separate. Pattern2 argument: To keep related code in one project promoting "less Cohesion", and "low coupling"

So I want to understand a bit more on these two patterns and when to use one over another.

Gang of four patterns usage in automation frameworks

I would like to know which Gang of four design patterns may have important applications when developing an automation framework.

For example Page Object Model (not a Gof pattern btw) is one of the most commonly used design patterns which are incorporated while developing automation frameworks.

In the similar context, I would like to know which of Gof patterns are commonly considered.

Lastly, it could be for any type of automation framework (Key-word, data driven etc).

Thanks.

MVP Pattern: How does the model ask for a View?

I'm having troubles while implementing the MVP pattern. To explain it easy:

I have a WinForm (the View) who implements an interface (its corresponding IView). I have also a the presenter and, at last, the model.

But at the beginning, there was no IView, nor Presenter nor Model. There was one huge View that made everything. And so refactoring began...

Everything went fine, almost perfect. But now, I met this situation and a question about design came to me:

I found the view has a method which takes over of an event. This method is very big and have lots of logic. So I just put all the method in the presenter to free the view of logic. Everything was quite ok.

But then, I wanted to free the presenter from this logic and charge the model with it... because that logic were business rules!

I started doing this, and then I realized something: in some places this logic was asking me to instantiate other WinForms.

Now comes the question: If the presenter doesn't know anything about business rules, he shouldn't know when to instantiate a WinForm or not. So who knows? The Model, of course. But...

  1. How can the model tell somebody which View (and when) to instantiate?
  2. Who should be this "somebody"?
  3. Am I alright when I say the presenter should not know when and which view to create? Only tell the IView implementation to do it, only if somebody asks for it (maybe the model).

Thank you all!

Circular Dependency in java- Design

How to prevent circular dependency, any design patterns??,otherwise it will cause stack overflow. I was asked to redesign this.

class A {
    static void method(){
        B.method(); 
    }
    public static void main(String args[]){
        method();
    }
}

class B {
    static void method(){
        A.method(); 
    }
}

Suitable Design Pattern for message mapping

There are two message types (A and B) (derived from same interface), A separate class contains the mapping logic. I need to map fields from message A to message B based on the logic in mapping class. What would be the suitable design pattern for this scenario ?

Domain Events Implementation

We are starting DDD, and we need to implement domain events (DEs). We are thinking about "developping our own system" vs "prototyping an exiting framework". We know some things about DEs. But we need to have some real-life feedbacks about what features should be expected from such a system, before taking a decision :

  • Should DEs be stored and duplicated in each domain from a centralized event-store, before being consumed (for maintenance and logging purposes) ?
  • Do domains pick up events from the centralized event-store (if none), or do we need some kind of orchestrator for dispatching DEs ?
  • If we use a relational database for storing domains data (we know we should ignore it when desiging business logic), does that relational database fit for DEs, or should we prototype a NoSql database ?
  • Do we need to implement some tools to ensure events are well propagated into target domains ?

I know there are many questions here, to summarize I would just ask :

Based on your experience, what are the key-features we can expect from a "theorical DEs system" ? Have you develop your own implementation, does-it make sense ? Does a service-bus meet our needs ?

EntityFramework for multi-form winforms desktop app

I am developing desktop app based on winforms and EF. At the moment I have some problems with EF and architecture:

  1. Syncronizing data. There are multiple forms and each form uses it's own instance of Database Context. When data is updated on one form I need manually update it on other forms. There are a lot of non-flexible callbacks and copy-paste that refresh data.
  2. There are some calculations that running on client side and update a lot of records. Sometime user need to save it and with EF it takes long time. So, it is also running in separate Context so that work with other entities is not blocked
  3. There are DataGridViews with Binding entities and there are annoying problems with DbSet.Local and DbSet.ToList(). When data in gridview is saved it is sometimes is not updated in other places.

I am looking for any best practices and flexible patterns that can be used there. Also, looking forward to hear from those who solved same problems.

Thanks

Add dynamically methods to an object

Could you help me to find a solution to my problem?

I have a class that represents an entity (I will call it "Entity") I would like to dynamically add methods to my Entity according to different criteria.

For example:

If $_POST['TYPE'] == 'typeA', I would like to add following methods:

  • method1()
  • method2()
  • method3()
  • method4()

If $_POST['MODE'] == 'modeA', I would like to add following methods:

  • method5()
  • method6()
  • method7()

The problem is that there will be a lot of possible methods and if I add all of them to my class, I'm affraid that my class becomes too big.

So what is the best solution to do that?

Should I add all possible methods to my class?

Should I use inheritance and create all possible kinds of objects (Type1Mode1Entity, Type1Mode2Entity, ...)?

Do you know a design pattern (decorator?) to do that?

Ben

Builder Pattern vs Java Beans thread-safe

Based on this example http://ift.tt/1MKpv12

What if I change the usage in the first example to http://ift.tt/1haKPAI

Isn't it the same as the builder from the thread-safe point of view?