vendredi 24 juin 2016

Suggested design patterns or basic usages of reflection?

I know some of relection capabilities, but i never understand exectly when and why should i use them , I would like some examples on how and when is a good idea to use it? What are the design patterns you know wich performed with reflection? Is there any operation that can be done only with the use of reflection?

Create isolated DDD domain model as a lib, to be used for any client

I would like to create a DDD domain model library, to be used to any client. Where each client will provide default implementation of services.

design

My solution is something mixing Factory Method Pattern with Singleton:

1. domain-model.lib: Project structure:

project estructure

1.1. domain-model.lib: Implementation:

User.class:

public class User {
    private String id;
    private String name;

    public String getId() {
            return id;
    }

    public void setId(String id) {
        this.id = id;
    }


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

UserRepository.class:

public class UserRepository {
    public User getUser(String id){
        return UserDAOAbstractFactory.getInstance().getDefaultImplementation().read(id);
    }

    public void saveUser(User user){
        UserDAOAbstractFactory.getInstance().getDefaultImplementation().insert(user);
    }
}

UserDAO.class:

public interface UserDAO {
    User read(String id);
    void insert(User user);
    void update(User user);
    void delete(User user);
}

UserDAOAbstractFactory.class:

public abstract class UserDAOAbstractFactory implements Factory<UserDAO> {
    private static UserDAOAbstractFactory instance;

    public static UserDAOAbstractFactory getInstance() {
        if(instance == null){
            synchronized (UserDAOAbstractFactory.class) {
                if(instance == null) {
                    throw new IllegalStateException("Cannot call getInstance() method before calling build() method");
                }
            }
        }
        return instance;
    }

