mercredi 31 mai 2017

How to count a type "object" selected at runtime

I need to count a specific Object, but I'll know which object only at runtime. Right now I have something like

public class Details {
    private String typeOfObjectRequired;
    private int numberOfObjectRequired;
}

And in another class I have

public class Container {
    private List<Type1> type1List;
    private List<Type2> type2List;
    private Type3 type3Object;

    public int countType1() {
        return type1List.size();
    }

    public int countType2() {
        return type2List.size();
    }

    public int countType3() {
        return type3Object.getNumberOfSomething();
    }

}

Now I'm doing like this (in a third class that has both Details and Container as attributes)

public boolean hasNumberOfObjectRequired() {
    int count = 0;
    String type = details.getTypeOfObjectRequired();

    if(type == "type1") count = container.countType1();
    else if (type == "type2") count = container.countType2();
    else if (type == "type3") count = container.countType3();

    if (count > details.getNumberOfObJectRequired) return true;
    return false;
}

Is there a better way to do this? I don't like to have so many if, also because I have more than just 3 different types.

How to design a file container in C++?

My plan is to build a fileContainer that consists mainly of a std::map that associate specific files to an ID. Each file has for attributes a ofstream, a path (string) and a few other information.

The problem is that an ofstream cannot be copied (Why copying stringstream is not allowed?) and cannot even be moved (Why can't std::ostream be moved?). One can therefore not create file objects to then insert them into the map of the fileContainer.

What I am trying to do is something like

file f(arguments...); // create a `file`
FC.insert(f);         // Note the FC is a global singleton of class `fileContainer`
...
{
   file& f = FC.getFile(fileID); // find a specific file in the file container
   f.open();
   f.write(s1);
   f.write(s2);
   f.write(s3);
   f.close();
}

I fail to see how such functionality could be achieved without having to copy or move a stream. Can you help me out to build this type of functionality?

Module pattern, what do I do wrong?

I want to use module pattern on this simple application, where you can search for countries, and some cities show up. I have read about module pattern, and it seems like its a usefull thing to learn.

I need some help with the syntax. I have written in what I thought was correct, but it did not work so I commented it out, can someone try to explain to me how to use it in my own example, its easier for me to understand. You can see the code that I tried it with under.

The "searchElements" and "getAllElements" are the functions that I want to have in the module file, together with the JSON objects.

http://ift.tt/2seRpNe

// var search_elements = (function(){

var searchElements = 
document.getElementById("btn").addEventListener("click", (e) => {
container.innerHTML = "";
e.preventDefault();
var innerDiv = document.getElementsByTagName("div");
var input = document.getElementById("input").value;

for(var i = 0; i < arrayList.length; i += 1) {
    target = arrayList[i].land.toLowerCase();

    if(input.toLowerCase() === target.toLowerCase()) {
        var newCard = document.createElement("div");
        var landElement = document.createElement("P");
        var landContent = document.createTextNode(arrayList[i].land);
        landElement.appendChild(landContent);
        var byElement = document.createElement("h3");
        var byContent = document.createTextNode(arrayList[i].by);
        byElement.appendChild(byContent);
        var img = document.createElement("img");
        img.setAttribute("src", arrayList[i].img);
        newCard.appendChild(img);
        newCard.appendChild(landElement);
        newCard.appendChild(byElement);
        container.appendChild(newCard);
    } else {
        continue;
    }
}

return {
  searchElements: searchElements
 }
});


// var get_all = (function(){

var getAllElements = 
document.getElementById("btnTwo").addEventListener("click", (e) => {
container.innerHTML = "";
e.preventDefault();
var innerDiv = document.getElementsByTagName("div");

for(var getAll = 0; getAll < arrayList.length; getAll += 1){
    var newCard = document.createElement("div");
    var landElement = document.createElement("P");
    var landContent = document.createTextNode(arrayList[getAll].land);
    landElement.appendChild(landContent);
    var byElement = document.createElement("h3");
    var byContent = document.createTextNode(arrayList[getAll].by);
    byElement.appendChild(byContent);
    var img = document.createElement("img");
    img.setAttribute("src", arrayList[getAll].img);
    newCard.appendChild(img);
    newCard.appendChild(landElement);
    newCard.appendChild(byElement);
    container.appendChild(newCard);
}

return {
  getAllElements: getAllElements
}
});

Algorithm - How to draw a non-perfect diagonal in a pixelated space?

I'm programming this for my class

enter image description here

Is a group of squares and I need to paint its with different shapes.

But I don't know how to draw a diagonal just by passing 2 coordinates (x1,y1)(x2,y2)

Does anybody know an algorithm/pseudo-code for this?

P.S. I'm using typescript

Executing Method/Code based on run-time object type

I have this situation:

I have an abstract class, let's say A, implemented several times. In another part of the application, I have a list of A objects, and I have several operations that needed to be done based on the actual type of the object in the list. As an example

/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

abstract class A{
    abstract void op();
}

class B extends A{
    void op(){
        System.out.println("b");
    }
}

class C extends A{
    void op(){
        System.out.println("c");
    }
}

class Ideone
{
    public static void print(B b){
        //Some operation unique to class B
        b.op();
    }

    public static void print(C c){
        //some operation unique to class C
        c.op();
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        List<A> l = someMethodThatGivesMeTheList();
        for(A a: l){
            print(a);
        }
    }
}

The example does not compile, but explains what I want to do. How?

I found only the possibility to apply a Visitor pattern, but that would require modifying class A and its subclasses to accept the visitor, and I would prefer to avoid it.

Using getClass() and switch\if is clumsy, not really what I'm looking for.

In the example I used two static methods, but some new classes, wrappers, everything can be used as long as it solves the problem, I have complete control over the code.

A similar question here is Calling method based on run-time type insead of compile-time type, but in my case I'm working with Java, so no dynamic type exists to solve my problem.

Does the following way of creating static methods of `Console` from `TextReader` and `TextWriter` use some design pattern(s)?

System.Console.In is instance of TextReader, and System.Console.Out and System.Console.Error are instances of TextWriter.

The static IO methods of Console just call the equivalent methods on the Console.In and Console.Out TextWriter properties http://ift.tt/2rDNJra

public static int ReadLine()
{
    return In.ReadLine();
}

public static void WriteLine()
{
    Out.WriteLine();
}

Does the above way of creating static methods of Console from TextReader and TextWriter use some design pattern(s)?

I am asking that, because TextReader and TextWriter are created from streams using design pattern "Adapters".

Thanks.

Inheritance design concept

I have 2 unrelated classes

public class ManagedType{
    private string id;
    private string name;
    private string description;
    private string version;
    private string Properties;
   private List<string> baseTypesl
}

public class OtherClass{
    private string id;
    private string name;
    private string description;
    private string target;
    private string sources;
   private List<string> relationships;
}

So is it advised if I abstract out id, name, description into a new base class and let it extends this.

My view is that since they are unrelated we shouldn't. Also we should never extends a class only for properties(unless they are related), but only for common behaviors(which is none here). Please let me know your view on the same.

Sending message to chatbot

I am supposed to design a new C# web application. It has been 5 years since I last designed an application and as such I am feeling a bit lagging in my knowledge to design a good application. Following are a few expectations from the application design:- 1. Loosely Coupled 2. Beautiful aesthetics -Lots of charts and drag drop functionality (free to use any framework or plugins) 3. Lots of interfaces Any suggestions on what tools\frameworks I must be aware of before I start delving deeper. Appreciate your help in advance.

Thanks & Regards

mardi 30 mai 2017

Design pattern for refactoring out class methods with many shared variables

I have the class DataManipulation with the 3 functions ExtractData, Validate, and FinishForms.
All of the methods need access to the private variable of the class (there are quite a few more, example shorter for readability).

The actual class is very long and I would like to separate it into 3 classes, one for each of the methods I have shown.
I use dependency injection to instantiate the class and simply separating the 3 methods into 3 classes would mean passing around quite a few variables, which I think does not help readability.

TL;DR. I have a very long class where methods manipulate a lot of internal variables. Methods can be grouped into 3 distinct areas of responsibilities, but dividing the class into 3 would mean passing around a lot of the internal variables.

I am looking for the right design pattern to use for my problem.

public class DataManipulation
    {
        private readonly IUnityContainer unity, 

        private ImportModel VarUsedEverywhere;

        private List<string> _errorMessages = new List<string>();

        public DataManipulation(IUnityContainer unity)
        {
            _unity = unity;
        }


        public async Task<ImportLogModel> Process(Stream importFile)
        {

            ExtractData(importFile);

            await Validate();

            await FinishForms();

            return VarUsedEverywhere;
        }
    }

.

        private bool ExtractData(Stream importFile)
        {
            //Extract data into VarUsedEverywhere
            //Add to _errorMessages if operations do not succeed.

        }

.

        private bool Validate()
        {
            //validate data in VarUsedEverywhere
            //Add to _errorMessages if operations do not succeed.
        }

.

        private bool FinishForms()
        {
           //Order all the values in VarUsedEverywhere
           //Add to _errorMessages if operations do not succeed.
        }

how command pattern parametrize clients with different requests?

The intent of command pattern is "Encapsulate a request as an object, thereby letting you parametrize clients with different requests..." Can someone explain what does parametrization clients with different requests means? and how command pattern parametrizes clients with different requests?

Any Explanation in this regard will be highly appreciated

Set attribute of bean from a Generic Method Java

I am facing some difficulties to solve this problem. I have to make changes from a "generic" method for parsing CSV files to POJO lists. It was implemented by somebody else. The clazz parameters represent the possible beans that match the type of CSV file. I have to implement a certain logic for setting the last time a file was persisted in my database. Like this, I can keep track when was the last Parsed and persisted file and launch my batching process from this file for avoiding re-reading the whole folder. Should I use reflection or something like:

//  clazz.getMethod("setDate", initialDateFromFileName);

This is a little piece of the method where I already implemented the logic for retrieving the date I want following some business rules I have to stick with.

    private <T> List<T> performProcessing(String path, List<String> headers, Class<T> clazz, String pattern,
                String account, String fileSeparator){
  LOGGER.info("Start perform CSV Processing for account: " + account + " and pattern :" + pattern);

    List<T> listTargetObject = new ArrayList<>();
    Date lastModifiedDate = (Date) quartzDatabaseRepositoryIn.getLastModifiedDate(account);
    List<String> titleCase = new ArrayList<>();
    File folder = new File(path);
    File[] files = folder.listFiles();

    DateUtils.sortFilesByLastModifiedDateDescending(files);

    for (File file : files) {

        if (file.getName().contains(pattern)) {

            LOGGER.info(MessageFormat.format(FILE_RETRIEVED_LOGGER_MESSAGE, file.getName()));
            Date initialDateFromFileName = DateUtils.getDateFromFileName(file.getName());

            if (initialDateFromFileName.after(lastModifiedDate)) {


                  LOGIC FOR Unmarshalling
       ...
}

Then there is another method who will call the performCSV put it into an ArrayList of Foo Objects and persist into the database.

And let say I have a Bean(class) named: Class.java with different instance variables and one of them is

private Date date;
//With setters and getters

My question is: how could I access each setDate for each clazz parameter I will pass into this method?

Java implementation to handle callback messages

I have the following situation I need to handle in my code:

public class Class1 {

    IRequester requester;

    public Class1(Requester impl) {
        requester = impl;
    }

    public List doSomething() {
        requester.request1();  // sends messages to a set of nodes
        //do some more local processing
        list = requester.request2(); // sends some more messages and returns a list
        return list;
    }
}

In this case request1() sends a request to a set of nodes and returns a result which will be used locally for more processing, and then the request2() is made which returns a list. This needs to be returned at the end of execution of doSomething(). request1() and request2() are done through requester which is of type IRequester

public interface IRequester {

    request1();

    List request2();
}

Now request1() and request2() are implemented by the class which actually does the requests. This is the class that handles the communication between the nodes.

public NetworkManager implements IRequester {

    request1() {

        // Create an operation
        // Add callback to the operation             
        // schedule operation
    }

    request2() {

    }
}

Now, my issue is that when I implement request1() here in there I need to create a procedure which will send a message to the node. This procedure can have a callback attached. When the node responds it returns the result. How do I implement this such that it returns the result at the end of my request1?

Working with accumulated bucket values in Entity Framework

I'm attempting to find design patterns/strategies for working with accumulated bucket values in a database where concurrency can be a problem. I don't know the proper search terms to use to find information on the topic.

Here's my use case (I'm using code-first Entity Framework, so EF-specific advice is welcome):

I have a database table that contains a quantity value. This quantity value can be incremented or decremented by multiple clients at the same time (due to this, I call this value a "bucket" value as it is a bucket for a bunch of accumulated activity; this is in opposition of the other strategy where you keep all activity and calculate the value based on the activity). I am looking for strategies on ensuring accuracy of this "bucket" value (within the context of EF) that takes into consideration that multiple clients may attempt to change it simultaneously (concurrency).

The answer "you must track activity and derive your value from that activity" is acceptable, but I want to consider all bucket-centric solutions as well.

I am looking for advice on search terms to use to find good information on this topic as well as specific links.

Is having Constants in Interfaces for boolean parameters of Interface methods a good practice or code smell?

So I have the following Interface:

public interface RoleService {
    boolean INCLUDE_DEACTIVE_OBJECTS = true;
    boolean EXCLUDE_DEACTIVE_OBJECTS = false;
    Set<? extends BaseBusinessObject> getOwnedBusinessObjectsOf(final Employee employee, final boolean includeDeactiveObjects);
}

and somewhere in an upper layer, an example usage is as follows..

if (someCondition) {
    ownedBusinessObjects = roleService.getOwnedBusinessObjectsOf(employee, RoleService.INCLUDE_DEACTIVE_OBJECTS);
} else {
    ownedBusinessObjects = roleService.getOwnedBusinessObjectsOf(employee, RoleService.EXCLUDE_DEACTIVE_OBJECTS);
}

So instead of passing values such as true (or false), I believe it is much easier to read the method call when I say INCLUDE_DEACTIVE_OBJECTS.

But I am not sure, is this just plain stupid? Is this an anti-pattern or a code smell or some sort of violation of a best practice?

I think this resembles avoiding Magic Numbers somehow, but is it as useful or is it rather confusing?

private class implementing inner interface

I am trying to study this piece of code where private nested class implements a nested interface.

public class ConfigurationManager {

 private class ChainPowerListener implements PowerListener {

        private List<PowerListener> powerListeners = new CopyOnWriteArrayList<>();


        ChainPowerListener() {
            super();
        }

        public void registerListener(PowerListener listener) {
            powerListeners.add(listener);
        }

        @Override
        public void onAppPowerOn() {

        }

        @Override
        public void onAppPowerOff() {

        }
 }

}


public interface AppPower {

    boolean isPowerOn();

    void setPowerListener(PowerListener listener);

    public interface PowerListener {

        void onAppPowerOn();

        void onAppPowerOff();
    }

}

  1. What does super refer to in the ChainPowerListener() constructor above? Is it the class that implements AppPower interface?
  2. What is the benefit of this pattern if at all? Is this pattern common in Java world?

I am from c# background who is just starting to learn java. So hope you will be lenient if I am asking something stupid :)

lundi 29 mai 2017

Understanding Factory Pattern with its uses

I have the basic working knowledge on C# and not have the intention of extending it to patterns and design strategies. I came across "Factory" pattern and have few clarifications. Here it goes :

public class Factory
    {
        public string MyProperty { get; private set; }

        private Factory()
        {
        }

        private Factory(string myProperty)
        {
          MyProperty = myProperty;
        }

        public static Factory CreateObjectbyCallingConstructor(string myProperty)
        {
            return new Factory(myProperty);
        }

        public void Display()
        {
            Console.WriteLine("Hello" + MyProperty);
        }
    }

Here's how I invoke it :

 static void Main(string[] args)
        {
            Factory f = Factory.CreateObjectbyCallingConstructor("there");
            f.Display();
            Console.ReadLine();
        }

I understand the following concepts:

a) It is not possible to create instance because of private constructor.

b) I have a static method which is going to create an instance along with parameterised constructor. So I get an instance .

Now, the same thing can be achieved using a normal class instantiation without having private constructor. My question what business problem it solves for me to go for Factory pattern ?

Can anybody explain in layman's language so that I could relate it easily also with immutability with comes with it?

How to comunicate ParentFragment to ChildFragment

I used to use the combination of Activity, Fragment, ChildFragment.

for example,

class ParentFragment extends SpecificPurposedFragment{

    void onCreateView(){
        FragmentTransaction bt = getSupportFragmentManager().beginTransaction();
        ChildFragment childFragment = ChildFragment.newInstance();
        bt.add(childFragment, DIALOG);
        bt.commitAllowingStateLoss();
    }

    int count(){
        return dataList.size();
    }
}

class ChildFragment extends Fragment {

    void onEvent(){
    // When event is invoked, childFragment have to know ParentFragment State
    if(getParentFragment() instanceOf SpecificPurposedFragment){
        int count = ((ParentFragment)getParentFragment()).getCount();
        // UI handling by count.
    }
}

}

in this case, for child Fragment know parentFragment state, ChildFragment use TYPE-CASTING ParentFragment to SpecificPurposedFragment. It has STRONG-DEPENDENCY.

How to be solved it? (condition: more lower DEPENDENCY)

PHP MVC Config class as dependency or with just class constants, accessible from overall?

In my MVC project (PHP 7.1) I have a Config class and a multitude of config files, each of them looking like this:

return [
    'web' => [
        'host' => 'localhost',
        //...
    ],
];

At the app entry point I make an instance of the Config class and load all config file arrays in it. The created object is then passed as constructor argument in all classes that needs it:

class AbstractView {

    private $config;

    public function __construct(Config $config) {
        $this->config = $config;
    }

    private function prepareContext() {
        $this->assign('appHost', $this->getConfig()->get('web/host'));
    }

}

Because it's quite a "big effort" to pass the Config object quite overall in my app, I thought of implementing aConfig` class with only class constants in it, like:

class Config {

    const WEB_PROTOCOL = 'http';
    const WEB_HOST = 'localhost';

}

and access them from overall directly with

class AbstractView {

    private function prepareContext() {
        $this->assign('appHost', Config::WEB_HOST);
    }

}

I wanted to ask: Is this a really good alternative, having in mind that I want to completely avoid static states in my app? Is this alternative a "static" one or absolute not? What about testability (I don't have any experience with it yet)?

Thank you very much.

c++ - abstract class and alternative to virtual constructor

Let say I have the following code:

class Block{
private:
  data Data;
public:
  data getData();
};

Actually, there are several ways to build a block, but always with the same member Data and method getData(), the only difference is how to build the block. In other words, the only difference is the constructor...

Instead of writing a different class for each building process, I could factorize parts of my code, defining and declaring getData in an abstract class, if there were such thing as a virtual constructor in c++ that I could write differently for each derived class corresponding to a different building process.

I do not have a lot experience for this kind of things, so I wondered if there was an alternative to a virtual constructor ? or may be a different way to do this factorization ?

PS: I am aware of http://ift.tt/2s7oBWN but it seems quite complex regarding what I want to do, which seems quite common... I just want to factorize shared code between several classes, which corresponds to everything except the constructor. And I want to force new classes corresponding to other building processes to implement a new constructor.

More details about my particular situation:

I have an algorithm where I use blocks and it does not depend on their building process, so I have implemented the algorithm using a template argument to represent a block indifferently of its building process. But I use a few methods and its constructor, so I need my classes representing blocks to all have the same kind of methods I need and the same constructor to use them as a template argument of my algorithm implementation. That is why I thought of abstract class, to force a newly implemented class representing blocks to have the methods and the constructor I need in the algorithm I implemented. May be it is a bad design pattern and that is why I am stuck...

ES6 Map an object to a decorator

I'd like to map an object with properties (key) to a decorator (value). I'd like to use a Weak Map if possible. I have a solution that is working using a string, which is fine except that Weak Maps do not accept strings as keys. Is this possible with a Map or a WeakMap?

'use strict';

class Accordion {

    constructor() {}

}

let Decorators = new Map();

Decorators.set({nodeName: 'tag-name-here', component: 'accordion'}, (client) => { return new Accordion(client) });

class Client {

    constructor() {

        let key =  {nodeName: 'tag-name-here', component: 'accordion'}
        let decorator;

        if (Decorators.has(key)) {

            decorator = Decorators.get(key)(this);

        }

        console.log(decorator); //undefined, unless I use a string as a key.
    }
}

new Client();

generic pattern: express.js

I would like to create a generic pattern for my routes (using express 4):

router.get('co/:c/works', worksController.list);
router.get('co/:c/bi/:b/works', worksController.list);
router.get('co/:c/bi/:b/pl/:p/works', worksController.list);
router.get('co/:c/pl/:p/works', worksController.list);
router.get('co/:c/pl/:p/bi/:b/works', worksController.list);
...

where :c, :b, :p are identifiers (integer)

Then I am trying to use:

router.get('co/:c\/bi/:b|\/pl/:p+/works', worksController.list);

my problem is that for the route

http://localhost:3000/co/:12/bi/:34/works

the identifiers are truncated after the first character like this:

http://localhost:3000/co/:1/bi/:3/works

could you please help me and tell me how to fix it ?

thank you.

Olivier

Factory Pattern Database connection

I am trying to implement factory pattern on Database Connection using MYSQL , SQLSERVER facing wired error "Object reference not set to an instance of an object " on sql command object

internal class SqlServerDB : IDatabase
    {
            private SqlConnection _Connection = null;
            private SqlCommand _Command = null;


        public IDbCommand Command
        {
            get
            {
                if (_Command == null)
                {
                    _Command.Connection = (SqlConnection)Connection;

                    //_Command = new SqlCommand();
                }
                return _Command;
            }
        }

        public IDbConnection Connection
        {
            get
            {
                if (_Connection == null)
                {
                    string connectionString = ConfigurationManager.ConnectionStrings["testSQL"].ConnectionString;
                    _Connection = new SqlConnection(connectionString);
                }
                return _Connection;
            }
        }
    }

Database Factory Section :

  public static class DatabaseFactory
        {
            public static IDatabase CreateDatabase(DBType type)
            {
                switch (type)
                {
                    case DBType.SqlServer:
                        return new SqlServerDB();
                    case DBType.MySql:
                        return new MySQLDB();

                }
                return null;
            }
        }

Main Method

static void Main(string[] args)
        {
            IDatabase database;
            DBType databaseType = DBType.SqlServer;

            database = DatabaseFactory.CreateDatabase(databaseType);
            IDbConnection connection = database.Connection;
            IDbCommand command = database.Command;
            command.CommandType = CommandType.Text;
            command.CommandText = "select * from User";
            connection.Open();

        }

and the selection of database by Enum.

What is the use of applying Design patterns in javascript?

I started learning Design patterns. And i learned about Module Design pattern in javascript. Which provides object oriented capabilites like functionality (Private and Public variables) in javascript. One thing is that, why i should make the variables as private or public. Since even a novice developer can see the javascript code in applications and even he can access and see those variables using breakpoints in the browser tools such as inpect elements?

Call method with implicit downcast

I have a List defined as

List<ParentClass> parentClassList;

Parent class is abstract, so when I add elements to the List I do something like

parentClassList.add(new ChildClassOne(...));
parentClassList.add(new ChildClassTwo(...));

and so on... I actually have 5 child classes right now.

What I'd like to do is to call a method in another Class, overwriting its arguments, so:

public void doSomething(ChildClassOne arg) {...}
public void doSomething(ChildClassTwo arg) {...}

But if the type of the List is the parent Class I can't do

doSomething(parentClassList.get(0));

Basically I need to perform different actions based on the child's type and I need access to all the methods inside a specific child. Different childs have different methods, they have only one methods in common.

Dinamically setting the validity of the state consistency of an object in relation of the action we have to perform

I have searched very hard on google on every possible discussion forum about this topic but I can't seem to find anything that meets my needs. I try to explain what I want to obtain: basically I want to use the something similar to the builder pattern to validate the state of an object in creation phase because this allows me to centralize the validation logic in an elegant way and it is readable and easy to mantain by a developer. For example such a code:

Person person = new PersonBuilder() .id(1)
.name("John")
.surname("Smith")
.age(36)
.hobbies("Playing tennis") .build();

for me is very elegant and readable and it is perfect because everytime that I want to use an object of the Person class I can provide only valid state of object before stepping through the next phases.

But to think about it this validation rules are good only for an object for which I want to perform an insert or update because the validator checks that all mandatory fields are setted otherwise throws back an IllegalStateExcpetion. What if I want to perform a research of the person by any of the available attributes? I mean when I search for an object I don't have to specific all the mandatory fields. I could also specify just the surname or just one of the other available fields...

Could it be acceptable to add a "buildForSearch" method into the builder with different criteria of validation?

I know that maybe is conceptually wrong to differentiate the entity behaviour of validation basing on the actions but do you know if there is a pattern to accomplish this, mantaining the advantages of the builder pattern?

Many thanks for the help

Forcing Subclasses to Be Immutable

I have a base class with some properties:

class Component {
    readonly id: number
    readonly type: number
}

And I'd like to have some subclasses:

class HealthComponent extends Component {
    max_health: number,
    current_health: number
}

etc.

What I want is essentially for HealthComponent to have the same behavior as an Immutable.Record:

const health = HealthComponent(100, 100);
health.max_health = 40; // Shouldn't work
const new_health = new HealthComponent(40, health.current_health); // Works

All of the classes are just data; no behavior (if there is any behavior, it will be in static methods, not instance methods). Now I want to enforce as much as possible that the subclasses are immutable (in the sense that modifications are allowed, but making changes results in a new object a la Immutable.js) and I can't figure out the best way to do this. So far the best thing I've come up with is to just have each subclass have a readonly data member that is an Immutable.Record with the appropriate fields, but even this isn't quite right because changing it would return a new data object, but I really want a whole new Component object, and this also doesn't really enforce that all components follow this convention. The other thing I've considered is to have the base class be an Immutable.Record with a data: Immutable.Map field and then the subclasses provide an Immutable.Map to the super constructor with all the keys, but then people could just add new keys willy nilly which isn't ideal either.

Is there a magic design pattern that could help me here?

dimanche 28 mai 2017

Multiple similar activities, solution to do that ? Android

Hello I'm creating an app with multiple similar activities and here is question, should I build separated layouts + activities or maybe should I build just one activity and just load layout ? In app looks like I have main menu with option like prizes/opening hours/contact etc then when I clock prizes I go to content of it which is just text.

Java Using For Loop while handling Array to make Pattern

If I want to print the pattern below, and I have an Array:

*******
 ***** 
  ***  
   *   
  ***  
 ***** 
*******

This is what I have so far:

public static void main(String[] args)
{

int[] p = {7,5,3,1,3,5,7};

for(int i=0; i<=7; i++)
{

System.out.print("\n");

for(int k =i; k<=7; k++)
{

 k = p[i];  //I'm trying to find a way to print "*"s with array element value 



for(int j = i; j<=7; j++)
 {
System.out.print("*");
 }
}
}
}
}

I definitely went wrong somewhere, and I apologize for my ignorant. I'm just trying to learn. Thanks!

VB.NET Inheritance Pattern with Auto Complete Members

I have scoured the web looking for a way to create a class and have it auto populate itself with member functions, much like the way IDisposable does when you press enter after implementing it.

I know I can design my own interfaces, but all member subs, properties and functions get auto populated with 'Throw New Not NotImplementedException()'.

Is there a way these can refer to the 'Base' class as default? eg. MyBase.Sub(), or populate with code that I choose?

Architecture: Dependency Injection, Loosely Coupled Assemblies, Implementation Hiding

I've been working on a personal project which, beyond just making something useful for myself, I've tried to use as a way to continue finding and learning architectural lessons. One such lesson has appeared like a Kodiak bear in the middle of a bike path and I've been struggling quite mightily with it.

The problem is essentially an amalgam of issues at the intersection of dependency injection, assembly decoupling and implementation hiding (that is, implementing my public interfaces using internal classes).

At my jobs, I've typically found that various layers of an application hold their own interfaces which they publicly expose, but internally implement. Each assembly's DI code registers the internal class to the public interface. This technique prevents outside assemblies from newing-up an instance of the implementation class. However, some books I've been reading while building this solution have spoken against this. The main things that conflict with my previous thinking have to do with the DI composition root and where one should keep the interfaces for a given implementation. If I move dependency registration to a single, global composition root (as Mark Seemann suggests), then I can get away from each assembly having to run its own dependency registrations. However, the downside is that the implementation classes have to be public (allowing any assembly to instantiate them). As for decoupling assemblies, Martin Fowler instructs to put interfaces in the project with the code that uses the interface, not the one that implements it. As an example, here is a diagram he provided, and, for contrast, a diagram for how I would normally implement the same solution (okay, these aren't quite the same; kindly focus on the arrows and notice when implementation arrows cross assembly boundaries instead of composition arrows).

