jeudi 30 novembre 2017

What kind of design pattern XxxxHelper is?

I got a one-year-old legacy project from other develop a team. In the project, I found a folder called "Utils". In this folder, There are many XxxxHelper.swift source code files. These helpers are also wrapping some third party pods.

Example: DeepLinkHelper wraps CocoaPods "Branch"

import Foundation
import Branch

class DeepLinkHelper {
    static func handleDeepLink(params: [AnyHashable:Any]?, error: Error?) {
        if error == nil {
            if let clickedBranch = params?["+clicked_branch_link"] as? Bool, let referringLink = params?["~referring_link"] as? String, let referringUrl = referringLink.toURL(), clickedBranch {
                let endpoint = referringUrl.lastPathComponent
                switch(endpoint) {
                case "debugLink":
#if ENV_DEBUG
                    NotificationCenter.default.post(name: Notification.Name(rawValue: InternalNotifications.backgroundAlertUser), object: nil, userInfo: ["title":"Branch Link","message":"Success!"])
#endif
                    break
                case "connaccts":
                    // Display connected accounts
                    NotificationCenter.default.post(name: Notification.Name(rawValue:InternalNotifications.switchToViewController), object: nil, userInfo:["destination": ViewControllerNames.connections])
                    break
                case "guestinvite":
                    // Request server to add source account as unvalidated connection
                    if let gValue = params?["g"] as? String {
                        handleGuestInvite(gValue)
                    }
                    break
                default:

                    break
                }
            }
            print("BranchIO-DLparams: \(String(describing:params))")
        }
        else {
            print("BranchIO-Error: \(error!)")
        }
    }
    static func handleGuestInvite(_ gValue: String) {
        NotificationCenter.default.post(name: Notification.Name(rawValue:InternalNotifications.switchToViewController), object: nil, userInfo:["destination": ViewControllerNames.main,"reset":true,"guestInviteData":gValue])
    }
}

Other helpers:

KeychainHelper.swift wraps the pod KeychainSwift. PhotoHelper.swift wraps the pod TOCropViewController and other native kits TrackingHelper.swift wraps the pod Tune

Question again:
What's these design pattern? And, what is the benefit to wrapping native or third-party SDKs and kits?

Vue.js - Declare a parent model on container

Is there any way of making this work?

Javascript:

const vm = new Vue({
  el: "#app",
  data: {
    invoice: {
      title: "test"
    }
  }
})

Pug:

#app
  // This works
  h2 
  input(v-model="invoice.title")

  // This is the thing I want to work
  div(v-model="invoice")
    span 

The thing I want to achieve is to say that "this whole container is bound to this object in the data. Every child of it should try to find the wanted data in that object and not in the root.

Let's say I have a lot of properties in the homeAddress object, then I don't want to have to write

.container
  span     
  span 

but only

.container(v-model="homeAddress")    
  span 
  span 

Design Patterns need to be required for which roles

Can some one help me out on this topic

Design Patterns need to be required for which roles

a. Analyst

b. Designer

c. Coder

d. Tester

Options

  1. a,b & c

  2. b & c

  3. a only

  4. a,b,c,d

Git: is there a good workflow for rapidly prototyping code

I often spend time 'experimenting' with code, rapidly prototyping different ideas before deciding on a final approach; but I'm struggling to find a good workflow that supports "checkpointing" my progress.

Using git I can easily commit at any stage, but jumping back and forward between commits on a branch rapidly becomes frustrating as I end up on headless branch and it's easy to lose further commits as they're not really tracked anywhere. Creating multiple branches like "featureA_simple_threshold_20", "featureA_simple_threshold_10", "featureA_complex_threshold_42" alleviates that problem, but leads to (what seems to me) a very messy workspace; and that's before conflicts start.

I've had a look at the recipy package for Python: http://ift.tt/1i9jrUD which is similar to what I'm looking for, but relies on persisting array-like objects, while I'll often just have a handful of print statements for my results.

This seems like it should be a pretty common use case, so are there any good workflows that can be recommended? Is there an alternative tool that could help me out here? (I'm primarily developing in Python, but this seems like a non-language specific problem)

Remove if statement and make it more readable

Hi wondering if there is a better way to remove this else if statement and use a strategy pattern. any ideas?

public async Task<TResponse> HandleResponseAsync<TRequest, TResponse>(TRequest item)
    where TResponse : class, new()
{
    TResponse result = default(TResponse);
    Type currentResponseType = typeof(TResponse);   

    if (currentResponseType == typeof(MyResponseA))
    {
        result = //dosomething
    }
    else if (currentResponseType == typeof(MyResponseB))
    { 
        result = //dosomething
    }
    else if (currentResponseType == typeof(MyResponseC))
    {
        result = //dosomething
    }

    return result;
}

design a master controller/scheduler

Well design a master controller/scheduler which should be configurable and capable of running multiple processors at a same time

Scheduler Operation :-

scheduler process should be able to perform various operations below are the examples

  • execute sql queries and stored procedures in the database 2 should be able to send emails with given set of arguments and attachment to business 3 should be able to send ftp files based on input arguments 4 should be able to execute batch files process should have below capabilities

    Process Operation :-

    1 Remotely start/stop a child process 2 Raise alerts when any above process fails 3 Automatically restart the process if it fails 4Remotely kill a child process that breaches a pre set timeout limit

    So for scheduler and processor I have to come to design with

    1 High level design
    2 Class level diagram
    3 Design should be flexible t incorporate more operations

    4 any design pattern you think we can use

dynamically choose API to use

I use an external tool in my Python code. In order to initialize this tool, I have to create a couple of objects. The external tool in question provides two quite different APIs, and no one of these APIs is capable of creating all objects the tool needs. Let's say, the tool is trafic simulation tool, where car objects are created using API 1 and bikes are created using API 2.

I have played with inheritance, tried to pick an appropriate design pattern but all my solutions look ugly to me.

The most simple way to represent what I am trying to achieve is:

class ObjectHandler():    
    api_1_types = ('type1', 'foo')
    api_2_types = ('type2', 'bar')

    def __init__(self):
        self.handler1 = ObjectHandler1()
        self.handler2 = ObjectHandler2()

    def create(self, obj_type):
        if obj_type in self.api_1_types:
            return self.handler1.create()
        elif obj_type in self.api_2_types:
            return self.handler2.create()
        else:
            raise NotImplementedError

class ObjectHandler1():
    def __init__(self):
        # load external module that defines API 1
    def create(self):
        # return an object created via API 1

class ObjectHandler2():
    def __init__(self):
        # load external module that defines API 2
    def create(self):
        # return an object created via API 2

if __name__ == '__main__':
    handler = ObjectHandler()
    object_1 = handler.create('type1')  # must be created by ObjectHandler1
    object_2 = handler.create('type2')  # must be created by ObjectHandler2

I am now searching for a good OO and pythonic way to achieve this.

Up-/Download of big files via REST

Simple question: I want to upload/download large files around via REST. What is the best practice to do that? Are there any chunk-patterns, do I use multipart on the transport layer, what do you recommend?

Use case: we have an API where you can upload payments (e.g. 500mb) and download large account statement files. I am aware that other protocols exist to do that but how is it done with REST?

mercredi 29 novembre 2017

How to maintain asp.net mvc model binding on post to action method when there are many possible models

I have an asp.net mvc web page with drag and drop. Each item that can be dragged has its' own and different model. There will be hundreds of potential models and up to 2 can be dropped and posted to the action method at one time.

Currently I have one action method that has an input parameter of FormCollection because of the MANY potential models. Is there any way to have the input parameter the specific model instead of FormCollection? This is only a problem for me because there are potentially hundreds of different models. My current design will require me to manually map the fields, unless I can input the model(s).

reactjs services and presentation components splitted

I am giving my first steps into reactjs. I created a service to the movie db API using fetch. I already accomplish to list the name of the movies.

What I am trying to do is have a completly independent components. One component to connect to the API and other component be responsible to present that info.

Right now what I have both of this behaviours in the same component :(

Can anyone help me?

Here's my code

import React, { Component } from 'react';

const listUrl = 'http://ift.tt/2jv9WkI';

class ListingService extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    fetch(listUrl)
      .then((response) => {
        if (!response.ok) {
          throw Error('Network request failed');
        }
        return response;
      })
      .then((response) => {
        return response.json();
      })
      .then((response) => {
        this.setState({
          movieName: response.results.map((movie) => {
            return (
              <li key={movie.id}>{movie.title}</li>
            );
          }),
        });
      }, () => {
        this.setState({
          requestFailed: true,
        });
      });
  }

  render() {
    if (this.state.requestFailed) return <p>Failed!</p>;
    if (!this.state.movieName) return <p>Loading...</p>;
    return (
      <div>
        <h2><ol>{this.state.movieName}</ol></h2>
      </div>
    );
  }
}

I have a father component with this code:

import React from 'react';
import ListingService from '../../services/listing/index';


const List = () => {
  return (
    <div>
      <b>List of movies</b>
      <ListingService />
    </div>
  );
};

export default List;

Should I use redux to this?

Using PHP DBC Class in other files [duplicate]

This question already has an answer here:

Coming from Java I am very confused how the PHP class system works. I have a DBC class and a User class. Both I have to use in a third PHP file (signup.inc.php), but this error occurs: Uncaught Error: Call to undefined method DBC::prepare() in User.php DBC::prepare().

So User.php doesn't know that $this->dbc is a PDO object? I tried to google something similar but still don't get how the class/inheritance system works. Does anyone have a tip or tips for improvement?

DBC.php (db connection with singleton):