    public static <T extends UserDAOAbstractFactory> void build(Class<T> clazz) {
        if(instance == null){
            synchronized (UserDAOAbstractFactory.class) {
                if(instance == null) {
                    try {
                        instance = clazz.newInstance();
                    } catch (InstantiationException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                else{
                    throw new IllegalStateException("Factory already built. Cannot build twice.");
                }
            }
        }
        else{
            throw new IllegalStateException("Factory already built. Cannot build twice.");
        }
    }
}

Factory.class:

public interface Factory<T> {
    T getDefaultImplementation();
}

2. "Application 1" - Project structure:

project structure- application 1

2.2 "Application 1" - Implementation:

UserDAOFactoryMock.class

public class UserDAOFactoryMock extends UserDAOAbstractFactory {
    private UserDAO userDAOMock = new UserDAO() {
        final String USER_ID = "123";
        User user;

        @Override
        public User read(String id) {
            if(user.getId().equals(USER_ID)){
                return user;
            }
            return null;
        }

        @Override
        public void insert(User user) {
            this.user = user;
            this.user.setId(USER_ID);
        }

        @Override
        public void update(User user) {
            throw new UnsupportedOperationException();
        }

        @Override
        public void delete(User user) {
            throw new UnsupportedOperationException();
        }
    };

    @Override
    public UserDAO getDefaultImplementation() {
        return userDAOMock;
    }
}

UserDAOFactoryTest.class

public class UserDAOFactoryTest {

    public UserDAOFactoryTest(){
        UserDAOAbstractFactory.build(UserDAOFactoryMock.class);
    }

    @Test
    public void insertReadUser_expectOK(){
        User user = new User();
        user.setName("Paulo");

        UserRepository userRepository = new UserRepository();

        // Insert User
        userRepository.saveUser(user);
        String userId = user.getId();

        // Read user
        User returnedUser = userRepository.getUser(userId);

        // Check
        assertTrue(user.getId().equals(returnedUser.getId()));
        assertTrue(user.getName().equals(returnedUser.getName()));
    }
}

My concern is, it is a good approach to use with the team? There is some anti-pattern?

in C#, what is the best way to have a global property but can be changed only by single class

I have a property e.g. rate which must be available through out the application to all classes as a readonly property, but admin should be able change it at any time.

What is the best way to achieve that in OOP world?

awk to print from last match of start match pattern till end pattern

I have a file with contents like this.

if {[CELL NAME "CELL1"]} {
define_cell \
       -pinlist { i0 i1 i2 0 } \
       CELL1
}
if {[CELL NAME "CELL2"]} {
define_cell \
       -pinlist { i0 i1 i2 0 } \
       CELL2
}
define_cell \
       -pinlist { i0 i1 i2 0 } \
       CELL3  
define_cell \
       -pinlist { i0 i1 i2 0 } \
       CELL4

I am trying to get a subsection like this.

define_cell \
       -pinlist { i0 i1 i2 0 } \
       CELL3

When I am trying to do so with a simple script like below, I am actually getting from first match of define_cell till the end of the file contrary to my expectation.

awk '/define_cell/,/CELL3/{print $0}' <FILE>

How can I achieve the specific goal. I have tried to follow the solutions suggested in this. awk find the last match and print the next N lines But not able to get it to work.

Which way is better to encapsulate a single unit of work in Node.js, OOP or functional?

I have a complex buisness action for example deleting a user account. It contains multiple connected steps, and has to keep track of some state between steps. What is a better approach for writing this action?

I see a lot of more functional approach like one below.

function someAction(someParam, anotherParam, callback) {

    async.waterfall([
            step1,
            step2,
            step3,
            step4
            ],callback
    );

    function step1(p,cb){/**use someParam and anotherParam here via closure*/}
    function step2(p,cb){/**...*/}
    function step3(p,cb){/**...*/}
    function step4(p,cb){/**...*/}
};

someAction('value', 1241, (err)=>{/**...*/});

What I don't like about this approach is that everything is defined within the scope of a single function (here someAction).

I find a more object-oriented way to be a little more readable. The state and the stepX functions are not truly private - sometimes it is convenient for testing.

function SomeAction(someParam, anotherParam){
    //private state
    this._someParam = someParam;
    this._anotherParam = anotherParam;
};

SomeAction.prototype._step1 = function(p, cb){
    //use this._someParam and this._anotherParam
};

SomeAction.prototype._step2 = function(p, cb){
    //use this._someParam and this._anotherParam
};

SomeAction.prototype._step3 = function(p, cb){
    //use this._someParam and this._anotherParam
};

SomeAction.prototype._step4 = function(p, cb){
    //use this._someParam and this._anotherParam
};

//public api
SomeAction.prototype.execute = function(callback) {
    async.waterfall([
                this._step1,
                this._step2,
                this._step3,
                this._step4
            ],callback
    )
};

new SomeAction('value', 1241).execute((err)=>{/**...*/})

Is there any performance difference between them ? What is the recommended approach in Node.js ? Is it true that each time I callsomeAction in functional approach - all the stepX functions have to be defined from scratch ?

Applying design patterns [on hold]

I am having problem with application of design patterns , i don't know whether below scenario requires design pattern .

I have implemented real-time streaming in my application , however i have not followed any design , i feel i lack design skills in me . Below is the way the real-time streaming works.

1) Polling request is made to Async servlet(PriceAsyncServlet) , all the request are hold in context in queue in AccumalateRequest.java
2) Price details are feed into mq from third party system every seconds via xml
3) Spring MDB (MessageListerner.java) listens to messages in mq
4) MDB parses the xml using XmlParser.java which uses staxParser
5) Once the xml parses data and set data in java object , the java object is updated to cache manager
6) CacheEventListener.java method get invoked since it is listener for any modification on ehcache instance, all price are set to aysnc context of asynchronous servlet and hence price is delivered to front end.

Below is the class diagram depicting the same:-

enter image description here

Could i done a better design , instead of writing a MDB,XML parser . Could i have applied any design here ? when i can apply design pattern and when i cannot apply design pattern ?

What is the common way to handle successful REST POST operation in UI using React and Redux

I have a Thread component responsible to render messages of the specific thread and a component to submit a new message. Thread component's state is managed by Redux, which provides asynchronous actions like FETCH_MESSAGES and POST_MESSAGE. Below is the simplified pseudo-code.

class Thread {
  messages: [] // This is actually a prop connected to Redux
  render = () => {
    messages.map(messageComponent)
    <SubmitMessageComponent />
  }
}

What is the common way to handle successful POST operation of new Message in the UI, when server sends the object back with id? Is it safe to push that object to the array of earlier fetched messages or should I fetch all messages again to ensure consistency? First operation seems efficient but disjointed. I'm considered about handling concurrent REST API operations from different sources properly. Fetching everything all over again would always ensure the consistency of the state, but would be redundant performance wise (Imagine there are near infinite amount of messages)

Is there de facto way to deal with create operation in web application user interface?