Martin Style

Martin Style

What I've normally seen

Not Martin Style

I immediately saw the advantage in Martin's diagram, that it allows the lower assemblies to be swapped out for another, given that it has a class that implements the interface in the layer above it. However, I also saw this seemingly major disadvantage: If you want to swap out the assembly from an upper layer, you essentially "steal" the interface away that the lower layer is implementing.

After thinking about it for a little bit, I decided the best way to be fully decoupled in both directions would be to have the interfaces that specify the contract between layers in their own assemblies. Consider this updated diagram:

Proxy Style

Is this nutty? Is it right on? To me, it seems like this solves the problem of interface segregation. It doesn't, however, solve the problem of not being able to hide the implementation class as internal. Is there anything reasonable that can be done there? Should I not be worried about this?

One solution that I'm toying around with in my head is to have each layer implement the proxy layer's interface twice; once with a public class and once with an internal class. This way, the public class could merely wrap/decorate the internal class, like this:

Proxy and Decorator Style!

Some code might look like this:

namespace MechanismProxy // Simulates Mechanism Proxy Assembly
{
    public interface IMechanism
    {
        void DoStuff();
    }
}

namespace MechanismImpl // Simulates Mechanism Assembly
{
    using MechanismProxy;

    // This class would be registered to IMechanism in the DI container
    public class Mechanism : IMechanism
    {
        private readonly IMechanism _internalMechanism = new InternalMechanism();