class DBC {

private $connection;
public static $_instance;
private $dbServer = "...";
private $dbUsername = "...";
private $dbPassword = "...";
private $dbName = "...";

public static function getInstance() {
    if(!self::$_instance) {
        self::$_instance = new self();

        return self::$_instance;

    } else {
        return self::$_instance;

    }
}

private function __construct() {

    try {

        $this->connection = new PDO("mysql:host=".$this->dbServer.";dbname=".$this->dbName,
        $this->dbUsername,
        $this->dbPassword,
        [
            PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
        ]);

        $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        self::$_instance = $this->connection;

doesn't show the rest of this file in one piece ...

} catch (PDOException $error) {
            #...
        }

    }

    private function getConnection() {
        return $this->connection;
    }

}

User.php:

include_once 'DBC.php';

    class User {

        protected $email;
        protected $...;
        protected $...;
        protected $...;
        protected $...;
        protected $...;

        public function __construct($dbc) {
            $this->dbc = DBC::getInstance();
        }

    function findByEmail ($email) {

            $statement = $this->dbc->prepare("SELECT * FROM user WHERE user_email = :user_email");
            $statement->bindParam(":user_email", $email);
            $statement->execute();

            if ($statement->rowCount() > 0) {

                return false;

            } else {

                return $this->createUserFromDB($statement);
            }

        }

And the call in signup.inc.php:

 require_once 'DBC.php';
    require_once 'User.php';

        $dbc = DBC::getInstance();
        $user = new User($dbc);

Strategy Pattern and Open-Closed Principle Conflict

I was reading through strategy pattern and was trying to implement it but I have got stuck at deciding the strategy implementation which I feel violates the open-closed principle.

In strategy pattern we code to interface and based on client interaction we will pass in the strategy implementation.

Now if we have bunch of strategies so we need to decide using conditions which strategy the client chooses something like

IStrategy str;
    if(stragety1) {
     str = new Strategy1()
    } else if (stragety2) {
     str = new Strategy2()
    } and so on..
str.run()

Now as per open-closed principle the above is open to extension but it is not closed to modification

If I need to add another strategy(extension) in future I do need to alter this code.

is there a way where this could be avoided or it is how we need to implement strategy pattern ?

Translating wrapper-/proxy- pattern to redux

I am currently investigating reduxjs as a viable framework for an upcoming project. There, we migrate from an old solution, which makes heavy use of the proxy/wrapper pattern.

i.e.:

  • there are models which are kept dumb (pojo) intentionally. They only carry data. Let's assume these are tasks

  • Now these tasks are wrapped dynamically with objects that add cross-cutting features like validation and change tracking to them.

Now: Whenever the property is changed, in effect, 3 changes to the application state may happen. E.g.:

  1. the "title" property of the task is changed
  2. as this change is done throught the wrapper/proxy, it detects the change and
    1. a) updates the "haschagnes" field to "true"
    2. b) and (potentially) adds a validation error to the "validationErrors" list

As far as I understand, in Redux, every action should only be handled once and lead to 1 atomic state change. However, in this case, it would be up to three changes.

So my question is: Is it possible to translate this wrapper/proxy- pattern based approach to a redux style one? And if so, how? (Middleware, WrapperReducer, ...?)

Thank you guys!

Java: avoid spaguetti code

I often so far it comes me up the next code:

public ClassA getClassA(AType type)
{
    switch (type)
    {
        case AType.T1:
           //result = a lot of code
           break;
        case AType.T2:
           //result = a lot of code
           break;
        case AType.T3:
           //...
    }

    return result;
}

I'm posting this question here because I looking for a way to do it a bit more ellegant using design patterns (creating additional classes (strategies?, factories?...) or whatever idea.

Currently, I think this code is like an spaguetty-like code.

Any ideas?

onblur and onclick in at a time in js

i have a case where on a page there is a input field and a button to next page.

Now if onblur event is called on input the data should get saved and onclick of button the page should redirect to next page with the latest data from this page.

if the user types in input and directly hits the button, both the events are called at the same time and the latest data is not saved.

is there a design pattern or a common solution to this problem?

mardi 28 novembre 2017

Best pattern or strategy to store Diagrams (and Models)?

We are developing a simple Modeling Tools (to use it in other refactoring tools) to manage diagrams like CDG (Call Dependency Graph between classes) and etc.

Our diagrams are similar to UML diagrams and they have some details like Use Case or Class Diagram's details.

In this project we should store diagrams and open them later for some changes by users. (Similar to other modeling tools)

Basic Implementation of this tools in Java are here:
http://ift.tt/2jvLpw3

The Question is: What is the best way to store a diagram? Which patterns exist to do this (and our team should learn them)?

Two factors are important:
1- performance of reading and writing diagrams.
2- diagram size on the hard/server.

Vue Updated or undo pattern with child component

I have a problem with updating the correct object from a child component.

My setup is as following: One ul list with most of the data that I want to present or edit. On one part of the "li", there is a child component to show that part of the data, which is a list of resources connected to that object, and also to handle the push of new resources.

I also want the user to have a button the enable edit mode of the row, and then buttons for Update and Cancel.

The problem I'm facing, is to figure out which object I should edit and then save. What I'm doing now, is trying to copy the data in row into a mutableRow that I'm then using as my model for the input controls, while the actual row data is being shown when the user is not in edit mode. In the update method, I post to the db and updated the row object.

ul
  li(v-for="row in rows")
    p(v-if="!row.editing") 
    input(v-else, v-model="mutableRow.name")
    resources(:row="row")
    button(v-if="!row.editing") Start edit
    template(v-else)
      button Update
      button Cancel

Is this the correct way to do it and if so, how should I handle the prop being sent to my child component? I've tried fetching the mutableRow via this.$parent.mutableRow, I've tried switching the "resource(:row="row")" with a v-if and send in mutableRow if in edit mode, but then I end up changing both objects from the component some how.

Is there another pattern I could use here?

Does this transformation pattern have a name?

A random thought just came to mind: it is possible to implement accessors and mutators by passing a function that takes, transforms, and returns data. Of course, far more than accessors and mutators can be implemented with such a capability, but transformations can be very simple in their design.

  1. Does this design pattern have a name?
  2. Are there any languages that regularly use this pattern?

As an example, the Child class uses simple transformations to create an accessor and mutator:

#! /usr/bin/env python3
def main():
    c = Child(123)
    assert c.data == 123
    c.data = 'Hello'
    assert c.data == 'Hello'
    c.data += ', world!'
    assert c.data == 'Hello, world!'


class Parent:
    def __init__(self, data):
        self.__data = data

    def transform(self, transformer):
        self.__data = transformer(self.__data)


class Child(Parent):
    def __get_data(self):
        self.transform(self.__collect)
        return self.__value

    def __collect(self, value):
        self.__value = value
        return value

    def __set_data(self, value):
        self.transform(lambda data: value)

    data = property(__get_data, __set_data)


if __name__ == '__main__':
    main()

Design pattern for a calculation that has to output a report in Ruby

I have a class that does calculations. Most of the times it is used in the code to output a single value:

Use: value = Calculator.new(1234).output

This is an example of the class definition:

class Calculator

  def initialize(parameter_1)
    @parameter_1 = parameter_1
  end

  def output 
    op_1_result = operation_1(@parameter_1)
    op_2_result = operation_2(op_1_result)

    operation_3(op_2_result)
  end

  def operation_1(param)
  ...

end

But sometimes the user has to print a report of the calculation, showing many of the variables from inside the calculations.

The first solution I implemented was to pass a parameter at initialization telling the class that it should save some internal variables for the report, like this:

class Calculator

  attr_reader :report

  def initialize(parameter_1, reporting=false)
    @parameter_1 = parameter_1
    @reporting = reporting
    @report = {}
  end

  def output 
    op_1_result = operation_1(@parameter_1)
    @report[:op_1_result] = op_1_result if @reporting

    op_2_result = operation_2(op_1_result)
    @report[:op_2_result] = op_2_result if @reporting

    operation_3(op_2_result)
  end

  def operation_1(param)
  ...

end

Then, when I want to get those intermediate variables, I would:

calculator = Calculator.new(1234, true) # reporting activated
report = calculator.report

report[:op_1_result] # one of the intermediate variables of the calculation

Does this break the single responsibility principle, as the class is now calculating the value and reporting at the same time?

Is there a better way to do this, a design pattern where I could have a fast calculation of the output result where it is needed and show the report where needed without all those ifs?

Any light on this and comments will be really appreciated!

Hiding implementation of members owned by PImpl-objects