        public void DoStuff()
        {
            _internalMechanism.DoStuff();
        }
    }

    internal class InternalMechanism : IMechanism
    {
        public void DoStuff()
        {
            // Do whatever
        }
    }
}

... of course, I'd still have to address some issues regarding constructor injection and passing the dependencies injected into the public class to the internal one. There's also the problem that outside assemblies could possibly new-up the public Mechanism... I would need a way to ensure only the DI container can do that... I suppose if I could figure that out, I wouldn't even need the internal version. Anyway, if anyone can help me understand how to overcome these architectural problems, it would be mightily appreciated.

Setting super properties using abstract subclasses

Is it ok(for java and SOLID principals) to extend abstract classes in order to set properties from the super class? What I want to achieve is to apply different values to p2 depending on what p1 has and also p3 values will depend of what the value of p2 is(something similar when you cascade drop down menus). Could this scenario be dealt with a design pattern?

public interface Iface{
    public void set_p1(int i);
    public void set_p2(int i);
    public void set_p3(int i);
}

public abstract class A implements Iface{
    private int p1;
    private int p2;
    private int p3;

    public void set_p1(int i){
        this.p1 = i;
    }

    public void set_p2(int i){
        this.p2 = i;
    }

    public void set_p3(int i){
        this.p3 = i;
    }
}