I have a class which I want to create an interface for without showing any of the implementation (not because it's closed source, but because of a lot of unnecessary headers such as OpenGL coming with it), let's call that class Foo. I know this is commonly done through either the PImpl-idiom or virtual interfaces, and I've implemented the PImpl-idiom for that class.

However, this class has public functions which returns other classes that are also including those headers, so obviously I can't return those objects as-is as that'd require me to include headers I don't want to include in Foo.h. However, these classes are used internally within the library a lot, and thus I don't want to implement them with PImpl as that'd introduce a lot of overhead (they're used a lot within a 3D renderer's code). Let's call one of them Bar:

Foo.h:

#include "Bar.h"

class Foo
{

private:
    class impl;

    std::unique_ptr<impl> m_pimpl;

public:
    Foo();
    Bar& get_bar();
};

Foo.cpp:

#include "Foo.h"

class Foo::impl {
private:
    Bar m_bar;

public:
    Bar& get_bar();
};

Foo::Foo() : m_pimpl{std::make_unique<impl>()} 
{ }

Bar& Foo::get_bar() {
    return m_pimpl->get_bar();
}

For this to work I need to #include "Bar.h", but Bar.h might include headers I want to hide. This leaves me with the option to make Bar use the PImpl-idiom as well, but I don't want that overhead for Bar because Bar is used a lot internally within Foo. However, I figured a way to solve this, but I'm not very sure about it as I haven't seen it used anywhere before:

Using PImpl without an owning pointer/reference to simply wrap a class and create a interface for it. This way the overhead only applies when outside of Foo, but internally it'll still use the non-wrapped class.

For example, let's say PBar is wrapping Bar:

PBar.h:

class Bar;

class PBar {
private:
    Bar &m_bar;

public:
    explicit PBar(Bar &bar);
    void do_stuff();
};

PBar.cpp:

#include "PBar.h"

#include "../impl/Bar.h" // This is the actual Bar implementation


PBar::PBar(Bar &bar) : m_bar(bar) {

}

void PBar::do_stuff() {
    m_bar.do_stuff();
}

And Foo instantiates PBar on creation with a reference to the actual Bar inside the object:

Foo.h

#include "PBar.h"

class Foo
{

private:
    class impl;
    std::unique_ptr<impl> m_pimpl;
    PBar m_bar;

public:
    Foo();
    PBar& get_bar() { return m_bar; }
};

Foo.cpp:

class Foo::impl {
private:
    Bar m_bar;

public:
    Bar& get_bar();
};

Foo::Foo() : m_pimpl{std::make_unique<impl>()},
             m_bar(impl->get_bar())
{ }

Is this pattern ever used? Are there any other ways I can solve this problem? It's more or less the same principle as PImpl, but is there anything bad about it I haven't yet thought about? It definitely feels even less clean, but I can't see how this could be done in any other way.

Also, I want neither PBar or Bar to be constructable outside of Foo, so that's not a problem.

Thanks!

Purpose of passing factory object in Simple Factory Design Pattern (Head-First)?

I am from C++ background, recently started learning Design Patterns.

I am facing problems with this code from Head First Design Patterns:

Link: PizzaStore.java

public class PizzaStore {
SimplePizzaFactory factory;

public PizzaStore(SimplePizzaFactory factory) { 
    this.factory = factory;
}

public Pizza orderPizza(String type) {
    Pizza pizza;

    pizza = factory.createPizza(type);

    pizza.prepare();
    pizza.bake();
    pizza.cut();
    pizza.box();

    return pizza;
} 
}

Please help me with the following doubt:

What is the relevance of passing a factory object in the Constructor of PizzaStore class ?

  • PizzaStore class already contains a SimplePizzaFactory object
  • The passed-on object is not initialized with any data (which needs to be copied by PizzaStore Constructor):

    public PizzaStore(SimplePizzaFactory factory) { 
    this.factory = factory;
    
    

    }

Thanks

Research appropriate tools for query building

guys, please give me some advice to choose appropriate tools for my requirements.

I have some object (for example SQLBuilder) that receives some dto (that represents native random SQL) and parse it.

SQLBuilder also is supposed to know how:

1) Work with LINQ or something like this (It's the hardest part, because for this purpose we need static types (linq to sql provider), but we don't know concrete types. Queries that we received can work with be random tables):

  • SQLBuilder.Where( x=> x.id == 2 )

2) Release native SQL:

  • SQLBuilder.ToSQL ()

3) Append native SQL in different parts and replace old one if it already exists there:

 - SQLBuilder.AppendWhereSQL ( "Where id = 3")
 - SQLBuilder.AppendSelectSQL ("Select Id, Name")
... etc.

I think it's a relatively common task in developing and there is exists ready appropriate tools (framework, dll etc.) that implement similar functionality

Check an object for interface which is not impemented

I am looking for a possibility to check, if an object fit to an interface, which is not implemented by the object.

Since composer changed the way of programming in php, you do not have access to all of the code you use.

For example you want to extend a composer project of yours. You want to manipulate an Collection. There are multiple classes, where you could use your new package. In some regions of your project, there are ArrayObject´s in other regions there are Collection´s with different interfaces. You want to get them all, but you can not manipulate all these old classes, because it´s legacy :) or a packagist package.

Thatswhy I am looking for a nice way to check, if an interface in one package fit to an object in an other package, which do not implement this interface.

// come from one package and I can not change the class
class FreshExample extends \ArrayObject
{
    public function doSomething(): string
    {
        return 'a new thing';
    }
}

// come from an other package and I can not change the class
class OldExample extends \ArrayIterator
{
    public function doSomething(): string
    {
        return 'a old thing';
    }
}

// my new package classes
interface ExampleInterface extends \Iterator
{
    public function doSomething(): string;
}

class WorkWithExamples
{
    /**
     * @param OldExample|FreshExample|ExampleInterface $example
     *
     * @return string
     */
    public function manipulate($example): string
    {
        // here I want to check if the incoming object fits to the interface
        if (false === $example->valid()) {
            return $example->doSomething();
        }

        return sprintf('%s!', $example->doSomething());
    }
}

One possibility would be, to use reflaction classes for the interface and the other objects, for a check, if both have the same methods, and so on.

An other way could be to use the decorator pattern.

Are there any other, or better way?

Interpreting class as text

(Apologies for the long question)

Hi, We have a service running that monitors our queues every 15 minutes and outputs the result to a number of things (company IM, logs, Table storage). I am looking for a nice way to translate the data into "smart" text to output to our IM.

The service monitors 3 things (Alerts) and the result object looks like

    public class ServiceMonitorResult 
    {
        public string Name
        public int Count 
        public int Age 
        public int Delta
        // our 3 alerts
        public IAlert CountAlert // can be null 
        public IAlert DeltaAlert // can be null 
        public IAlert AgeAlert   // can be null 


    }  

    public interface IAlert
    {
        AlertStatus Status// enum : New - Continuing - Ended
        ...
        public string MessageText   //  usually like $"{ServiceName (very long)} {alert status} breached  {Alert}  with value X at {DateTime.Now}. Started At {startedAt}"
    }

When this result gets sent out on our compay IM, the result can sometimes be very verbose. We have over 200 services, if we have an average of 10% breaches, that is 20 messages/15 mins !!

You can imagine in times when there are multiple fauliures how many message you would get.

I have removed the MessageText from the IAlert to have another class that is responsible for building the message based on the Alert status. The reason for that is the result of this monitoring needs to be displayed differently - for example in IM it needs to be compact and clear ; it doesnt matter much in table storage because its used for analysis and is not read by humans.

Given that:

  1. These alerts can be null , and if they are not they can have a status of New, Continuing or ended.
  2. I am interested in showing services that have at least one alert with status New
  3. I am interested in showing services that have at least one alert with status Ended

What I am trying do is use sort of design pattern/algorithim instead of having nested if else statements that will be turn into spagehetti and will be unefficient to maintain/understand . I have had a look at the interpretor pattern but it doesnt look like it will work here. Any ideas?


Example of monitoring input

ServiceName:CountAlertStatus /AgeAlertSatus / DeltaAlertStatus

  1. service100:N/-/E
  2. Service101:N/N/C
  3. Service102:-/-/-
  4. Service103:C/C/C
  5. Service104:C/E/N
  6. Service105:N/N/N
  7. Service106:E/E/E

(N:new , C: continuring:, E: ended, -:null alert)

Desired output

  • service100 : Count (X) breached and Delta is not breached anymore at {Now}
  • service101 : Count (X) and Age (Y) breached. Delta is still breached (Z) at {Now}
  • Service104 : Delta (X) breached and Age not breached anymore. Count Still breached at {Now}
  • Service105 : Count (X) Age(Y) and Delta (Z) breached at {now}
  • Service106 : Count (X) Age(Y) and Delta (Z) breach ended at {now}

service102 & service103 will NOT show any alerts because they are null / Continuing and therefore we do not care

Factory pattern - build in SQL repository and construct afterward?

I'm working on a web game that has several different types of bricks so I decided to implement the factory pattern. The bricks are stored in a database (must have) and then build using the factory with the properties from the result set.

Factory:

public class BrickBuilder {

public Brick build(String type, int width, int height, String image) {
    Brick brick = null;

    switch (type) {
        case "energy":
            brick = new EnergyBrick(width, height, image);
            break;
        ...

    return brick;
}

Parent class:

public abstract class Brick {

// Properties

public Brick(String type, int width, int height, String image){
    this.type = type;
    this.width = width;
    this.height = height;
    this.image = image;
}

public abstract void construct(double x, double y, int hitCount);

Concrete implementation:

public class EnergyBrick extends Brick {

// Properties

public EnergyBrick(int width, int height, String image) {
    super("energy", width, height, image);
}

@Override
public void construct(int hitCount, double x, double y) {
    this.hitCount = hitCount;
    this.x = x;
    this.y = y;
}

SQL ResultSet to Brick used by getAll, getByName, ... in the repository

private Brick rsToBrick(ResultSet rs) throws SQLException {
    String type = rs.getString("name");
    int width = rs.getInt("width");
    int height = rs.getInt("height");
    String image = rs.getString("image");

    Brick brick = BUILDER.build(type, width, height, image);

    return brick;
}

Generate bricks

private void generateBricks() {
    List<Brick> databaseBricks = BrickRepositorySQL.getInstance().getAll();
    bricks = new ArrayList<>();

    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 14; j++) {
            chance = Math.floor(Math.random() * 5);
            if (chance == 4) {
                continue;
            }
            if (chance == 3 || chance == 2 || chance == 1) {
                // Create new concrete brick with tesame properties as in the array 
                x = j * 140;
                y = i * 80;
                brick.construct(x, y, 1);
                if (chance == 0) {
                    x = j * 140;
                    y = i * 80;
                    // Create new concrete brick with tesame properties as in the array 
                    brick.construct(x, y, 1);
                }
                bricks.add(brick);
            }
        }
    }
}

I have an ArrayList that has all the different types of bricks from the database. I would like to take one of the bricks out of this array, for example the EnergyBrick and then create a new EnergyBrick with the same properties and use the construct method on this brick to set the x and y coordinates with the hitCount.

Things I have tried:

databaseBricks.get(brickIndex) and then use the construct method on this brick, problem is that all the bricks have tesame reference

repository.getByName("energy") works perfectly but takes way too long to query the database for each brick

lundi 27 novembre 2017

UML/Design Pattern: Need help to check my UML for its correctness

the task is:

Photo of the task

I'm new to UML, so I tried hard and I have these answers (look below). How could I improve them? Where do I have mistakes and what should I edit?

Question 1:

Answer1

Question 2a:

Answer2a

Question 2b:

Answer2b

For the third question I'm confused and I don't know how to draw that. Could you give me suggestions?

P.S. For any questions - ask in comments. I will try to answer asap

Appropriate design pattern for choosing between two classes which do not have similar functions

I have 2 classes Workflow1.java and Workflow2.java. At a class Selection.java I want to be able to choose between instantiating one of the 2 classes as a static member however I cannot implement the factory pattern as Workflow1 and Workflow2 cannot be subclasses since their methods are not the same. Although they achieve the same end result they do so by doing entirely different operations. Is there a design pattern for this scenario?

Example: If the classes were WalkHelper.java and DriveHelper.java, the methods you need in each are entirely different but what you are trying to achieve is the same - reach a destination. I haven't created walk() and drive() as methods as WalkHelper.java has existed in our code base and I'm adding DriveHelper.java to it.

How to avoid wrapping code in a promise callback?

In order not to wrap blocks of code in a promise callback (to save one level of indentation), I sometime do the following:

function myFunction() {
    // Create the promise object and get the "resolve" callback
    let promiseResolve = null;
    const promise = new Promise((resolve, reject) => {
        promiseResolve = resolve;
    });

    // Then later in the code:
    setTimeout(() => {
        // Something slow
        promiseResolve();
    }, 1000);

    // And at the end
    return promise
}

It works but it feels a bit messy. Is there any proper pattern to do this in JavaScript?

Regex in php- catching 9 types of numbers out of a string

I just started coding and have a little problem with regex in PHP.

I am trying to catch the following number types out of a string.

000 000 00 00 -
000 000 00 0 -
000 000 00 -
000.000.00.00 -
000.000.00.0 -
000.000.00 -
0000000000 -
000000000 -
00000000 -

And of course the 0 stands for a number between 0-9.

This is the pattern I've tried:

$pattern = "/\d{3}[. ]\d{3}[. ]\d{2}[. ]?\d{1-2}?/";

Something is wrong here, but I don't understand what?

Can you help me?

How to read files that contain a certain number/word in R?

I have a huge number of files and the filenames look like this:

 AL0201A0000500100day.1-1-2011
 AL0201A0000700100dymax.1-1-2011
 AL0201A0000900100day.1-1-2011
 AT0ILL10000400100day.1-1-1997
 AT0HBG10000700500hour8.1-1-1995

And I only want to read the files that contain for example 00007. The files are in different folders and subfolders.

How do I do that? I totally fail to use the * function in R. I know how to do that in Python, but I get nowhere in R. :/

Any suggestions?

Common pattern for temporarily storing data

I am wondering about temporarily saving data. I dont mean to save data on a drive, I refer to a structure in code that saves some data, e.g. user input. Imagine an user runs a programm, enters some text but I cant use it right after that. So I want to store it for later processing. Should be accessible among different classes, but in the same assembly.

What is the common pattern to do so? The only thing I can think of is to use a Singleton class or a static class as a data container but that doesnt feel right.

A general query about django / javascript patterns and how to best organize/encapsualte

I have been warned that this is subjective and likely to be closed, but seems an essential question that I haven't seen addressed.

I am currently coding webapps in django and using a bit of javascript to so this and that. Naturally, I sometimes want my javascript apps from knowing the context of my Django template, so the way I've been doing it is hardcoding the js into the .html file.

Example

<script>
var my_var = 

Clearly this is ugly as all hell as it forces me to keep my javascript code inside of the .html file. I'd like to make my .js file separate and load it.

Clearly thee are some options like write a function that takes arguments that can be captured in the template then passed.

e.g.

var my_var = 
myFunctionFromScript(my_var)

Is this the best way to be doing this? Is there a better pattern? What are others doing?

Thanks for your help.

-Joe

Multi-level counter iteration

I'm stuck on creating an algorithm as follows. I know this shouldn't be too difficult, but I simply can't get my head around it, and can't find the right description of this kind of pattern.

Basically I need a multi-level counter, where when a combination exist in the database, the next value is tried by incrementing from the right.

1 1 1 - Start position. Does this exist in database? YES -> Extract this and go to next
1 1 2 - Does this exist in database? YES -> Extract this and go to next
1 1 3 - Does this exist in database? YES -> Extract this and go to next
1 1 4 - Does this exist in database? NO -> Reset level 1, move to level 2
1 2 1 - Does this exist in database? YES -> Extract this and go to next
1 2 2 - Does this exist in database? NO -> Reset level 2 and 1, move to level 3
2 1 1 - Does this exist in database? YES -> Extract this and go to next
2 1 2 - Does this exist in database? YES -> Extract this and go to next
2 1 3 - Does this exist in database? NO -> Reset level 1 and increment level 2
2 2 1 - Does this exist in database? YES -> Extract this and go to next
2 2 2 - Does this exist in database? YES -> Extract this and go to next
2 2 3 - Does this exist in database? YES -> Extract this and go to next
2 3 1 - Does this exist in database? NO -> Extract this and go to next
3 1 1 - Does this exist in database? NO -> Extract this and go to next
3 2 1 - Does this exist in database? NO -> End, as all increments tried

There could be more than three levels, though.

In practice, each value like 1, 2, etc is actually a $value1, $value2, etc. containing a runtime string being matched against an XML document. So it's not just a case of pulling out every combination already existing in the database.

How to write Beautiful Native Libraries?

I am c++ developer,I am planning to write a library/module in c++ which is used by some set of users/application on Cross platform.

I am learning library/module writing, According to my experience and some reference I have created some set of rules for myself :-

Tools Preference :-

  • To create cross platform library Projects I will prefer to use CMake
  • To do active development I have choose MSVC Compiler and Visual Studio Editor because It has powerful debugging feature.

Code Organization :-

Header Files =>Private(Folder)
             =>Public(Folder)
Source       =>Src(Folder)

Project Organization :-

 XXX_Library => Headers
                Src
 XXX_Test   => Headers
               Src
 Examples   => Src     

Coding Rules :-

  • While exposing an Interface I mainly use C Language to avoid Cross
    Compatibility issues.
  • Use Error Code instead of exception
  • Always use Type-def if using any Third party library
  • While writing an class I will try to Follow SOLID

Those who are experienced in library Writing please share your views that will be extremely useful for me.

such as,

  • any obvious design pattern every Library/Module writer should follow?
  • any Well written open source library to refer ?
  • any Well written book every Library/Module should follow?

Elegant pattern for validating a set of input parameters in java

I'm struggling to find an elegant solution to a validation problem. the problem looks like this.

I have a set of input parameters: p1, p2, p3, p4 (They are received as key value pairs, type Object). Each parameter can have multiple predefined values and only a few combinations are valid. Examples of valid combinations:

  • p1=Va, p2=Vb, p3=V123, P4=Vabc
  • p1=Vb, p2=Vb, p3=V123, P4=Vabc
  • p1=Vc, p2=Vb, p3=V123, P4=Vxyz (where all Values Vxxx are predefined constants)

If the valid combinations would be static, I would create a holder class and create of static collection with all possible combinations of parameters.

But, in some cases one of the parameter could vary, and still be a valid data set. For example: P1 could be predefined constant, or could be some arbitrary numeric ID. In this case a valid set of data would be:

  • p1=[any numeric value], p2=Vn, p3=V123, P4=Vnnn

In this case, how can I validate such set of parameters, in which one could take any value and be valid.

I considered a few options but none I would like: 1. describing matching conditions with classic if else statement. not clear enough. Plus, At some point I need a mapping between my predefined combinations to an output constant. 2. I could have a custom equals method in my holder, but I don't like this approach. More, I'm trying to find a generic approach. What if the number of parameters would increase very much, and the number of variable parameters as well.

PS. I could separate the validation in half and do match first the constant parameters, but please remember that one of them can have either predefined constants either arbitrary numbers

Thank you!

Share request/responses between modules/services

Question

I'm writing monolith application that consists from multiple modules. For the sake of example there are two modules: Module_B depends on Module_A.

To achieve low coupling and make it easier to split my monolith to separate services in future, I arranged communication between Module_B and Module_A through ModuleAClient (see code below).

Should I share some of Module_A's request/response objects or duplicate them inside Module_B?

Share Module_A request/response

In example below I pass com.moduleA.ModuleARequestObject to and return com.moduleA.ComplexGraphResponse from buildGraph method. That mean that com.moduleA.* objects are spread across Module_B's classes. Does it mean higher coupling? If I change ComplexGraphResponse inside Module_A, Module_B will also change it behavior (may be broken).

Duplicate Module_A request/response

In other hand, duplicating some of complex Module_A request/response objects is an extra work and I can't see how it save me from high coupling. If I change ComplexGraphResponse inside Module_A, Module_B will fail to map ComplexGraphResponse to ComplexGraphResponseBDuplicate and will also fail.

Example

package com.moduleB.client;

// QUESTION: should I map moduleA request/response objects to moduleB request/response objects?
import com.moduleA.ComplexGraphResponse;
import com.moduleA.ModuleARequestObject;

//This class is located inside Module_B
@Service
public class ModuleAClient {

    @Resource
    private ServiceA serviceA;

    public ComplexGraphResponse buildGraph(Set<ModuleARequestObject> objects) {
        return serviceA.buildGraph(objects);
    }     
}

P.S.

I have found this question. Is it the same? Do you agree with response?

dimanche 26 novembre 2017

Kotlin - any substitute for companion object inside of another object (not class)?

I would like in my Kotlin Android app to have singleton object with some static definitions of it's inner states.

As I understand, object in Kotlin is for singleton, so I am trying this kind of approach:

object MySingleton
{
    public const val _DEF_DEFINITION_NO_ONE: Byte = 1;
    public const val _DEF_DEFINITION_NO_TWO: Byte = 2;
    (...)
}

This is fine, but the problem is, to being able use these definitions, now I must create Object's instance first.

Just wondering if I am able in Kotlin to create this kind of construction and have access to these definitions without creating MySingleton instance? Answer would be companion object working similar as static in other languages, but it's not allowed inside objects, only inside of classes.

Of course I can leave this as is or make these definitions global, but would like to know is it possible to do in a way I described? Or maybe should I design this in another yet way?

What are some common patterns for updating objects which span multiple rows in a database table?

Consider the following simple example: Assume we have a class 'Account' which contains a list of 'Transactions'. Likewise, in the database we have two tables; 'Account' and 'Transactions'.

Now, in our program, we consider the Account to be the primary object. A typical use case would involve adding new transactions to the Account. These new transactions would then have to be persisted in the database.

With respect to inserting only the new transactions in the database, what are some common patterns for identifying the transactions in the account-object that are actually new?

Obviously, one could do something like "select max(transaction_id) from transaction where account_id = 5", and then insert only the transactions in the object with id greater than max(transaction_id). However, I feel there should be solutions which do not require an additional query.

What is the design pattern for file upload

I got the below question from one of the interview.
In Web application:
Step 1: Upload the file (pdf, txt, excel, doc) through Multi-part component.
Step 2: Server side code receiving the file and validate the uploaded file.
Step 3: After validate the file, it has pass to different system
Please share me your idea, Which design pattern is opt for the above process.

Thanks in advance.

Differences and similarities between bridge and command design patterns?

I want to know the exact Differences and similarities between bridge and command design patterns with real world examples.

The aggregate must know and base its behavior only on its own state? Can the aggregate use the state of other aggregates in its behavior (methods)?

Can the aggregate use the state of other aggregates in its behavior (methods)? Should I inject links to other aggregates, services with access to other aggregates. Or the aggregate must know and base its behavior only on its own state?

Does the DDD community have a clear understanding on the "Aggregate" pattern on this issue? Or this question does not apply to DDD? On the other hand, for example, I've heard a fairly unambiguous view of the community that you do not need to inject a repository to the aggregate.

Where is the boundary between the fact that the operation of the meaning of the aggregate that precedes should not go to the level of services (anemic model), and meanwhile, to reduce the dependence and connectivity of aggregates?

If the aggregate is based only on its state and there are no external dependencies, then it is necessary to make a layer from the domain services? How to call these domain services?

I have an example. I deliberately threw out all the extra to simplify it as much as possible. And left only one operation. In this example, I implemented this approach: 1. Aggregates are independent and satisfy invariants only on its own state. 2. The logic belonging to the domain, but interacting with other aggregates and services is transferred to the domain services.

Описание примера: This is bounded context - auction. Here there are Lot, Bid, Bidder, Timer - which are put or restarted to count down the time before the victory. The operation that is being considered here is "make bid":

  1. Application layer get from client required data, get aggregates, services, repositories. Than call domain service (Domain Service BidMaker -> makeBid) and passes on to that service all that is necessary.
  2. Method of domain service (#Domain Service# BidMaker -> makeBid)

    а) Call method of aggregate (AR Lot -> makeBid), then this method check invariants, then make bid and add it to bidIds.

    b) Checks whether the timers exist in lot, if no start new timers or restarts old timers using the domain service - WinnerTimer.