Here I set p1 to 100

public abstract class setOne extends A {
    public setOne(){
        set_p1(100);
}

now I set p2 depending on the values of p1

public abstract class setTwo extends setOne {
    public setTwo(){
        //do some work using p1
        set_p2(200);
}

now I instantiate my setTwo abstract class

public class TestClass extends setTwo {
    public TestClass(){
         super();
}

TexClass myObj =  new TestClass();

now I expect the values of the object as follows:

myObj.p1 = 100

and

myObj.p2 =  200;

Would this design of interface be considered bad?

I have written an interface for storing data as List/Map and have the ability to retrieve it back. Something like this:

public interface Repository {

    <K, V> void register(String typeTag, Key<K> key, V value);

    void unregister(String typeTag);
    void unregister(String... typeTags);
    void unregister(Collection<String> typeTags);

    <T> void add(String typeTag, T object);
    <T> void add(String typeTag, Collection<T> object);

    <T, K> T get(String typeTag, Key<K> key);
    <T, U, K> Map<T, U> getAsMap(String typeTag, Collection<Key<K>> keys);
    <T, U> Map<T, U> getAsMap(String typeTag);
    <T, K> List<T> getAsList(String typeTag, Collection<Key<K>> keys);
    <T> List<T> getAsList(String typeTag);
    <T, K> Map<String, T> get(Collection<String> typeTags, Collection<Key<K>> keys);

    <T> T remove(String typeTag, T object);

    void clear(String typeTag);
    void clear();

    <U, V> Map<U, V> map(String typeTag1, String typeTag2) throws IllegalMappingException;
    <U, V, K> Map<U, V> map(String typeTag1, String typeTag2, Collection<Key<K>> keys) throws IllegalMappingException;
    <U, V> Map<U, V> map(String typeTag1, Criteria<U> type1Criteria, String typeTag2, Criteria<V> type2Criteria) throws IllegalMappingException;
}

Now, I have well thought up the purpose of this interface and that can be defined through basically the following methods:

register(), unregister(), add(), get(), remove(), clear() and map()

But, as you can see there are overloaded versions of these methods that support taking and giving back data in Collections. These can be classified as "convenience" methods(as it seemed to me). But it makes me wonder that the implementor is going to have to implement these methods as compulsion and there are just too many of these to implement. I personally got the feeling that the design is putting too much onto the interface and the "burden" should be reduced somewhat.

First of all,

Is this design really bad?

What things/strategy should I take into consideration/apply and keeping what in mind to change this design before I continue to expand the hierarchy.

Does two instance of singleton class has a same property value?

Hello stack in new to design pattern in c# can any one please give me some instruction about implementation of singleton class. i just implement one tutorial but i don't able to exact use of singleton class with this "singleton means we can create only one instance of a class" then why we don't access property which is written in the singleton class using two different instance of the class.

please look my code and give me instruction what was the mistake i made.

static void Main(string[] args)
    {

        Singleton instance = Singleton.getInstance();
        instance.Message = "Text Message";

        Singleton instance1 = Singleton.getInstance();
        Console.WriteLine(instance.Message);
        Console.WriteLine(instance1.Message);
        Console.ReadKey();
    }
class Singleton
{
    private static Singleton singleton=null;
    private Singleton(){}
    public static Singleton getInstance()
    {
        if (singleton!=null)
        {
            return singleton;
        }
        return new Singleton();
    }
    public string Message{get; set;}
}

samedi 27 mai 2017

Design Patterns In Python Packages

I have been searching and trying to find examples of design patterns in python packages to no avail. And I was wondering if anyone knows any python packages that have design patters in them.

The Humble Dialogbox example in Java

I remember reading the article, The Humble Dialogbox, by Michael Feathers, quite a while back in context of programmatic testing of GUIs.

When I needed to reference it again today, I realized the article's no more available - Not only is the original link broken, I cannot even find the article anywhere else on the web anymore.

Could someone summarize the salient points of the idea, with a Java program or snippets? Was the idea described in the original 'The Humble Dialogbox' article exactly identical to the MVP design pattern for testing GUIs?

How to apply OO design patterns in a NodeJS project?

i'm doing a project in NodeJS about finantial control that uses a model for accounts (Class Accounts) which have some "private" attributes (_id, _name, _parent, _balance and _isDeleted) and some methods (get attributes..., set attributes...).

All created accounts (objects) are converted into a JSON and stored into a file (custom database), except their methods (only the attributes are passed to the JSON).

When i load the database file, i get the JSON containing all accounts and their attributes, and need to show them into a view page, using EJS engine.

But after converting into JSON and loading them they doesn't have their methods to get their "private" attributes anymore, and i couldn't think any way to get those info, except by using directly the attribute reference (like _id, _name ...).

How can i get those attributes according to OO design patterns, avoiding to make external references to private attributes of a class?

Thanks!

How to synchronize update and render functions in 2d games

This may seems pretty basic, but I'm really wondering what's the best way to make sure a game has the time to update all its logic before rendering?

If we take the NES for example, if you know the cost of each instructions you can calculate how much time your logic takes before the VBlank so you are using most of the processing time available. Nowadays, it's pretty much impossible to do that kind of thing with modern computers.

I just want to know what I can use to scale my game and to be able to keep track of the cost of the functionalities I'm implementing so I can assure a solid framerate.

[Debugging]How will you identify what is wrong with the model and in which part?

I encountered one interview question:
Suppose you have: browser–>cache–>database model.Now,suppose a bug fix has been done on this model.After bug fixing, it has been found that a request–.>response that earlier took 1ms now takes 25 ms. How will you identify what is wrong with the model and in which part?

My Approach: I will see the stack Trace.That is sequence of method calls,which method calls which method and further measure the duration of each method call to find out which method took more time(database response,request etc) .Is there any other better alternative possible?

coding principle behind "if everything has it then nothing should have it"

As I am looking through the source code of a project I'm working on, I see the following pattern:

//in one class:
function getNavigation($region_id, $clear_cache = FALSE){ .. }

//in another class getPage($region_id, $clear_cache = FALSE){ .. }

..and so on. These functions all have the same second parameter, with a default value of false.

Furthermore, looking through the calls to these methods, each call ONLY passes one parameter, the $region_id - never a value for $clear_cache. I say ONLY, but there is one exception in test coding, that's it, where it's set to TRUE.

My intention is to remove the clear_cache variable and replace it with another needed parameter on the premise that "if everything has it then nothing should have it, and we should just assume it's the default way." I usually don't ask non-specific coding questions, but is there any name to this principle in coding?

If the coder wants to do that one test case then they can just manually change the value :)

Fluent Interface(chaining method) with C++ parallelism

Does anyone have an experience in using Fluent Interface (or chaining method) with SIMD and other levels of parallelism using C++? Is there any performance penalty, side effects, e.g. on instruction-level? By chaining we define an order to perform the methods, but how this order defines an argument calculations?

This technique is widely popular within web-developers. I have thought to apply it for my personal project for C++, but will I lose the performance cause of that?

I really appreciate your help. Thanks in advance.

Constructing and Designing Class Diagrams

I have the following scenario where I have to design a class diagram :

A grocery store (e.g., a supermarket) sells items. There are two types of items: edible (i.e., any item that can be used as food) and non-edible. Some items are sold by weight, and some are sold per unit. Some items are taxable, while others are not. Some items have special prices when sold in groups (e.g., 2 for $3). A purchase may contain many items.

The points need to be considered are :

  • An item is either edible or not and this fact does not change during the lifetime of the item, whereas the pricing strategies may change during the lifetime of the item.
  • Each pricing strategy is associated with a certain set of operations. For example, for the taxing strategy, whether or not an item is taxable, we may have an operation that computes the tax (this function can then return 0 for non-taxable items)
  • Although the set of operations for a pricing strategy stays the same, the ways those operations are handled may change over time. For example, the way we compute taxes for edible and non-edible items may differ over time.
  • Although the set of operations for a pricing strategy stays the same across different items, we may want to implement those operations in different ways for different items. For example, we may want to compute the tax differently for oranges and apples.

I know it must be a strategy design pattern. I am thinking of doing a PricingStrategy interface and implement the strategies but I am not sure of them. Moreover, I may create an Item super class and Edible and Non-Edible Items can inherit the class however nothing is clear in my head, any help is appreciated.

What is a best design to hold a "global" mutable list?

Let's say that I have an ArrayList of class Person and I have two objects that are generated from two different classes which read and write to this ArrayList.

For example,

public class Main { 
   public static void main(String[] args) { 
       A a = new A();
       B b = new B();
   }
}

What, in your opinion is the best design to handle this ArrayList. I can think about two options:

  1. create the Array List in class Main:

    public class Main { 
    
           public static ArrayList<Person> list = new ArrayList<>();
    
           public static void main(String[] args) { 
               A a = new A();
               B b = new B();
           }
    }
    
    

and then access the list inside classes A and B by:

Main.list....

  1. Create the ArrayList as a local variable in main method and send to the constructor of A and B.

    public class Main {

           public static void main(String[] args) {
               ArrayList<Person> list = new ArrayList<>(); 
               A a = new A(list);
               B b = new B(list);
           }
    }
    
    

Connect event of model in mvc

I am developing a small application with c#, i need to use the MVC pattern for separate the logic from the GUI, for that I have create two project, one is a dll project, and one is win forms project, where in the dll there is the logic of my models. Now some models, need to be updated, with c# event from other models. My question is where I can connect this events? I would like to be able to connect them inside the dll through a class, but there are so many parameters to go to the builder of this class that will then connect them. This is because I think that linking the events launched and received by the various models, should not be done within the project window form where I will create only views and controllers. Thanks in advance

Aggregate fields in DTO

I have some architectural/pattern question. Suppose that i have a domain model with two classes. I use Code First and Repository Pattern. (To make it more simple in the example I use only fields, not properties)

public class Person {
    public int Id;
    public string Name;
    public string Surname;
    public virtual ICollection<Pet> Pets;
}
public class Pet {
    public string Name;
    public int BirthYear;
    public int OwnerId;
    public Person Owner;
}

I also have PersonDto, and PetDto classes, with the only difference, that Pets field in PersonDto is a simple List. I use Automapper to transform model classes to dto. Dto are next sent to the client through REST Api. Now, what if on some view I need to show for every Person its Name, Surname and PetCount (lets assume that there are so many pets that it would make it very inefficient to pull them from database and simply count them on the view).

Now - what would be the correct approach to introduce PetCount. Should I put this field in the PersonDto as well as in the Person class, and prevent it from creating column in the database (it doesn't seem right for me). Or maybe I should only create PetCount field in PersonDto - but then when to count this value, in the repository method or maybe while mapping (the latter also doesn't seem right for me). Another question is if I should create an extra field in PetDto, or maybe I should inherit PersonDto with PersontWithPetCountDto, or maybe I should create PersontWithPetCountDto class without inheritance, but with PetCount field and all the fields from PersonDto

Design pattern to editor of templates in Spring

I have a service in Spring that reads a template written/edited by user and with fields and entities existing in template (edited by user) are return the results of this template. Example: , in this case user are a entity and name is a field written by user, follow example, the question is what best design pattern to this service ? for the better organized.

http://ift.tt/2qYgoGc

Note: the entity represent a endpoint, this service is a big client of an API

vendredi 26 mai 2017

Add partial implementation to abstract method

What is the best way to achieve a design where an abstract method is implemented but must also still require implementation from subclasses. This sounds very rusty at the moment so I will illustrate it:

abstract class Foo {
    abstract void update();
}

abstract class Bar {
    void update() {
        //Do something
        update_();
        //Do something else
    }

    abstract void update_();
}

So basically, I want a way to add some implementation to an abstract method without stopping it propagating. I feel that simply renaming the method will create unclean code.

What is the best way to approach this problem? Is it simply renaming the method? Or is this pattern best avoided altogether?

How to best deal with empty lines when overloading the input stream operator?

I'd like to read a file line by line, and for every non-empty file create a new instance of some class Foo. I'm unsure how to best achieve that.

So far, I have overloaded the >> operator for Foo:

std::istream& operator>>(std::istream& is, Foo& foo)
{
    std::string line;
    std::getline(is,line);

    if (!line.empty()){
        foo.valid = true; 
    }
    return is;
}

Now I can do the following:

std::ifstream ifs(file);
Foo *foo = new Foo();
std::vector<Foo> all_foos;    

while(ifs >> *foo) {
    if(foo.valid) { 
       all_foos.push_back(foo);
       foo = new Foo();
    } else {
       delete foo;
    }
}
ifs.close();

I think that this is rather ugly and there has to be a nicer solution that doesn't require the valid flag. But how? As far as I can see, the >> operator requires an instance of Foo - but how does one deal with this instance in case it's not needed, e.g., when the input stream reaches EOF or contains an empty line?

What's the best way to do this in C++?

How should I model processes in RxJava?

Suppose I have some process, such as downloading a file or running a big computation.

The events it fires might look like this:

{ progress: "0%" }
{ progress: "23%" }
{ progress: "78%" }
{ progress: "100%" }
{ content: "Hello. world. " }

Or perhaps:

{ progress: "0%" }
{ progress: "23%" }
{ error: "Access denied. " }

In each case, we have n status-updates (T) followed by either a result (S) or an error (Throwable):

T* ( S | Throwable )

A process is a mix of Observable<T> and Single<S>.

There are a few ways to model a process using the Rx primitives:

  • Observable<T> and Single<S>
  • Observable<Either<T, S>>
  • Observable<Object> and instanceof
  • Process<T, S> with toObservable and toSingle methods
  • etc...

How has this been successfully modelled in the past?

Which approaches are best and when should they be used?

What is the simplest Event design pattern

Lately, I've been pondering about the following problem for a while. For the code bellow, what is the easiest way to modify Game::counter via Event::Perform() method which is called from Game class? I considered Observer and Command design patterns, but it seems that there is a much simpler way to do this.

class Game
{
public:
    Game();
private:
    int counter;
    vector<Event*> Events;
};

class Event
{
public:
    virtual void Perform() = 0;
};

Thank you

How PassNGuard Quick Find Pattern works?

I'm using PassNGuard v1.0.0.0
What does it mean Quick Find Pattern? How does it work?

jeudi 25 mai 2017

Is there some thing in python language which is similar to interface in Java or C++ as well? [duplicate]

This question already has an answer here:

I've used to program use Java or C++, both has the 'interface' mechanism. And in some books of Object Oriented Programming and Design Pattern, interface is often mentioned.

Is there anything similar to interface in Python?

Factory pattern with parameters

I am using the JDBC connector for my log4j output and want to post my log entries to a Postgres database. This looks as follows:

<Jdbc name="Jdbc" tableName="log">
    <ConnectionFactory class="database.ConnectionFactory" method="getConnection"/>
    <Column name="event_date" isEventTimestamp="true" />
    <Column name="level" pattern="%level" isUnicode="false" />
    <Column name="logger" pattern="%logger" isUnicode="false" />
    <Column name="message" pattern="%message" isUnicode="false" />
     <Column name="exception" pattern="%ex{full}" isUnicode="false" />
</Jdbc>

As far as I understand this requires a static class with the method getConnection and I implemented this using the factory pattern:

public class ConnectionFactory {
    private static interface Singleton {
        final ConnectionFactory INSTANCE = new ConnectionFactory();
    }

    private ComboPooledDataSource comboPooledDataSource;

    private ConnectionFactory() {
        comboPooledDataSource = new ComboPooledDataSource();
        try {
            // Load the jdbc driver.
            comboPooledDataSource.setDriverClass("org.postgresql.Driver");
        } catch (PropertyVetoException exception) {

        }

        // Need to create datasource here, requires parameters.
    }

    public static Connection getConnection() throws SQLException {
        return Singleton.INSTANCE.comboPooledDataSource.getConnection();
    }
}

My problem is, that I want to create the connection to the database via parameters (host, port, database, etc.) and do not want to hard-code it. Also having a static class which holds the configuration would not be preferred because I would like to be able to unit test it easily.

What is a good solution to achieve this? Am I maybe overlooking something or is this a bad practice?

Dependency Injection vs Abstract Factory - choosing the right pattern

I'm developing tool that migrates issues from old to new issue tracking system. I have separated everything with interfaces, but I'm not sure what's the best way to glue it back together. I have 3 dependencies, that require runtime data:

  • INewSystemClient - client to connect to new system
  • IRetryStrategy - handles timeouts and retries
  • IMigrationSettings

These 3 dependencies are dependencies of many others. I couldn't figure out other way to glue everything, than registering these 3 as singletons (via DI container). I also know, that singletons are considered a bad pattern, so I'm considering switching to abstract factory.

Example relationship which forced me to use singleton:

  • Dependency1(INewSystemClient client, ...) // constructor for Dependency1
  • Dependency2(INewSystemClient client, ...) // constructor for Dependency2

INewSystemClient requires runtime data like user, pw, host etc.

Should I switch to abstract factory and make factory create objects instead of DI container?

How i can reused/compsose repository method?

Used DSLContext I have a method for select all relationship data.

 open fun selectAllSomethings(id: String): List<SomeDto> = ctx
    .select(..), 
    .from(..)
    .join(..)
    .leftJoin(...)
    .fetch()
    .map()

And need reused this logic with add where for concrete id and change fetch to fetchOne and map. How i can reuse first part of query?

ctx.select(..), 
    .from(..)
    .join(..)
    .leftJoin(...)

Is it necessary to divide this into two different methods? Or need to add "if" ?

Tips for turning ideas into programs? Design, structure etc

I am starting to make more complex programs (Python) at work other than single tasks scripts, and I'm curious to know what one would research to better & more thoughtfully plan and design their programs? I'd rather have a method of designing things out before I sit in front of PyCharm and start coding.

Looking for books, articles, or just topics to research.

TY!

Are the decorator streams also implemented as adapters of stream instances or as some other design pattern?

From C# in Nutshell: enter image description here

The stream adapters are implemented as adapters of stream instances.

Are the decorator streams also implemented as adapters of stream instances? What design pattern are they implemented?

Note that decorator streams are implemented as derived classes of System.Stream or of its derived classes, while stream adapters are not (but via composition which I guess). So I wonder if adapter patterns can be implemented via either composition or inheritance?

Thanks.

How can I conglomerate an array of forecast data in PHP?

The Setup

I have an array of rain probability that I'm outputting as a forecast:

$rain_probability = array(
  '7am'  => '33',
  '8am'  => '0',
  '9am'  => '8',
  '10am' => '7',
  '11am' => '8',
  '12pm' => '19',
  '1pm'  => '8',
  '2pm'  => '13',
  '3pm'  => '50',
  '4pm'  => '50',
  '5pm'  => '60',
  '6pm'  => '60',
  '7pm'  => '7',
  '8pm'  => '5',
  '9pm'  => '0'
);

$forecast = 'The likelihood of rain is: ';

foreach( $rain_probability as $hour => $percentage )
{
  $forecast .= "$hour: $percentage%. \n";
}

echo $forecast;

The Results

The likelihood of rain is:
7am 33%.
8am 0%.
9am 8%.
10am 7%.
11am 8%.
12pm 19%.
1pm 8%.
2pm 13%.
3pm 50%.
4pm 50%.
5pm 60%.
6pm 60%.
7pm 7%.
8pm 5%.
9pm 0%.

Desired Results

I'd like this to be more human-friendly, like this:

The likelihood of rain is:
7am: 33%.
8am-11am: less than 10%.
12pm: 19%.
1pm: 8%.
2pm: 13%.
3pm-4pm: 50%.
5pm-6pm: 60%.
7pm-9pm: less than 10%.

What I Tried

Thought this would be pretty simple, so I began writing a loop that would check to see if the probability for the previous hour was the same as the current hour. Then needed to special case for numbers less than 10%. Then had to special case the first and last array elements. Pretty soon I was in the midst of a lot of conditional statements and (excuse the pun) the code was not very dry anymore. And wasn't sure there wouldn't be bugs with certain combinations or sequences of probabilities, and could setup tests for that. But overall started feeling like I may be reinventing the wheel and that maybe there was a better approach.

The Question

My question is not "how can I make this work" - but rather does there exist a classical approach, pattern, or even a class or library for solving this problem? ( Sort of feels like a computer science homework assignment )

Suggestion for design pattern or implementation

I am stuck at finding correct pattern or solving the following problem.

class Proxy:
    db_name = ''

    @property
    def cursor(self):
        return db_cursor(self.db_name)


class Profile:
    db_proxy = Proxy()

    def __init__(self, user_name, gender, **kwargs):
        self.user_name = user_name
        self.gender = gender
        # etc...

    @classmethod
    def create(cls, data):
        # create profile in database, and assing properties to object
        cls.db_proxy.cursor.execute('create user profile query')
        profile = cls(**data)
        return profile

    @property
    def is_male(self):
        return self.gender == 'male'

    @property
    def is_female(self):
        return self.gender == 'female'


class User:
    db_proxy = Proxy()

    def __init__(self, user_id, profile):
        self.user_id = user_id
        self.profile = profile

    @classmethod
    def create(cls, user_id, user_profile):
        cls.db_proxy.cursor.execute('create user query')
        profile = Profile.create(user_profile)
        user = cls(user_id, profile)
        return user

    @property
    def is_male(self):
        return self.profile.is_male

    @property
    def is_female(self):
        return self.profile.is_female


class Server1:
    def __init__(self):
        # database proxy should connect to 'server1_db'
        pass

    def create_user(self, user_id, user_profile):
        user = User.create(user_id, user_profile)

        return {
            'id': user.user_id,
            'name': user.profile.user_name,
            'gender': user.profile.gender,
            'success': True
        }


class Server2:
    def __init__(self):
        # database proxy should connect to 'server2_db'
        pass

    def create_user(self, user_id, user_profile):
        user = User.create(user_id, user_profile)

        return {
            'UserId': user.user_id,
            'UserName': user.profile.user_name,
            'Gender': user.profile.gender,
            'Status': 'OK'
        }

1) I want to have User/Profile one implementation, so they would be like core logic to process users and their profiles. Also it has access to database "proxy".

2) Different Server's are connected to separate databases with separate settings on each, however the way User/Profile are stored and queried should remain the same.

3) After Server instantiated, i need to connect to required database, that is set in __init__ method of the server.

4) After request received on server, i want to be able to user User/Profile instances as described in create_user() method of Server's, and so processing users will use correct databases

5) User/Profile, Proxy, Server1, Server2 are implemented in different modules.

6) The main thing is to be able to use User/Profile instances without providing it db connection to methods, like this create_user(db, *args), and it would itself handle db connection set in Proxy or kind of.

I came up with idea to set db connection in Server's __init__ method, like this:

...
def __init__(self):
    User.db = db_connection()
    Profile.db = db_connection()

However it wont work, because db would be overrided after another Server initialized.

Also i tried to create UserProxy/ProfileProxy for every server and use them:

class UserProxy(User):
    db = None

class ProfileProxy(Profile):
    db = None

class Server:

    def __init__(self):
        UserProxy.db = db_connection()
        ProfileProxy.db = db_connection() 
    ...

    def create_user(self, **kwargs):
        user = UserProxy.create_user(**kwargs)

It would work for User, but obviously not for Profile, because inside users module, where User and Profile classes are, User are using Profile class and doesnt know anything about which db to connect to.

7) I am not sure if i described it understandable enough, not an english native speaker.

8) Maybe it looks too complicated, but maybe there's some kind of desing pattern available to accomplish this.

Basic small Angular file structure

Question

Can someone show me the correct way to lay out the structure for my first angular project?

Overview

This is my first Angular project, and i wish to get the structure correct before I go further.

I am building a form that has multiple sections and functions.

I have seen many different ideas online and mainly for large projects not for a small starter project so I hope someone can help me get starred.

Current structure

enter image description here

all the form files are different sections of my form.

app.js

// app.js
// create our angular app and inject ngAnimate and ui-router 
// =============================================================================
angular.module('formApp', ['ngAnimate', 'ui.router'])

// configuring our routes 
// =============================================================================
.config(function($stateProvider, $urlRouterProvider) {

    $stateProvider

        // route to show our basic form (/form)
        .state('form', {
            url: '/form',
            templateUrl: 'form.html',
            controller: 'formController'
        })

        // nested states 
        // each of these sections will have their own view
        // url will be nested (/form/signup)
        .state('form.signup', {
            url: '/signup',
            templateUrl: 'form-signup.html'
        })

        // url will be /form/select
        .state('form.select', {
            url: '/select',
            templateUrl: 'form-select.html'
        })

        // url will be /form/type
        .state('form.type', {
            url: '/type',
            templateUrl: 'form-type.html'
        });

    // catch all route
    // send users to the form page 
    $urlRouterProvider.otherwise('/form/signup');
})

// our controller for the form
// =============================================================================
.controller('formController', function($scope) {

    // we will store all of our form data in this object
    $scope.formData = {};

    // function to process the form
    $scope.processForm = function() {
        alert('awesome!');
    };

});

test.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function ($scope) {

    $scope.user = {bankName: ''};

    $scope.banks = [{
        "name": "Bank A",
        "branches": [{
            "name": "Branch 1",
            "code": "1"
        }, {
            "name": "Branch 2",
            "code": "2"
        }]
    }, {
        "name": "Bank B",
        "branches": [{
            "name": "Branch 3",
            "code": "3"
        }, {
            "name": "Branch 4",
            "code": "4"
        }, {
            "name": "Branch 5",
            "code": "5"
        }]
    }];

});

Proper Code or Design Pattern to select combination of items from an enum

I want to select multiple items from a enum based on the some of parameters. So, for example suppose I have an enum named Animal

public enum Animal
{
   [DisplayName("Dog")]
   Dog,
   [DisplayName("Cat")]
   Cat,
   [DisplayName("Mouse")]
   Mouse,
   [DisplayName("Ant")]
   Ant,
   [DisplayName("Monkey")]
   Monkey
}

And I want to get only specific items from this enum based on the parameter, so if my parameter is "FourLegged" I should get Dog, Cat, Mouse, for other parameter I should get different set. And there could be multiple combination of enum and parameters, I can pass one or more pararmeter to get related items from the enum.

What should be the best/proper way to implement this? Is there any code or design pattern to implement this? It can be other approach than using enum.

mercredi 24 mai 2017

PHP MVC Multiple databases, multiple data mappers?

I am working on my HMVC project.