    c) If timers new - save them using repository

    d) Call method of aggregate (AR Lot -> restartTimers), then this method add timers to winnerTimerId и winnerTimerBefore2HoursId.

I got a duplication of the name of the methods of the domain service and the aggregate. And logically, however, the "make a bid" operation belongs to the Lot aggregate. But then you need to transfer the logic from the BidMaker domain service to the aggregate, which means that you will also need to inject a timer repository and a timer service into the aggregate.

I would like to hear opinions - what would you change in this example and why? And also opinions on the first and main issue. Thanks to everyone.

/*Domain Service*/ BidMaker{
  void makeBid(
    WinnerTimer winnerTimer,
    TimerRepository timerRepository,
    int amount,
    Bidder bidder,
    Lot lot,
  ){
    //call lot.makeBid
    //check Lot's timers and put new or restart existing through WinnerTimer
    //save timers if they new through TimerRepository
    /call lot.restartTimers
  }
}

/*Domain Service*/ WinnerTimer{
  Timer putWinnerTimer(){}
  Timer putWinnerTimerBefore2Hours(){}
  void restartWinnerTimer(Timer timerForRestart){}
  void restartWinnerTimerBefore2Hours(Timer timerForRestart){}
}


/*AR*/ Lot{

  Lot{
    LotId id;
    BidId[] bidIds;
    TimerId winnerTimerId;
    TimerId winnerTimerBefore2HoursId;

    void makeBid(
      int amount,
      BidderId bidder,
      TimerId winnerTimerId,
      TimerId winnerTimerBefore2HoursId
    ){
      //check business invariants of #AR# within the boundaries
      //make Bid and add to bidIds
    }

    void restartTimers(TimerId winnerTimerId, TimerId winnerTimerBefore2Hours){
      //restart timers
    }
  }

  Bid{
    BidId id;
    int amount;
    BidderId bidderId;
  }

}

/*AR*/ Timer{
  Timer{
    TimerId id;
    Date: date;
  }
}

/*AR*/ Bidder{
  Bidder{
    BidderId: id;
  }
}

Generic Repository in Java vs one Repository for each entity when we use Hibernate

What is the best way to create a good code, when you work with Hibernate in Java and you have to decide whether to use in generic repository or one specific repository for each entity.

Firstly I tried to use one generic repository, but I had some problems when I tried to write the name of the class in "Select" clauses and I ended up with one repository for each entity so I know exactly the name of the class.

What are the best practices in this case?

Strategy - automatically register and select strategy by name

I have a lot of actions. All actions works with some Object/Context that passed in all actions. I want to use pattern Strategy/Policy.

interface Action {
    val name: String

    fun run(ctx: Context)
}

class Multiply(): Action {

    override name = "MULTIPLY"

    override fun run(ctx: Context) {
        writeToDb(ctx.id, ctx.number * 2)
    }
}

class Substract 

class SendNotification

etc...

So I want to register all strategies on startup. And select strategy from structure like Enum.

val action = selectAwaitingAction()
val ctx = selectCtxById(action.transaction_id)
perfromAction(ctx, actions.getByName(action.name))

fun performAction(ctx Context, action: Action) {
    action.run(ctx)
}

Is it possible in Java/Kotlin and what pattern should I use?

Design Pattern for Angular 2 and beyond

I am newbie developer and I am learning angular for 3 months now. As part of my learning, i have come to know about OOPS design patterns and I am learning them slowly, day by day.
During the process of learning angular and getting my head around Component architecture and use of Rxjs library which heavily rely on Observer pattern. I am just completely overwhelmed by the things I have to learn Rxjs, Reactive Programming, Functional Programming, thinking in component architecture.
I tried to find out design patterns for angular in order to understand the basic concepts for creating a good system design for the angular application but couldn't find any.
Now all I want from you guys as an angular developer, who has wrapped his head around the concepts of angular is in terms of data bindings, routing, and all the syntax part and wanting to take the next step.
How to be a good developer in Angular, so that I can help my team in designing angular application the way it should be designed harnessing the reactive paradigm, component architecture. I am not sure about the title of my question and I will change it if you can suggest me some meaningful and expressive title to convey the info.

SPA pattern to support multiple backend versions

We have a Single Page Application SPA with Angular 5 and Spring Rest Backend.

the application is distributed and hosted by many customers each of them has a specific minor version of the software.

The Backend has not changed much in recent years, a breaking change every 2 month or so.

Now the problem we face, is that the client is evolving very fast but upgrading the backend is very expansive for the customer so we would like to install the client independent of the backend version. We would need to support multiple backend versions, what is a good approach to do that?

The idea is to use a list of adapters one for each minor version. Are there better approaches?

What is the right way to handle belongs_to relationships in Rails controllers?

Say, for example, that I have 2 resources Author and Book, where Author has_many Books and Book belongs_to Author.

This means that by doing the following:

# routes.rb

resources :books
resources :authors do
  resources :books
end

I will have two routes that point to BooksController#index: 1) GET /books and 2) GET /authors/:id/books.

Consider the scenario where we don't care about all the books, only the list of books from a given author (effectively putting route #1 out of use).

This leaves BooksController#index with logic that goes something like:

# BooksController.rb

def index
  @books = Book.where(author: author)
  render json: @books
end

However, the Author scoping is leaving me quite uncomfortable seeing as it is a general BooksController, where the other CRUD methods have nothing to do with Authors. Should something like the above #index method be in a separate, namespaced controller like Author::BooksController?

How to manage Login Session variables in MVC

I have search the web including SO but couldn't find the best solution to the problem. I have taken over a MVC project which has around 15 controllers and each controller class starts with these 2 lines:

int userid = (int)System.Web.HttpContext.Current.Session["UserID"]; string usertype = (string)System.Web.HttpContext.Current.Session["UserType"];

Code Snapshot

These 2 variables (userid,usertype) are then used throught the controller action methods.

What would be the best way of avoiding this? The 2 options that I found were either creating a SessionEndAttribute class and add it to each controller OR create a base controller class with the session check and make all controller classes inherit from the BaseController class.

samedi 25 novembre 2017

What's the best design for extra data on behaviour class?

I have a game where the player can finish some tasks.