Right now I am using data mappers in order to move data between the models (domain objects) and a MySQL database. Each mapper receives a MySQL adapter as dependency. The injected adapter receives a PDO instance (a database connection) as dependency and runs sql queries on the database.

I also use a dependency injection container (Auryn).

I'd like to be able to simultaneously retrieve data from storages of different types (MySQL database, PostgreSQL database, XML feeds, etc).

Let's say, I want to retrieve User data from a PostgreSQL database (by using PDO data-access abstraction), to change it, and to save it into a MySQL database (by using mysqli data-access abstraction) on another server.

My question is:

Should I create a different mapper for each storage type (like

UserMapperPgsql(PgsqlAdapter $adapter) 
UserMapperMySql(MySqlAdapter $adapter)

), or should I create only one mapper with more adapters (one for each data type) as dependencies (like

UserMapper(PgsqlAdapter $adapter1, MySqlAdapter $adapter2, ...)

)?

Thank you all for your suggestions!

VBA validate list of emails using pattern

I have got list of emails in a cell separated by semi-colons and space but i have got the pattern which validates emails only if they are separated by semi-colons. Where do I insert the space to fit my pattern?

Example of emails: aaa@bbb.com; ccc@eee.com; fff@ggg.com

Amount of email addresses in a single cell varies from 1 to 20

Pattern validating emails separated by semi-colons:

^(([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+([;.](([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,5}){1,25})+)*$

Common methods and different constructors

I am working in custom MVC php web application. Here is what I have at this moment:

  • A class "CtrlBase" which all controllers should extend.
  • And because the application have 3 different parts (applications (I will use the word applications here)) that are independent from the user's point of view, but a lot of functionality is shared between the 3 apps I have a specific controller for each app that extends "CtrlBase": CtrlBaseAdmin, CtrlBaseCms, CtrlBaseWeb.

    • The main difference between the 3 different controllers that should be taken into account at this level is in the constructor.
    • I have a CRUD controller for users that has the same functionality in all 3 apps except that each extends the specific base controller depending on the app. This example code will illustrate it better:

    class Users extends CtrlBaseAdmin {

    public function __construct() {
        parent::__construct();
    }
    
    public function index()
    {
        .
        .
        .
    }
    
    public function edit()
    {
        .
        .
        .
    }
    .
    .
    .
    
    

    }

All the methods: index, edit, add, and delete are the same for all three apps but the parent constructor id different and all the controllers of the same app extend the same parent controller.

So my question is how to avoid this code duplication?

Thank you

Which design pattern use when different libraries to create a Spreadsheet?

In my controller class I just want to use only one spreadsheet class to handle all the functions related to spreadsheet creation, save, load, write etc.

Currently I'm using one open source library phpspreadsheet to create a spreadsheet, if later I want to change that to another library of spreadsheet creation, I don't want to change much on the controller class, instead, I can create another class for this library, like Spreadsheetlib2. So which design pattern is better to use here? "Bridge" or Adapter?

// Bridge Pattern what I'm trying now.

interface SpreadsheetInterface {

    public function create();

    public function write();

}


class Spreadsheet extends AbstractSpreadsheet {

    public function create() {

    }
}



class PhpSpreadsheet implements SpreadsheetInterface {

    public function create() {

    }
}


abstract class AbstractSpreadsheet {

    protected $spreadsheet;

    protected function __construct(SpreadsheetInterface $spreadsheet) {
        $this->spreadsheet = $spreadsheet;
    }
}

Inserting the value in data frame into the codes in R

I have the names of the 1000 people in "name" data frame

df=c("John","Smith", .... "Machine") 

I have the 1000 data frames for each person. (e.g., a1~a1000) And, I have the following codes.

a1$name="XXXX"
a2$name="XXXX" ...
a1000$name="XXXX"

I would like to replace "XXXX" in the above codes with the values in name data frame. Output codes would look like this.

a1$name="John"
a2$name="Smith" ...
a1000$name="Machine"

Decorator Design Patter, Segmentation fault

I want to implement the Decorator design pattern. However, my code gives me Segmentation fault error. I tried to compile it using the -g flag and then check it with gdb. gdb shows only that the error is somewhere inside the action method, but I do not understand where and why.

#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

class CComponent
{
protected:
    int * i_array;
    int i_size;
public:
    CComponent(int i_size)
    {
        this->i_size=i_size;
        i_array= new int[i_size];
        for(int i=0; i<i_size; i++)
        {
            i_array[i]=0;
        }
    }
    virtual int action() = 0;
    ~CComponent()
    {
        delete i_array;
    }
    int get_i_size()
    {
        return i_size;
    }
    int get_array_at(int index)
    {
        return i_array[index];
    }
};

class CConcreteCComponent : public CComponent
{

public:

    CConcreteCComponent(int i_size) : CComponent(i_size) { }

    int action()
    {
        for(int i=0; i<i_size; i++)
        {
            i_array[i] = rand() % 100;
            cout<< i_array[i] << " " << endl;
        }
        return 0;
    }
};

class Decorator : public CComponent
{
protected:
    CComponent * c;
public:
    Decorator(int i_size) : CComponent(i_size)
    {
        c = new CConcreteCComponent(100);
    }
    int action()
    {
        return c->action();
    }
};

class CConcreteDecorator3 : public Decorator
{

public:
    CConcreteDecorator3(int i_size) : Decorator(i_size)
    {
    }

    int action()
    {
        int w = action();
        for(int i=0; i<c->get_i_size(); i++)
            if(c->get_array_at(i) % 2 == 0)
                return w;
        return w + 50;
    }
};

class CConcreteDecorator1 : public Decorator
{
public:
    CConcreteDecorator1(int i_size) : Decorator(i_size)
    {
    }

    int action()
    {
        int w = action();

        if(c->get_array_at(0) == 0 && c->get_array_at(i_size -1) == 0)
            return w + 100;
        return w;

    }

};

class CConcreteDecorator2 : public Decorator
{
public:
    CConcreteDecorator2(int i_size) : Decorator(i_size)
    {
    }

    int action()
    {
        int w = action();

        if(c->get_i_size() > 7)
            return w + 150;
        return w;
    }

};

int main()
{
    Decorator * d = new CConcreteDecorator3(100);
    Decorator * d2 = new CConcreteDecorator1(100);
    Decorator * d3 = new CConcreteDecorator2(100);
    int res;

    res = d->action();
    cout << "res :" << res << endl;

    return 0;
}

mardi 23 mai 2017

factory design pattern, parent = new child()

When I'm using the factory pattern, i am confused with how to make child classes from it when the child has extra properties/methods. The factory returns the parent type as it works out which child to make but when this happens i cant use what it returns like a child class.

public abstract class Factory 
{
        public abstract Person getPerson(string type);
}

public class PersonFactory : Factory
{
        public override Person getPerson(string type) {
               switch (type) {
                      case "admin": 
                             return new Admin();
                      case "customer": 
                             return new Customer();
                      default: 
                             return new Admin();
               }
        }
}


public abstract class Person
{
        public abstract string Type { get; }
        private int _id;

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }
}

public class Admin : Person
{
        private string _securityRole;

        public Admin()
        {
            Id = 0;
        }

        public override string Type
        {
            get{
                return "admin";
            }
        }

        public string SecurityRole
        {
            get { return _securityRole; }
            set { _securityRole = value; }
        }
}

So my question is, when i create a PersonFactory object and decide to use that factory to create other derived classes. I noticed that getPerson() returns Person and not actually type Admin or Customer. How can i make the factory create the child classes so that they are actually child objects?

Factory pf = new PersonFactory();
Person admin = pf.getPerson("admin");
admin.Id = 1;            // is fine
admin.SecurityRole       // cannot access

reduce Duck-typing phenomenon in entity-component-system

How to reduce Duck-typing phenomenon in entity-component-system?

Example

(These are pseudo code. Many things are simplified and omitted.)

There are 2 systems in my ECS :-

System_Projectile : manage all projectile and bullet aspect.
System_Physic : manage physic's component.

There are 2 components-type : Com_Projectile , Physics.

Sometimes, I find that it is nice to cache pointer to another entity in some certain component :- .

class Com_Projectile{
    public: Entity* basePhysic;
};

Here is how I currently change position of the Com_Projectile via its field : basePhysic.

class System_Projectile{
    public: void manage(Entity* projectile){
        Com_Projectile* comP = getComponent<Com_Projectile>(projectile);
        //suffer duck-typing at "comP->basePhysic"
        System_Physic::setVelocity(comP->basePhysic,Vec3(1,0,0));
    }
};

getComponent<> is a function to request a certain component from an entity.

Problem

The real program based on the above snippet works OK.
However, when coding, Com_Projectile::basePhysic suffer duck-typing.

  • I get no clues about basePhysic's type at all.
  • I have to be conscious about type of basePhysic.
  • Then, I have to recall name of system (System_Physic::) that can do a thing I want (setVelocity()).
  • There are a lot of indirection for my brain.

In my old days, when I use a lot of (deep) inheritance, it is much easier, like this :-

    basePhysic->setVelocity(Vec3(1,0,0));

I really miss the cute content assists that list all the functions that related to physics.

enter image description here

Question

How to reduce duck-typing in some certain part of ECS system?
More specifically, what is a design pattern to enable the cute content-assist again?

My current workaround is to let Com_Projectile cache Physic* basePhysic instead of Entity*, but it will promote unwanted (?) coupling.

class Com_Projectile{
    public: Physic* basePhysic; //edited from "Entity* basePhysic"
};

Design Pattern in java unrecognized

i had the question of what is the name of the design pattern of the code below.

FileInputStream fin = new FileInputStream("X.zip");  
BufferedInputStream bin = new BufferedInputStream(fin);
ZipInputStream zin = new ZipInputStream(bin);

can anyone help me ? thanks.

How far to take the single responsibility principle

Say i have a class like so:

class Config
{
   private $configA;
   private $configB;
   private $configC;
   private $configD;

   public function getConfigA(): string
   {
        return $this->confiA;
   }
   //...
}

In one sense this class has a single responsibility: managing config settings.

But in another sense it has lots of varying reasons to change: a config is renamed, new config added, config removed, return types changing, validation required on a config etc etc

Should there be a class for each config setting which would satisfy single responsibility or is that too far?

Design pattern, ordered set of string transformations

Is there a design pattern or strategy to deal with the following scenario:

3 different strategies for transforming strings through various different methods: decoding, decrypting, removing sections of the string at specific places, converting to array and so on.

Each strategy use different combinations of the possible transformation to achieve its end result on the string.

I have a class responsible for each transformation for example: Decoder, Decrypter, Splicer and so on. And I have 3 concrete classes that have the transformers it requires injected into its constructor.

Is there an accepted design pattern for this problem. I feel that there is a more elegant way to achieve this but cannot see it

How can I realise the Microservices Pattern with React?

I am wondering how I could use the Microservices pattern with my React application. I understand that this pattern 'splits' an application into many small applications as it were.

I thought that I could split my NodeJS REST API into different, separate processes, to which my React App connects. E.g. one only to get some user data, one API to handle authentication - would this make sense?

Apart from this, I was thinking how I could apply this pattern to React. I am splitting my React application into different Components, but would this component-split already count as a microservice? I would not think so since there are no separate running processes. How could I separate my React App into microservices and apply this pattern? Or is a wrong application of the microservices pattern?

I hope I am not misunderstanding the whole concept, I am just starting out and would really appreciate some guidance with this pattern & my React/electron/nodejs amibitions!

WPF controls and C# patterns

I have a slider. I also have three buttons. Each button it titled as follows, respectively: "Cesius", "Fahrenheit", "Kelvin".

I thought to implement a factory pattern in an interface and then have three separate classes called toCelsius, toFahrenheit, toKelvin.

However, I realized that I might need to add some other kind of temperature measure, a fourth kind of unit, a fifth kind of unit, etc (i.e. a fourth button, a fifth button, etc).

So I would need to alter the interface. I would also need to add to each separate Class and to cater for the new additional units.

Is there a more elegant pattern I could use, instead of factory?

I'm teaching myself C# and it goes slowly. I'd appreciate you pointing me in the right direction so I can do some research on the suggested pattern to use.

Thanks.

Strategy pattern movies conditionals from inside the main class to the client code, so what's the point?

I am trying to understand the strategy pattern, here is an example, we have a Customer that has a method GetDiscount, this method is written as follows

GetDiscount
    If (Condition1)
        Return 10%
    else (Condition2)
        Return 20%

Now I have refactored the code using the strategy pattern so it becomes

GetDiscount
     Invoke the attached strategy

And we create two strategy class 10%Strategy and 20%Strategy to encapsulate the behavior of the discount

And for the client code to use the customer class it becomes

c = new Customer

if(condition1)
c.attach(10%Strategy)
else (condition2)
c.attach(20%Strategy)

c.GetDiscount

So as you can see we have moved the conditionals from inside Customer class into the client code, not only this, but this conditional branching itself is considered a business logic and we let it to leak into client code that might be a presentation controller for example.

Am I missing something?

Interfaces without methods vs fields

I have two classes, LivingCreature ,and Animal which inherits from it.

I want to implement a class for each existing Animal, but since different animals share lots of features, I want to be able to classify Animals into several categories: Flying, Walking, Swimming, Carnivore, Vegeterian and so on...

Every animal can reside in several, even from the same area, for example Flying, Walking and Carnivore.

Also, each category may hold several unique attributes, for example a flying animal should consist speed and eating type (e.g. whether it sits on a tree picking worms, or "raiding" the earth and picking animals with its legs)

The First thing that I definitely want to avoid is to hold a different set of fields for each concrete animal implementation.

Now, since some categories are simply binary (Carnivore or Vegan) and some are definitely not, I wonder what would be the right way to implement it.

I tend to go towards interfaces for each category, even if they won't be holding any methods , but I'm encountering a conflict:

  • It looks odd to hold an interface for such simple use like isMeatEating which holds a single boolean field.
  • On the other hand, having several categories as Animal's fields and several others implemented as Interfaces, sound very wrong and confusing.

What would be the correct/best option here, design-wise? (Perhaps there's a design pattern which matches this use-case)

Best way to evolve library with method returning enum type as response

I have a .NET library i have to evolve. It has some methods that return a enum as response . For example:

    //v1.0
    public enum Vehicle
    {
        Truck,
        Mini,
        Superbike
    }

    public Vehicle getCar(){
        ...
        return Vehicle.XXX;
    }

In version 2.0 I want to define more Vehicles, so it gets something like this:

   //v 2.0
    public enum Vehicle
    {
        Truck,
        Mini,
        Superbike,
        WaterBike
    }

    public Vehicle getCar(){
        ...
        return Vehicle.XXX;
    }

Many other apps are using this library , so i don't want to break compatibility backwards. I need to migrate (just replace) the library from 1.0 to 2.0 in all the applications without breaking anything. Considering a new type will be returned in getCar() method, old code in the apps will not understand that.

How do you propose to evolve the library? It`s a design question.

PHP Design Patterns Workbook?

Good evening.

I'm looking for "Design Patterns in PHP Workbook" with the tasks from the real project and solutions based on design patterns.

For example something like this one: http://ift.tt/2rc279S or this one: http://ift.tt/2rLkOyc

I know that there are a lot of articles and books about patterns. Great books and articles. However, almost each article contains examples based on really abstract things like how to build Snowman using Builder or how to cook Pizza using Abstract Factory and so on. In addition to that, there are lots of examples from the C++ or Java world that not relevant to the PHP world and tasks at all that's why these examples more mislead learners than help.

I'd like to collect these examples in one place in order to "create" workbook (if there isn't any).

Thanks in advance for your answers.

Bridge pattern different implementation by type

I searched examples for bridge pattern and bellow example explains design pattern very well but i have one question about bellow example.What should i do for example if manual gear handleGear method differs for Car and Truck or auto gear handleGear implementation differs for Car or Truck? Could you please provide example code for this situation?

/* Implementor interface*/
interface Gear{
    void handleGear();
}

/* Concrete Implementor - 1 */
class ManualGear implements Gear{
    public void handleGear(){
        System.out.println("Manual gear");
    }
}
/* Concrete Implementor - 2 */
class AutoGear implements Gear{
    public void handleGear(){
        System.out.println("Auto gear");
    }
}
/* Abstraction (abstract class) */
abstract class Vehicle {
    Gear gear;
    public Vehicle(Gear gear){
        this.gear = gear;
    }
    abstract void addGear();
}
/* RefinedAbstraction - 1*/
class Car extends Vehicle{
    public Car(Gear gear){
        super(gear);
        // initialize various other Car components to make the car
    }
    public void addGear(){
        System.out.print("Car handles ");
        gear.handleGear();
    }
}
/* RefinedAbstraction - 2 */
class Truck extends Vehicle{
    public Truck(Gear gear){
        super(gear);
        // initialize various other Truck components to make the car
    }
    public void addGear(){
        System.out.print("Truck handles " );
        gear.handleGear();
    }
}
/* Client program */
public class BridgeDemo {    
    public static void main(String args[]){
        Gear gear = new ManualGear();
        Vehicle vehicle = new Car(gear);
        vehicle.addGear();

        gear = new AutoGear();
        vehicle = new Car(gear);
        vehicle.addGear();

        gear = new ManualGear();
        vehicle = new Truck(gear);
        vehicle.addGear();

        gear = new AutoGear();
        vehicle = new Truck(gear);
        vehicle.addGear();
    }
}

lundi 22 mai 2017

Utilizing a Generic Repository Interface

I've seen various uses of the repository pattern. I'm leaning toward a pattern that I see far less frequently, and I'm wondering if there is a good reason for that.

Pattern 1: Access the Repo through the business object by injecting into the Constructor

        Class Teacher : IPerson
        {
            Private IRepository myRepository;

            Internal Teacher(IRepostory repo){
                This.myRepository = repo;
            }

            Public overrides void Save(){
                Repo.Save(this);
            }
        }

example:

 IPerson p = DataAccess.GetPersonFromId(id);
 p.Name = "Bill";
 p.Save();

Benefits

  1. The constructor will be internal and access only by a factory pattern, so I'm not worried about the complexity here.
  2. IPerson forces an implementation of Save() method but teacher does not need to know how it's being persisted
  3. Works similar to an Entity Framework Proxy object
  4. I can call Save() on an Iperson object without needing to know its an invoice
  5. Application -> Business Object -> Repository seems like the logical dependency structure.

Cons

  1. The business objects are not Plain Old C# objects anymore.

  2. Any changes to the entity repository are likely going to need to change the "Person" interface.

  3. Should I be applying the same pattern with an IFactory? Do we keep injecting services?

Pattern 2: Access Directly

        IPerson p = DataAccess.GetPersonFromId(id);
        IRepostory repo = DataAccess.GetRepositority()
        p.Name = "Bill";
        repo.Save(p);

Benefits

  1. Seems like the simpler way to do things.

Cons

  1. I can't very well make use of a generic repository that can be used for all derived types. I would like to use an Irepository interface that can take a Person Type and know how to persist it.

Summary

I was leaning toward pattern 1, but almost every example I see out there uses a version of Pattern 2.

The main goal is that I don't want to be using TeacherRepository anywhere in the Application Layer. I would like to rely entirely on IRepository. However, It doesn't look like I can do that in Pattern 2, because Save() needs to know its dealing with a Teacher to properly persist the data.

Are there any unique other patterns that could allow me to work with a generic repository?