I have separated the behaviour part of the task to its ORM part. Eventually a copy of the task is being saved somewhere on the player's document (doesn't matter where for this specific question).

The problem is, I am not sure where to put the extra information that I send to the client that is not necessary for the behaviour itself, but it is needed to show the player information regarding the task itself.

This is my task interface:

interface ITask
{
    /**
     * @param Player $player
     */
    public function init(Player $player);

    /**
     * @param PlayerAction $action
     */
    public function progress(PlayerAction $action);

    public function reset();

    /**
     * @return bool
     */
    public function isComplete();
}

This is my abstract task:

abstract class BaseTask implements ITask
{
    /**
     * @var int
     */
    public $id;

    /**
     * @var int
     */
    protected $currentValue;

    /**
     * @var int
     */
    protected $targetValue;

    public function __construct($targetValue)
    {
        $this->currentValue = 0;
        $this->targetValue = $targetValue;
    }

    /**
     * @param int
     */
    public abstract function setCurrentValue($current);

    /**
     * @return  int
     */
    public abstract function getCurrentValue();

    /**
     * @return int
     */
    public abstract function getID();

    /**
     * @param int
     */
    public abstract function setID($id);

    /**
     * @return int
     */
    public abstract function getTargetValue();

    /**
     * @param int
     */
    public abstract function setTargetValue($target);

    /**
     * @return boolean
     */
    public function isComplete()
    {
        if ($this->getCurrentValue() >= $this->getTargetValue())
        {
            return true;
        }

        return false;
    }
}

Now I need to decide how where to put the extra data, e.g description, title, theme etc...

  1. I thought about two options: I can just put it on the base task itself, but then what happens if I don't need it? I just leave it blank? feel like the wrong place for me.
  2. I could create a wrapper class that will hold the task, but then I will need to always call the wrapper to get to the task, and it feels kind of wrong.

Looking for alternative suggestions.

why MVC and singleton both are "design pattern"?

Every literature that is searched said that "MVC - is a design pattern assigns..." and the same such pattern as Singleton describes as "a software design pattern".

But WHY? This is different things that specify concepts on different levels of developing. In one MVC project you can have few Singleton, Factory and Unit of Work for example. But MVC and all this patterns still will be called "design patterns".

Best design method to allow user to change a class method - Delegates/Inheritance/Interface?

I'm writing class Movies that, for simplicity sake, is responsible adding/removing/keeping a set of movies. Movie instance has many params such as length, color, genre, etc. Movies should also allow a user to call Movie bestMovie() which will return 'the best' movie in the set.

Assuming that I already have two ways of choosing a best movie implemented (one based on highest IMDB ranking, the other on Rotten Tomatoes) but I want to allow the user to add new types of decision algorithms (e.g. based on length + season of the year) for example. What is the best design to allow this?

Thoughts that I had:

  1. Allow the user to inherit from Movies and override bestMovie(). Feels like a wrong usage of inheritance.
  2. Create an interface called MovieSelection and implement class IMDBMovieSelection. The user can then add class SeasonMovieSelection. Movies Ctor will then get MovieSelection as param which it will use in bestMovie() - It feels wrong to create objects just for "signaling" a method to my main object
  3. Use delegates/anonymous functions when calling bestMovie(<anonymous function>) (similar to what I would use with List.Sort(IComparable)) - Feels not scalable and hard to maintain, especially if the function is a complicated one.
  4. Provide ability to extend the class using a partial class - not even sure if that's a real option

Would appreciate any insights here. I'm sure I'm not the first one to face this issue, but didn't know what exactly to search for.

Thanks

How to implement the Template design patter?

I have this exercise that I need to refactor using Template design pattern. I have seen a basic explanation of how it works, but I can't get a clear idea of how I should implement my solution. Could anyone help me out? What would be the logic in this case?

I have this BodyFatCalculator class:

package bodyfat;

public class BodyFatCalculator {

public double calculate( BodyMeassures body, boolean isWoman ) {
double fatPercent = 0;
if( isWoman ) {
  fatPercent = Math.log( body.getWaist() + body.getHip() ) - body.getWeight()
                                                             * Math.log( body.getHeight() );
}
else {
  fatPercent = Math.log( body.getWaist() + body.getAbdomen() ) - body.getWeight() * Math.
          log( body.getHeight() );
}
return fatPercent;
}  
}

And I also have this BodyMeassures class:

package bodyfat;

public class BodyMeasures {

private double height;
private double waist;
private double weight;
private double hip;
private double abdomen;

public BodyMeasures( double height, double waist, double weight, double hip, double abdomen ) {
this.height = height;
this.waist = waist;
this.weight = weight;
this.hip = hip;
this.abdomen = abdomen;
}

/**
* @return the height
*/
public double getHeight() {
   return height;
}

/**
* @return the waist
*/
public double getWaist() {
   return waist;
}

/**
* @return the weight
*/
public double getWeight() {
   return weight;
}

/**
* @return the hip
*/
public double getHip() {
   return hip;
}

/**
* @return the abdomen
*/
public double getAbdomen() {
   return abdomen;
}

}

Modeling payment transaction system

I need to create (payment) transaction system. Transactions contains some actions/steps, some actions depends on another, but some can performs in parallel.

Synthetic example:

Transaction: 
    1. get confirmation
    2. get balance
    3. check in fraud system (can be in parallel with 1 & 2 step)
    4. hold (depends on 1 & 2)
    5. make request to payment provider (depends on 3 & 4)
    6. finish (depends on 5)

In this example we have few steps that can perform in parallel and some steps that depends and wait for other action. I plan to store actions in database with references to dependencies (steps that should be performed before).

I plan to use some kind of status model for states of actions like WAITING, READY etc. (Actually examples of status models another good question) And also I want to make some structure to work with (biggest problem).

At first I plan to use tree, where top of tree is FINISH and all operations execute from leaves to top, but I have some different actions that can depends on same leaf (I mean different leaves that have link to the same leaf(action) below) and I thinking about using some kind of graph.

I'm in search for good examples, references and practices, books about writing this kind of software.

graphics.py pattern calculation to flip coordinates

I am using graphics.py to create a pattern that will then be used as part of a tiling system to populate a window. The following code works, however, when X and Y are different values, one side of the pattern diverges. I have tried variants of this calculation and can't get it to work:

def drawLine(window, x1, y1, x2, y2, colour):
    line = g.Line(g.Point(x1, y1), g.Point(x2, y2)).draw(window)
    line.setFill(colour)

def draw_Patch_Final(window, pos_x, pos_y, colour):
    x = pos_x
    y = pos_y
    print(x, y)

    while x < pos_x + 100 and y < pos_y + 100:
        print(pos_y, x, (2 * pos_y) + 100 + x, pos_x + 100)

        # TODO Flip Coordinates for reverted pattern
        # If X and Y are different values, pattern diverges
        drawLine(window, pos_y, x, (2 * pos_y) + 100 - x, pos_x + 100, 
colour)
        drawLine(window, y, pos_x, pos_y + 100, (2 * pos_x) + 100 - x, 
colour)

        drawLine(window, y, pos_x, pos_y, x, colour)
        drawLine(window, pos_y + 100, x, y, pos_x + 100, colour)
        x += 20
    y += 20

This produces:

enter image description here

With the code calls of:

draw_Patch_Final(window, 50, 50, "Red")
draw_Patch_Final(window, 180, 180, "Black")
draw_Patch_Final(window, 300, 250, "Green")

As the green patch's x and y values are different it hinders me from calling the pattern at any given grid location. Any fixes for different X and Y values? The pattern draws in the correct location but wrong dimensions.

Calling a method of a different object without breaking encapsulation

I have an object GameLogic which has a Player (interface) object.

GameLogic has a method getAvailableMoves() which is used inside GameLogic to let Player know about his available moves.

I'm currently implementing an AIPlayer (implements Player) which should use the Minimax algorithm as a strategy. For that to happen, I want to be able to use GameLogic's getAvailableMoves() method from inside AIPlayer. However, I'd like to do that without breaking encapsulation. That is to say that I'm trying to avoid passing GameLogic as a reference to Player.

What is the appropriate solution for this scenario? I assume I should use a Design Pattern but I'm not sure which.

CSS Rotate depending on width / fixed pixel value

TLDR: i want to achive this as scalable solution: triangle with gradient and pattern

Longer explanation: Target is to have a rotated div with a gradient as background. But the problem is that the rotation cant be defined as deg because it varies depending on the browser-width. So the element should be 100% width of the browser with a fixed height on the left and a fixed lower height on the right side.

Basically this can be done easily with an image-background which stretches only horizontally. Only problem is that there should be also a pattern overlay which should be clipped on the same area and this should repeat and not stretch (as you can see these pattern consists of equal boxes)

So my idea was: Is it possible to rotate an element for specific target pixels?

Current Example:

.triangleClipper {
  height: 100px;
  overflow: hidden;
}

.designElement {
  background: linear-gradient(to right, #03cc65, #fbfe02); 
  height: 100px;
  width: 200%;
  transform-origin: top left;
  transform: rotate(-2deg);
  margin-top: -60px;
}

http://ift.tt/2zoXCtd You see the problem on the right edge when resizing the browser. So on width screens you see the end of the triangle and small screens it is too high. Target is to remain same heights on left and right edges on every browser size.

Any other ideas are welcome.

Entity Framework, Repository Pattern and 2 DBs

I am working on an app that works with 2 DBs. I want to use EF, Repository and UnitOfWork Pattern. I am learning clean code principles and design patterns, so want to have some feedback,since although I (think) understand the main ideas, I'm struggling a bit in the implementation. I have readed a lot of answers and articles but still not being able to bring the ideas to my specific problems completely.

I have 2 DBs.

  1. Legacy-DB of our ERP-System. Only Read-access (aka ERP-DB). From this DB I have to take all the Info I need.
  2. Project-DB. Needs to be created and for it I have no restrictions. (aka Project-DB)

So first if I understood it right for the ERP-DB I should use the DBFirst Approach since I can't modify the DB and for the Project DB I could use anyone, being CodeFirst maybe the best approach (Since I am trying to do DDD) so I can first design my domain model and then define what will be persisted.

Now 1 question:

  • The ERP-DB is very "generic" and has for example a table "articles". Here you find any type of article we have, from complete build devices to assembly pieces. So with DBFirst the EF generates for it an entity called "Articles". But I don't want to use such a class in my domain model, I would like better classes like transmitter, termometer, measureCell etc. They are "specific" articles. So I need to map Articles to the different domain objects.

    • Do I need to do it manualy or can EF does it for me in DBFirst?
    • If manually, should I create a Repository for each domain object and put the map logic in it? Or should I create 2 Repositories, 1 for data entities and 1 for domain objects and then where to put the map logic?
    • Some specific articles contains more than one article, i.e. a transmitter has a measureCell, both entities are in the same articles table. So here should my TransmitterRepository have a method, that knows how to retrieve a transmitter or where should I put this logic?

Now, regarding the project-DB, I could use CodeFirst to focus on my domain model and define what needs to be persisted. So if I choose this approach and understand it right I could map here directly my data entities to my domain objects. But I dont understand it completely since for me I am just putting the same logic somewehere else, instead of having it in the repos I have it directly in my objects, but what do I "win" there?

Moving a circle on a map using Observer pattern

I have a (probably an easy) problem with my java program. I'm trying to create a circle that will move from one place to another. The map is a part of an easy dialogue game that says "go here" and the map should react to it. It has to be using an Observer design pattern.

So far I have the map in the game implemented but I just can't fathom how to make the circle function as it should, while using Observer, too. Thanks for any help

package GUI;

import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Paint;
import javafx.scene.shape.Circle;
import logika.Game;
import logika.IGame;
import main.Main;
import utils.Observer;


public class Mapa extends AnchorPane implements Observer{

    private IGame game;
    private Circle dot;
    //private double posTop = 0.0;
    //private double posLeft = 0.0;

    public Mapa(IGame game){
            this.game = game;
            game.getGamePlan().registerObserver(this);
            init();
    }

    private void init(){

        ImageView obrazekImageView = new ImageView(new Image(Main.class.getResourceAsStream("/zdroje/mapa.gif"),255,255,false,true));

        tecka = new Circle(10, Paint.valueOf("red"));

       //this.setTopAnchor(tecka, 15.0);
       //this.setLeftAnchor(tecka, 20.0);

        this.getChildren().addAll(obrazekImageView, dot);
        update();
    }

    public void newGame(IGame newGame){
        game.getGamePlan().removeObserver(this);
        game= newGame;
        game.getGamePlan().registerObserver(this);
        update();

    }

    @Override
    public void update(){
        this.setTopAnchor(this, game.getGamePlan().getCurrentPlace().getPosTop());
        this.setLeftAnchor(this, game.getGamePlan().getCurrentPlace().getPosLeft());
    }
}

Calculate and Control customer credit and update it

I have a financial system and I have to design a module for save, update and control limitation. You can know each customer has a UserID and each UserID has a maximum amount of credit per day. For example, UserID = 12 has MaxAmountPerDay = 10$ and CurrentAmountPerDay.

At first, I wanted to design a simple module and define a table as follows:

  User ID | MaxAmountPerDay | CurrentAmountPerDay
-------------------------------------------------
  12     | 10              | 0
  25     | 100             | 84

Now you can imagine when the customer with UserID = 12 has done a transaction I have to control if the transaction amount + current amount > max amount then throw an exception else I have to do the transaction and update current amount and when an exception happened after updating I have to rollback the update operation.(update and rollback are in different database transactions so the rollback is the same update with new amount)

Before I do this design I decided to look up for a better solution or even an open source framework for doing that because I guess my customer's requirements will change in future, for example maybe they will need to MaxAmountPerMonth, or some more requirements which I don't know now.

Find entire row in R data frame?

I have a large dataframe df with 10 columns.

For example:

col1 col2 col3 col4 col5 col6 ......
a    22   13   dd   kuku ppp
q    123  444  dff  pupu sds

I get a new record rec1 with the same structure (10 columns):

rec1 <-  col1 col2 col3 col4 col5 col6 ......
         a    22   13   dd   kuku ppp

I want to search df and return true/false if I have found this row or not. Please advise how to do this? Dplyr filter?

vendredi 24 novembre 2017

Polymorphism vs Abstraction : Is polymorphism one of the way to achieve Abstraction?

My understanding of a Polymorphism is, it is one of the way of achieving Abstraction ? Does every one agree with my view ? Or there is any flaw in my thinking ?

How to make String pattern using 2D arrays?

  1. Greetings stack overflow today i have a question about programming and I was making this program but what printed out it didn't what I have expected I was testing this program for a while and coding it but I just can't come up with something to make the right shape please help... This is the cod that I have been working on I want to make it with for loops and 2D arrays like a matrix with Strings but it just not working for me... I been trying to print out the first word HELLO but nothing it just printed HELLO E L L E L HELLO in a single line of code Need to print out is:

    HELLO E L L E L HELLO

    public class fancy_word
           {
    
    public static void main (String [] args)
    
      {
        //first a String 2d array using method 3
        String PO[][] = 
            {
    
            {"HELLO"},
            {"E L"},
             {"L"},
            {"E L"},
           {"HELLO"}
        };
        /*String VIP [][] = 
        {
              {"CAT","A","CAT"}
        };
        String COD[][] = 
        {
              {"A"}
        };
        String U_45 [][] = 
        {
             {"DOGHOUSE","O    S","G  U","HO","HO","G  U","O    S","DOGHOUSE"}
        };
        String UI_98 [][] = 
        {
             {"ONE","N","ONE"}
        };
        String HKL_001 [][] = 
        {
            {"IT","IT"}
        };
        */
       //Nested loop within math and if statements declaring 
        for(int i = 0;i<PO.length;i++)
        {
           for(int LED = 0;LED<PO[i].length;LED++)
           {
               System.out.print(PO[i][LED]+" ");   
           }
        }
        System.out.println();
    }
    
    

    }

Java design pattern - class to represent a variable for interpreter

Please share your best practice, how is it better to make a class to store variables of different types? For example, there are 4 types of data that can be stored in the variable: int, float, boolean and string. And I'd like to make a class to store any of these types. What is better? To make a simple class that will hold any of these as an Object and will keep the type separately? Or just store the Object and use it's real type? Or to make a base class and then to make subclasses for each type? How to make a getter for the value in both cases? Just return Object that will have a real type of that variable? I don't like both methods because the access to the data is quite complicated - calling foo shall implement some logic to understand what is the real type there. But I cannot find any other. Please share your experience how it's usually done in Java? The area is - small interpreter or data exchange with the database. In other words, to keep data of different kind which real type will be known just in run time, and to process it.

Factory Method pattern vs ordinary abstract class implementation

I'm trying to understand the Factory Method pattern. I've managed to distinguish it from the Simple Factory, but now I don't get why it's actually called a "pattern". Please, look at my example below:

Class Diagram link

Sample java code for Messenger:

public String exchangeMessages(String messageToSend) {
   Socket socket = getSocket();
   socket.open();
   socket.send(messageToSend);
   String receivedMessage = socket.receive();
   socket.close();
   return receivedMessage;
}

And for Client:

public static void main(String[] args) {
   Messenger messenger = new TCPMessenger("127.0.0.1", 4321);
   String result = messenger.exchangeMessages("Hello!");
   System.out.println(result);
}

If I understand correctly, everything makes sense because exchangeMessages method exists. We use the abstract factory method getSocket inside it and thanks to it we:

let subclasses decide which class to instantiate

But isn't it just an ordinary abstract class implementation? We take advantage of the code shared by both TCPMessenger and UDPMessenger - for me, this is not a pattern but a core feature of Object-Oriented Programming that everybody knows from the beggining of OOP language learning!

Moreover, I think that naming this creational is very confusing. We actually care about exchangeMessages method, so Client (part of the code that uses our "pattern") is not even aware of the Socket class which creation we're all about. It's more like a way to implement Messenger functionallity (which can be easily extended etc...) than a way to really create something.

Am I missing the point or is my example invalid? Please guys, let me know what do you thing about it.

Thanks in advance!

Accessing outer object from the nested one

Question about C++ standard and appropriate design pattern

I have an object which has several non-POD objects as members, and from within those objects I need to access the outer one.

For example it can be an object which "listens" to several different events, whereas listening means implementing some interface. You can't just inherit this interface directly by your main class, because you can't inherit the same base class multiple times. But even if you could - you may want to avoid this, since you don't want to expose this interface, it's just implementation details of your object.

I mean something like this:

class MyClass
{
    // ...
    struct Listener1 :public IEventListener {
        virtual void OnEvent() { /* need to access MyClass */ }
    } m_Evt1;

    struct Listener2 :public IEventListener {
        virtual void OnEvent() { /* need to access MyClass */ }
    } m_Evt2;
};

One obvious way to give access to the outer class is to have a member of pointer/reference to it in every inner object. But this requires writing some code (initialization of the pointer/reference), and compilers don't like when you use this in base member initialization, plus there's an actual code generated for this and object layout is inflated in memory.

There is also another possibility: using offsetof-like trick. The memory offset of the inner object wrt outer class is known at compile-time. Hence vice-versa also holds, i.e. we can subtract that offset from this of the inner object to get the pointer to the outer class. Wrap it with nice C++ accessor method and - voila.

#define IMPLEMENT_GET_PARENT_OBJ(parent_class, this_var) \
parent_class& get_ParentObj() { return * (parent_class*) (((PBYTE) this) + 1 - (PBYTE) (&((parent_class*) 1)->this_var)); }

class MyClass
{
    // ...
    struct Listener1 :public IEventListener {
        IMPLEMENT_GET_PARENT_OBJ(MyClass, m_Evt1)
        virtual void OnEvent() { get_ParentObj().OnEvent1(); }
    } m_Evt1;

    struct Listener2 :public IEventListener {
        IMPLEMENT_GET_PARENT_OBJ(MyClass, m_Evt2)
        virtual void OnEvent() { get_ParentObj().OnEvent2(); }
    } m_Evt2;

    void OnEvent1();
    void OnEvent2();
};

One can argue that if you declare such objects of inner type outside of the MyClass - then obviously the get_ParentObj() is broken, and you get the undefined behavior. Also you may technically get the reference to the outer class from the c'tor of the inner one, and invoke its methods even before it's constructed.

I know there are zillions of ways to solve this and make it fool-proof, such as creating inner objects dynamically and giving them a weak reference to the outer class, and etc. But this is an overkill in my scenario. Assuming you don't shoot yourself in the foot on purpose there seems to be no problem. And speaking practically it just works, without any memory waste or unneeded extra code.

Is it considered a good practice? And if not - why?

How does singleton class Work and Idea behind it? [on hold]

Here my code:

  private static JavaClass INSTANCE = null;

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

private JavaClass() {
        }

What is the use of this pattern and how does it work?

Private Variables in Module Pattern

I am not clear about the concept of private, if I can still access it through the public method and redefine the properties of the module. I mean, I can perfectly do:

var aModule = (function() {

    var privateVar = 1;

    return {
        publicFunction: function() {
            return privateVar;
        }
    }

})();

aModule.publicFunction = function() {
    privateVar = function() {
        console.log('a new content');
    }
    privateVar();
};

aModule.publicFunction(); // 'a new content'

I understand that this is not possible if I write it in ES6 with let or const, because it would give me error try to overwrite the value of the private variable, but what sense does it have in ES5?

How to redesign java application to provide another copy of variable in the new thread?

I'm writing socket client-server console application. I want to enable standart user input on the server and at the same time to communicate with clients. To achieve this all system.out.println, and scanner.scan, I've replaced with interfaces IScanner, IPrinter and implement them with CLIScanner/Printer and SocketReader/Printer.

All CLI actions are in classes that extends BaseDialog, which use one of IScanner/Printer implementations. Here the code of BaseDialog.

public abstract class BaseDialog {
    public static IPrinter printer;
    public static IScanner scanner;

    static {
        printer = CommunicationProvider.printer;
        scanner = CommunicationProvider.scanner;
    }

    public BaseDialog() {

    }

    public BaseDialog(IPrinter printer, IScanner scanner) {
        this.printer = printer;
        this.scanner = scanner;
    }

    public static void done() {
        printer.println("Done.");
    }

    public static void printOnExit() {
        printer.println("Shutting down...");
        printer.println("Finish");
    }

    public static void startMessage() {
        printer.println("Application has started");
    }
}

I have some classes that are extends BaseDialog and here is example.

public class HelpDialog extends BaseDialog {
    public static void printCommands(String[] commands) {
        for(String command : commands) {
            printer.println("\t " + command);
        }
    }

    public static void commandsBelongs(String owner) {
        printer.println("Commands for " + owner);
    }
}

All printer methods are static as well as IPrinter and IScanner instances.

Idea to use multithreading - each thread will use own printer or scanner, so this is code of the main start up class:

public class Main {
    final int portNumber = 3000;
    public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchAlgorithmException, IOException, InstantiationException, NoSuchMethodException, NoSuchFieldException {
        BaseDialog.startMessage();

        new CommandParser().Run();
    }

    private void startServer() throws IOException {
        ServerSocket serverSocket = new ServerSocket(portNumber);
        while(true) {
            Socket connectionSocket = serverSocket.accept();
            PrintWriter printWriter = new PrintWriter(connectionSocket.getOutputStream());
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            Thread thread = new Thread(() -> {
                BaseDialog.scanner = new SocketReader(bufferedReader);
                BaseDialog.printer = new SocketWriter(printWriter);
                try {
                    new CommandParser().Run();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
            });
            thread.start();
        }

    }
}

The problem is here

 BaseDialog.scanner = new SocketReader(bufferedReader);
 BaseDialog.printer = new SocketWriter(printWriter);

All threads use the same instance of scanner and printer, but I need for each thread their own instances scanner and printer. Because each scanner and printer work with different clients.

I've thought about declaring dialog classes as fields of classes that use them, but there are too many classes that use dialogs. I really don't wont to support this solution and prefer to the provide instances globally.

How to redesign application to provide for each thread own instances of printer and scanner?

Is there a common pattern to replace In Memory Datastores in a running application?

Let's say you have an application and this application is not using a common database, but a loads all the data in-memory and it works all from there.

Now, this is a WS and every few hours you want to 'update' your in-memory database. Since you don't want to risk an downtime and just want to replace the in-memory datastore on the fly. But there could be certain risk coming with that:

  • Certain data, which were available in the 'old' datastore might not be there anymore and if someone is consuming your data right in that moment, they will end up with an error.
  • Certain data could change and might just not be named the same or just slightly different.

I was just wondering if there is a certain approach or pattern for this kind of problem?

My approach would be to have for a certain time two datastores. The 'old' and the 'new' one. All new session get served by the new datastore and all old session will use the old datastore and might be forced to refresh to use the new one at some point. After that, I would throw the old one away and start the same song again.

How to handle a c++ project configuration?

We have a c++ code stack, that we need to share across two different projects, need to specialise at compile time for either of the projects.

The stack has a set of core functionality which will be common across two projects. For project specific code, we can think of 1. Set of features which have common implementation but optional between projects 2. Some features might have different implementation across the projects

Either case, core functionality should be able to plugin the project specific code.

We are thinking of having libraries for point 1, and macros for point 2. Is there any cleaner precedent or constructs that we could follow in this case?

Use of union in a command data structure

I am working on a project in which we pass commands to lower layer from upper layer.

1. Handle Single command at a time

we use following data structure.

struct Command{
     //Different command types==> SEND / CREATE_TRANSACTION etc.
     CommandType type;

     //Associated parameters with every command
     union{
         struct{
             string remote_ip;
             uint16_t remote_port;
         }address;

         struct{
             string transaction_id;
             string transaction_details;
         }tsx;
         .
         .
         .
     }params;
};

We pass different parameters for different commands. Union makes it memory efficient.

Is there any better way (or a design pattern) to do it in C++?

Another one.

2. Handle multiple commands in a single command object.

I can do it in this way:

struct Command{
    uint64_t flag; //ORed value of different command types 

    //parameters
    struct{
        string remote_ip;
        uint16_t remote_port;
    }address;

    struct{
        string transaction_id;
        string transaction details;
    }tsx;
};

But, it is not memory efficient.

Is there any better way to create multiple commands in a single object (in C++)?

Best practices to call model methods in java servlet

I am working in a java web base application. I have created a package for my model classes. Right now, I am calling the methods of these model classes from the servlet, but I wanted to make separate classes for each of my model class in which I can write my business logic, because by doing this my code will be more manageable. I do not know what are the best practices for this, and secondly I know there is a mvc software architectural pattern. I am wondering that is there any design pattern which I can follow for my application ?

Restrict access to a specific assembly c#

I'm working on a Winforms project with sql server, splitted in several assemblies.

The first assembly Entities contains DTO like :

public class Attribution
{
    public short UserId { get; set; }
    public User User { get; set; }
}
public class User
{
    public short Id { get; set; }
}

The second assembly Repository is accessing Sql Server database.

The third assembly Service is the link between previous.

There are other layers but this is not the point. I need of course DTO's everywhere in the app.

In sql server, Attribution.UserId and User.Id are the same datas, located in 2 separate tables, linked by Ìnner join.

Attribution.UserId must be public because I need access from Repository,Service, etc... But I don't need it in the "logical" part of the app, what I need is Attribution.User.

At this time I have a UserService class in which there is a GetUser() method and I call this method to get the user in my AttributionService.GetAttribution() method.

Is there a way to restrict access to Attribution.UserId property to Service assembly? Or is it a kind of "good practice violation" to query a User DTO in AttributionService class?

Many thanks for your recommandation.

`

jeudi 23 novembre 2017

Factory pattern with generics in java

I'm having trouble implementing factory with generics for a specific use case

I have model classes:

class BaseModel { }

class ModelA extends BaseModel { }

class ModelB extends BaseModel { }

And corresponding services:

class Service<T extends BaseModel> { }

class ServiceA extends Service<ModelA> {}

class ServiceB extends Service<ModelB> {}

My Factory class, to create service according to the model it services:

class Factory {
    private Map<Class<? extends BaseModel>, Class<? extends Service>> registry;

    Factory(){
        registry = new HashMap<>();
        registry.put(ModelA.class, ServiceA.class);
        registry.put(ModelB.class, ServiceB.class);
    }

    Service getService(Class<? extends BaseModel> clazz) throws IllegalAccessException, InstantiationException {
        return registry.get(clazz).newInstance();
    }
}

And a class that uses the factory

class Handler<T extends BaseModel>{
    private Service<T> myService;

    Handler(Class<T> modelClass) {
        Factory fact = new Factory();
        try {
            myService = fact.getService(modelClass);
        } catch (IllegalAccessException | InstantiationException e) {
            e.printStackTrace();
        }
    }
}

I get an warning for the line that uses the factory to get the service:

"Unchecked assignment 'Service' to 'Service<T>'"

I understand why I get the message, since the getService method returns Service, but I need Service<T> and puzzled about how I can change the code to get Service<T>

Any suggestions?

Thanks!