vendredi 31 mars 2017

Should we separate the ssis packages between several projects in our Solution?

I use SSIS2012. I have created three schema in my Data warehouse(STG, TRSF, DW).

The STG schema is for staging tables. All my source file are the CSV files. I am transferring the data from my source to each table in stg schema. I have a separate package for each tables (For example: If i have 20 csv files, I will have 20 packages and i will populate 20 tables in stg schema)

After that, I am transfering stg schema to trsf schema. During those process i have my business. I do lookup for FK and other business rules will be applied in this level. The same as privious example if I have 20 tables in stg schema, I will have 20 packages and I will fill 20 tables in trsf schema

In third step I will transfer the data from trsf schema to dw schema. Here also I have 20 packages.

At end, I will have 20 package for cleaning the tables in stg schema.

I create 4 packages for each transformation between csv files and the tables in dw schema.

I would like to know if it is good idea to create 4 seprate project for each step? Because now, I have 80 packages in one project and it can be grow up more.

Turtle graphics in python bringing me to a halt

So i have worked with several different functions within the limits of my python program, i have 3.5, but i keep hitting roadblocks and have multiple questions, first, i should explain that i have trouble learning things sometimes (due to learning disabilities) BUT, once i have learned something i dont forget it and it usually just takes different methods of explanation for me to understand/grasp the concepts. So, with that in mind, most of the tutorial information for 'installing a module for importing' i am not understanding on here, i think i need like a step by step info page but when i try and just do things from what i have seen, my computer is not doing them. i was able to get turtle installed somehow, though beforehand i had trouble installing tkinter on its own, of course now that is working. I am trying to create a program for random graphics within a controlled environment, so instead of just a program that scribbles, i have a program that designs its own images and shapes, but at random, where i never will have the same run twice, and i never will know what it is producing ahead of time. kind of like those adult coloring book pages will look. i have a turtle screen that currently is producing such images, but i cannot get the output canvases to save, for some reason, though i know they will only be in postscript if i can get them. secondly, i would like to save them and be able to recall the image that is created, for later use with another/other programs. i am working on this so that i can use them for another purpose once they have been output. the modules that my computer seems to stubbornly NOT want to work with, include matplotlib, pylab, (scipy??), (not sure if i spelled that one right or if its backwards), and some other simple number python functions like that. also, for whatever reason, within the limits of the previously explained program, the one that creates a randomized design, i have not been able to successfully define the created shapes for duplication onscreen. i was trying to see first about saving the image to a file to recall before, but then when i could not get the images to be recalled without them being on a webpage first, then i just tried to get it to duplicate within the program. it is not working within the settings of a 'begin_poly' to 'end_poly' when i ask it to 'get_poly', it does nothing and will not create the same shape again elsewhere on the page. so i can either try and get it to do THAT or i can try and save and recall an image and, say use the recalled image in other ways to create a larger and overall 'bigger picture'. these are some of the limitations i have come across and i know, absolutely no one, near me who works with python. so i am struggling trying to understand some of the stuff i am finding online, obviously i am a bit new to the language, however, when i start picking things up and understanding them, i love all of the things that programming has opened up for me to do! it makes ideas that i have in my head, a lot easier for me to put on-screen for others to see visually what i am thinking, rather than trying to explain verbally.. any help is much appreciated here.

C++ | For what exactly are boost.bind and boost.shared_ptr useful?

Yesterday i used boost libraries for the first time. I was told by a teacher to learn Observer design pattern. Then somewhere i read that in C++ you use Boost::Signals2 for the implementation of the pattern.

Then learning to use Boost::Signals2 i had to learn what is and how to use Boost::bind. But in order to use it i had to use and learn Boost::shared_ptr...

This is my code:

#include <iostream>
#include <boost/signals2.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>

using namespace boost;
using namespace std;

class Animal {
    public:
        virtual ~Animal(){};

        virtual void talk(){};
    protected:
        string name;
};



class Mammal : public Animal {
    public:
        Mammal(string NAME);
        ~Mammal(){};

        void talk();
};

class Oviparous : public Animal {
    public:
        Oviparous(string NAME);
        ~Oviparous(){};

        void talk();
};

Mammal::Mammal(string NAME){ name = name;};
Oviparous::Oviparous(string NAME){ name = name;};
void Mammal::talk(){ cout<<"Meeeeeawww de: "<<name<<endl;};
void Oviparous::talk(){ cout<<"Wwwweeeeegh de: "<<name<<endl;};

int main(int argc, char * argv[]){

    signals2::signal<void ()> sig;

    Oviparous * animal2 = new Oviparous("Serpiente");
    Mammal * animal = new Mammal("Perro");
    shared_ptr<Mammal> animal3(new Mammal("Vaca"));


    sig.connect(bind(&Mammal::talk,animal));
    sig.connect(bind(&Oviparous::talk,animal2));
    sig.connect(bind(&Mammal::talk,animal3));
    sig();
    return 0;
};

The output is:

Meeeeeawww de: Perro
Wwwweeeeegh de: Serpiente 
Meeeeeawww de: Vaca

This code was a test to see if i can use boost.signals without using boost.shared_ptr, and i was able to. I would like if someone can explain me why is shared_ptr better than a normal pointer. Also, i dont totally understand boost.bind... if i had to explain what it does, i would say that it associates a class method with an instanced object ( i know this is really vague, and boost.bind can do a lot more than that, but i simply dont understand that much of it).

TL;DR: why is shared_ptr better than a normal pointer? what does boost.bind do?

Does the null object pattern make debugging more complicated?

I was wondering if the null object pattern could actually make debugging more difficult in certain cases. For example, if a method returns an "empty" object rather than a null then it will not throw an error. This is good in terms of reliable, clean code but couldn't it mean that there is now an empty object being used that essentially does nothing that could cause unexpected bugs. Rather than having a null exception to point the programmer to the problem there is now nothing to help locate it.

Java: design-pattern for building certain columns in certain order

I have a table with N columns (up to 20-25). The list of columns (columns and their order) is set by user. So this list is unknown in code writing time.

I have the following solution:

class abstract AbstractColumnBuilder{

  public TableColumn buildColumnA(){...}

  public TableColumn buildColumnB(){...}

  public TableColumn buildColumnC(){...}

  public TableColumn buildColumn(String columnName){
     switch(columnName){
         case "a":return buildColumnA();
         case "b":return buildColumnB();
         case "c":return buildColumnC();
     }
     return null;
  }
}

class ConcreteColumnBuilder extends AsbtractColumnBuilder{

 public TableColumn buildColumnD(){...}

 public TableColumn buildColumnE(){...}

 @Override
 public TableColumn buildColumn(String columnName){
     switch(columnName){
         case "d":return buildColumnD();
         case "e":return buildColumnE();
         default:return super.buildColumn(columnName);
     }
     return null;
  }
}

and the usage

List<String>columnNames=...
for(String columnName:columnNames){
   TableColumn column=builder.buildColumn(columnName);
}

However, I don't like this solution. First of all it seems to me it is not very good from perfomance point of view - we need to make long case check in loop. Secondly developer can forget to override buildColumn method.

Is there any patterns for such case?

Regarding an usage of Chain of Responsibility

In the book Design Patterns : Elements of reusable object oriented software it is mentioned that Chain of Responsibility pattern can be used to let components access global properties through their parents. Can someone please enlighten me on this usage of the pattern?

jeudi 30 mars 2017

Dependency injection in object hierarchy

I've a class diagram like this:

       TopClass
       ◆      ◆
       |      |
  SubClass1   SubClass2
  ◆       ◆
  |       |
  |       ChildClass2
  |
  ChildClass1

TopClass has SubClass1 and SubClass2. Subclass1 has ChildClass1 and ChildClass2.

I use dependency injection on each of these classes. So when ChildClass1 needs interface X I need to pass X thru TopClass and Subclass1. When ChildClass2 needs Y I also need to pass it thru whole hierarchy. Eventually I end up with TopClass full of dependencies to interfaces it actually doesn't use. I find it smelly.

I've found an article about facade pattern which seemd promising but eventually I cannot find a way to use it in my situation.

Any other idea? And I wouldn't like to use singleton or any similar solution as I need to be able to unit tests these classes easily.

C#: "The Decorator Design Pattern: What is meant by adding functionality?"

I have just gone into studying the Decorator Design Pattern using C#.

I have made an example which kinda functions as i think it is intended except for one thing.

I kinda understood that the whole point of the pattern is to add functionality to an object dynamicly.

So when i create an object like this:

Inventory a = new Ashbringer(new TravelersBagpack());
a.Execute();

Then i kinda expected that the point was that the a object would now be able to call the Execute() method which only exists in the Ashbringer class. Thus adding functionality to the a object.

Though this i can't do without adding the Execute() method to the Inventory interface which would ultimately mean i would have to implement the Execute() method to all the classes implementing Inventory Interface or the abstract Decorator.

Perhaps there is a thing or two i don't know about interfaces or perhaps i miss understand the point of the Decorator Design Pattern?

When to use Class methods over Activities?

I'm getting introduced to Android programming and want to understand Activities a bit more (I'm coming in with basic-advanced java knowledge, basic knowledge in GUIs).

I currently assume that all methods will be contained in their respective activity, or in some helper class--whose methods wouldn't be shown to the user, (unless an activity used it), but whose methods could perhaps be used in multiple activities.

  1. Are these assumptions correct?
  2. When are helper classes even required?

  3. Any good online resources regarding (specifically) classes vs activity use cases?

  4. Any examples of a fairly simple, complete APK where I could look through and dissect the code, including XML? Hopefully something I could just import into Android Studio.

Thanks!

Mapping DTO to DTO pattern

I'm going to map a big DTO coming from a rest service to another different big DTO.
The two DTOs are different but semantically they are the same.
I'm looking for a pattern and i would like to implement the mapper using a TDD approach.
Ideally i want one or more test for one field-to-field mapping operation.

The problem

public class DestinationDTO {
    public int Id {get;set;}
    public string FieldA {get;set;}
    public SubObjectDTO SubObjectDTO {get;set;}
    public AnotherObjectDTO AnotherObjectDTO {get;set;}
    public ICollection<string> MyArray {get;set;}

} 

public class SourceDTO {
    public int Id {get;set;}
    public SourceObjectDTO {get;set;}
    public AnotherSourceObject {get;set;}
}

// perform the mapper invocation given the sourceDTO
public class MapperConsumer {
    public DestinationDTO MapIntoDestination(SourceDTO sourceDTO){
        var myMapper = new Mapper();
        DestinationDTO mapped = myMapper(sourceDTO);
        return mapped;
    }
}

My solution

The only approach I can figure out is to have and after inject an Interface that is responsible for handle the mapping of only one field, but this will increase the complexity of my project and the complexity of the root mapper (because i will need to inject 100 interfaces).

public class Mapper {
     private readonly IFieldAMapper _fieldAMapper;
     private readonly ISubObjectMapper _subObjectMapper;
     /*
     // ... other injected mappers
     */

     public Mapper(IFieldAMapper fieldAMapper, 
                   ISubObjectMapper subObjectMapper, 
                  /*
                  // ... injected other mappers
                  */)
     } 

     public DestinationDTO map(SourceDTO sourceDTO) {
            DestinationDTO dest = new DestionationDTO();
            dest.FieldA = _fieldAMapper.map(sourceDTO);
            dest.SubObjectDTO = _subObjectMapper.map(sourceDTO);
            /*
            // ... invoke the mappers for all fields
            */

            //finally return the builded DTO
            return destDTO;
     }



}

public class FieldAMapper : IFieldAMapper {
    public string map(SourceDTO sourceDTO){
        if(sourceDTO.SubObjectDTO != null){
            return sourceDTO.SubObjectDTO.SourceProperty;
        }
        return "DefaultValueForFieldA";
    }
}

My reviewed solution

Now i come back with my initial idea and i'm creating an IMapper only for handle the SubObjects mapping and mapping the primitive fields inside the map method.

The question

How do you handle this kind of problems ? Do you know a best practices or a pattern for this kind of problem ?

What is the simplest way in C++ to get and continue to call a class method, the type of which the current class does not know?

Example: Suppose we are developing a simple graphical interface:

We have windows and controls. What do we want:

  • There is a base window class that implements the GUI functionality hidden from the user.
  • From the base window, the user inherits a specific window.
  • There is a class of a button, an instance of which the user can add to his window.
  • The user can transfer the method of his window, and he will be executed when clicking this button.

I'm interested in how to reach the last point.

Kind of pseudo-code:

class BaseWindow;

class Button
{
public:
            Button(BaseWindow* parent)
            {
                        parent->AddButton(this);
            }

            void SetBehavior(/*Owners pointer and owner's methos*/)
            {
                        /* Save Owner pointer and owner's method*/
            }

            void Clicked(/*coords*/)
            {
                        if(/*coords == my coords*/)
                        {
                                    /*Call Owner's method*/
                        }
            }
};

class BaseWindow
{
            vector<Button*> Buttons;

            WindowClicked(/*coords*/)
            {
                    for(auto i:Buttons)
                    {
                                i->Clicked(/*coords*/);
                    }
            }

public:
            void AddButton(Button* butt)
            {
                            Buttons<<butt;
            }

};

class UserWindow:public BaseWindow
{
            Button MyButton;
public:
            void FunctionForButton(Button* butt){ cout<<"Say Hello, my sweet button";}

            UserWindow():MyButton(this)
            {
                        MyButton.SetBehavior(/*Put here my Function for Button and my pointer*/);
            }
};

Design Patterns for a SuperMarket system

I'm a Software Developer I who is beginning to think like a Software Developer II. I am tasked with a relatively simple Use Case for a coding challenge following as part of an interview:build a Supermarket Pricing System.

Rules and Requirements: Each item at Super Foods is identified by a unique four-digit code. Today, pricing schemes at Super Foods use the following pricing categories, but beware: prices are constantly changing, and the sales department is always creating new incentives and deals, such as buy one-get-one free.

EG: Chips and salsa (items #6732 and #4900) cost $4.99 together, but they cost $2.49 and $3.49 alone, respectively.

EG2: Buy two toothbrushes $1.99 each, get one free.

EG3: A bottle of wine (item #0923) costs $15.49 and is taxed an additional 9.25%

Having read through Design Patterns, this looks like a natural place for some form of Decorator Pattern for totaling the sales of objects. A SQLite database, with schema <ID, ObjectName, Price> will also be useful somehow, though I'm rusty on how we go about making the data access objects in all this.

I'm trying to wrap my mind around this in a full stack MVC mindset, I feel like I might be rusty on something. Is this what the Spring Framework is renowned for? Maybe an even better API for this use case can be recommended?

Thank you for anyone helping me to brainstorm the design of this system out.

Can I have entity as one of the value in DTO

I need to pass few data between layers of my application and within layer.I have defined DTO to do this. My question is can I have my domain entity is one of Value in my DTO.Is it good design?

In below code UserEntity is JPA entity.

UserDTO.java

private UserEntity userEntity;

private String empNo;

private String place;

Giving database context to object Factory

There is a question I always ask myself when I'm using a Factory pattern inside my code (C#, but it applies to any language I suppose).

I have a "Service" that takes care of interacting with my database, do stuff with objects and interacts with my object model.

This Service uses a Factory sometimes to delegate the instanciation of an object. But this factory obviously needs to interact by itself with the database to instanciate my object properly. Is it a good/bad practice to pass the Database context to the Create method for example?

Like this :

var myNewObject = MyFactory.Create(myDatabaseContext);

the other way would be to let the Service always be the only one to talk with the database.

var myNewObject = MyFactory.Create();
var extraProperty = myDatabaseContext.Get(something);
myNewObject.extraProp = extraProperty;

Any advices?

How to build a design taxonomy in CSS for Developers to use in build

I'm wondering if anyone has a suggestion for easily providing an editable taxonomy of basic HTML elements, in much the same way as Fabricator seems to provide, but with Bootstrap in mind, and with an eye to allowing Designers, rather than Developers, to actually decide on any visual changes.

I've been thinking about providing something like a live edit and sass watch so that they can realtime things, and they'd then simply git push to push this on to the dev team

We're currently on the cusp of building out a new site in A.N.Other (TBC) CMS, and beginning to provide discovery with the client in terms of UX workshopping etc, so I'd quite like to be able to get output from the project that would enable Dev team to have clearly defined elements for use, so that we've got pretty much a working UI Taxonomy that they can pick and choose straight away, once a choice of CMS has been made.

I've been looking at some Atomic Design pattern stuff from Brad Frost, which is really interesting, as well as doing a little digging into Fabricator.

Any direction as to whether Fabricator can achieve this for a responsive / bootstrap site would be great, but also any other frameworks that anyone can suggest might be useful.

Design Pattern to use existing classes

I am at the moment struggling with which design pattern should I use. My situation is as follows:

  1. I have a few existing classes e.g. Address, Client and Invoices.

  2. I need to create a class let's say a javabean that comprises possibly all fields from above mentioned classes as its getters and setters.

  3. Later on, I can create a object of the javabean and assign it to a Jasperreport as its datasource.

Can anyone suggest me which design pattern would ease my job as I don't want to reinvent the wheel? Thank you.

How should I approach for creating a command-line parser in java?

Hi I want to create my own command-line parser using java. As you might know, the design of this parser can be in a lot of ways.

I found this http://jcommander.org/ but this seems more complex than I hoped.

I have more simple questions like;

  • What kind of data structures can i use to store options and parameters?
  • When I capture the commands, how should I execute them?

Can you give me something more in the starting stage. Can be a class design approach or some little library that you know.

C++ How to design a class that can take on only a discrete set of values, e.g. Red Green Blue

Say for example that we want to design a color class, assuming that we only allow for 3 different color values: Red, Green, Blue.

How is this generally achieved in C++? Or better what is the general design pattern for this?

The only way I could think of, is to initialize 3 different static colors in the Color class,, make the colourCode inaccessible and allow construction of a new Color only with an already existing one.

class Colour
{
public:
    static const Colour Red;
    static const Colour Green;
    static const Colour Blue;

    Colour(){}

    bool operator==(const Colour &other) const{
        if(other.colourCode == this->colourCode){return true;}else{return false;}
    }

    Colour & operator=(const Colour & other){
        this->colourCode = other.colourCode;
    }

    Colour(const Colour & other){
        *this = other;}

private:
    int colourCode;

    Colour(int colourCodeIn){
        colourCode = colourCodeIn;
    }
};

const Colour Colour::Red(1);
const Colour Colour::Green(2);
const Colour Colour::Blue(3);

class Pen
{
public:
    Pen(){}
    void setColour(const Colour & infarbe){
        farbe = infarbe;
    }
    Colour farbe;
};

int main()
{
    Pen myPen1;

    myPen1.setColour(Colour::Blue);

    return 0;
}

regex match file with multiple extension

I have several strings like this

XYZ_TEST_2017.txt

ASD_TEST_2017.txt.tmp

I need to extract only those strings with only .txt lasting

So I'm using this regex:

[A-Z]{3}TEST[0-9]{4}.txt

However I still get the strings with multiple extensions like the second one (.txt.tmp)

http://ift.tt/2oaZvHK

How can I handle it?

Thanks

Advice on how to go about returning an entity with many other related entities

I am building an application with ASP.NET Web Api. This application has a MessageController, which has methods that concern everything related to, you guessed it, the Message entity. This Message entity has many related entities.

My question is, when I request a certain Message, should I return a Message and all its related entities, even though they might not be needed?

Reading similar questions on this site, I know that the answer is 'it depends', but usually in favor for returning a graph instead of sending a request for each dependend entity associated with the main entity, because of possible network latency.

My choice could be that I make adding in the extra entities optional (I got this from a pluralsight course on WEB API by Shawn Wildermuth), but the problem here is that if I have a lot of related entities, the URL will become something like ?includeThis=true,includeThat=false,includeSmtElse=false,... which seems to me a bit overboard. Not to mention the parameterlist of my ActionMethod. Also, this would mean that in my repository, I would have a jungle of methods with names like GetMessageWithThisIncluded, GetMessageWithThatIncluded, GetMessageWithThisAndThatIncluded, etc.

Now, if this is a good idea, what could be some patterns I could use to make this manageable? I know this goes a bit more into technicalities, but how to solve having a general method in my repository from which I can include or exclude entitities with EF?

Another idea is to just always load the graph, and whatever I use I use, and whatever I don't use I don't. There's one caveat though; I want to make use of Angular2. I have not used Angular2 before, but from what I read and watched, is that you break up the application (or page) into modules, which in turn make use of services. But don't these services need to make use of the smallest json possible? I.e., if I pull in a graph, how would this work with the services? Can I distribute from the graph to the services?

Or,...? What could be some other idea that I could make us of? Maybe have the graph and just add the id's of the related entities, so that if the consumer needs a related entity, it could request it by sending the id to the appropriate endpoint?

Facade design pattern and close coupling

When learning Facade design pattern, everywhere I find this kind of examples:

public class SystemA
{
 public void CreateCreditCard(){//implementation}
 //other methods here
}

public class SystemB
{
 public void CheckCreditCard(){//implementation}
//other methods here
}

public class Facade
{
 SystemA subsystemA = new SystemA();
 SystemB subsystemB = new SystemB();

 public void CreateAccount()
 {
   subsystemA.CreateCreditCard();
   subsystemB.CheckCreditCard();
 }
}

I don't know if I'm wrong but doesn't it create close coupling between the Facade class and the Systems(SystemA and SystemB), even if SystemA and SystemB are inherited from some abstract class or interface.

microservices: User Authentication and Authorization

I am planning to use microservice architecture in my upcoming project. I am a bit not clear on which mechanism to use for user Authentication and Autorization.

I googled for the same and I understood there are some mechanisms like distributed DB based opaque token, end-to-end JWT token based and combination of opaque token and JWT token.

My primary authentication is OAuth2. User signin using OAuth2 and the tokens are received at backend (@redirect URI) and I store this token for further queries by user.

At first I wanted to use distributed DB based token mechanism as it seemed simple enough for my case (with backend in VPC, i am sure my db is secure enough), where I will generate a unique token(UTKN) and map this UTKN against tokens(Access and Refresh) received from OAuth2 and send this UTKN in cookie to the client( client can be mobile app or an embedded device or a desktop browser). For user logout, I simply delete my session cookie.

Reason Why I wanted to use extra UTKN rather than sending OAuth2 Access token directly in session cookie is I don't want AccessToken which is, in some cases, not opaque and which contain app or user info (in case of JWT kind of AccessTokens) to be visible.

When I came across AccessTokens received for OAuth2,in case of Microsoft O365, are JWT based tokens which I think they might use this token within their internal backend as is to get user data.

Apart from db security and db failure are there any disadvantage or drawbacks for using distributed db based session mechanism over other mechanisms?

What pattern is this using?

In order to add some behavior into onScroll event of ListView,I added some code by subclass ListView like this:

class MyListView extends ListView{
      public void setOnScrollListener(OnScrollListener listener){
            final OnScrollListener lis = new OnScrollListener(){
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                listener.onScrollStateChanged(view, scrollState);
                //below is added behavior of my Listview
                }
            }

        super.setOnScrollListener(lis);
      }
}

and the usage of it is simple:

MyListView myList = new MyListView(...);
myList.setOnScrollListener(new OnScrollListener(){...});//here is the old logic

this sounds like Decorator pattern but it is not, because there is no composite but only inheritance(in facto I do not need composite here).

So the problem is what should I call it?

mercredi 29 mars 2017

Best approach to replace iframes

Have an open ended question. I have a html form which contains multiple iframes with various urls as their sources (src attribute). My question is - 1. are there any risks in general to have iframes in a web page? Like I heard that MS edge doesn't support iframes as such - is that true? 2. What's the best approach( and why?) to replace these iframes considering the urls used as sources are not having their own API to be used?

P.S:- all the urls return html streams which are rendered within these iframes.

Looking for some directions here as I am pretty lost in here. Thanks in advance!

Arka

Replace Multiple If\Else with Design Pattern

Based on various threads on SO (ex. Replacing if else statement with pattern ) I understand that I can replace multiple if\else statements with the Command pattern.

My situation is a bit different.

I have a series of Commands and I need to execute each Command only if the previous command was unsuccessful.

For example, suppose I need to retrieve text from a hypothetical page - I could scrape the text directly from the page using screen scraping or I could fetch the text from the API. I would only want to fetch the text from API if screen scraping was not successful. In other words I would only execute the "fetch" command if the "scrape" command didn't work.

In this case, I would test if the scraped String is empty or equal to null and then execute the second Command. If the second command is also unsuccessful I would execute the third Command and so on.

The important point is that we only execute subsequent commands if a certain condition is true/false. The condition is always the same for each Command but the number of commands might grow in the future.

I cannot implement this via the typically suggested route (using a Map and Command interface) bec this would not execute the next Command if the first one failed (it would also be unable to check if a Command was successful or not)

What design pattern could be used to solve this problem?

Good database / code design for invoices / customers / adresses

I've been working on a project a lot lately and catch myself walking in to some challenges.

I'm wondering what a good way would be to setup a relational database, while keeping track of older records.

Currently I am using PHP, MySQL, ZF2 and a custom-ish ORM (it kind of grew).

The software I'm working on has a lot of information - Products, brands, customers, addresses, invoices and contracts. The thing is - I want the user to be able to edit customers and addresses, without losing track of the data that was initially set in created invoices and contracts (you can't edit contact information on contracts).

Currently, I have a "static" copy of most tables - once a contract goes to the "fixed" status, it can no longer be edited, and a copy of the customer's information is made into a static table of the customers.

This works, because now the client can still edit the customer without editing existing contracts, and we can still keep track of the underlaying relations between the data.

This however is getting kind of bulky and annoying - big tables - lots of data, basically I setup the static entity management a bit wrong.

Now I've been thinking about other ways to do this, also have been searching a lot, but could not find some proper answers (maybe I'm asking the wrong questions?)

So, what would be a good way to go? I am willing to use existing ORM code - I have been looking into Doctrine, but I'm not sure how to make the "static" copies without making it just as messy as it is now. Another method I've been thinking about was keeping track of changes in tables / rows, and using dates next to a reference to another table - so that you could look up what a value was on a specific date (that would work for invoices as well) - allthough I'm not sure what a solid and simple way would be to do so.

TL;DR: What is a good combination of practices, database design, and maybe frameworks / libraries, to setup a relational database where historical data will be preserved?

How to form a single API from these methods?

I have an interface with the following methods:

public ArrayList<ArrayList<Pair<Integer, Integer>>> getDataFormated(SomeEnum type);  


public ArrayList<ArrayList<Pair<Integer, String>>> getDataForInfo();  

The first method based on the type populates the return result correctly.
Both method are using the same data (which is basically a json file) to do their processing.

How would I make them into 1 method?
I could make the return result from the first method as ArrayList<ArrayList<Pair<Integer, String>>> since the integer can be converted back and forth to string as needed but seems to me error prone.
What would be an alternative? How could I use templates here or some other way?

Grep pattern from file (list) into same line

i have to files (see below) and want to grep the patterns (file 1) from file 2(2 columns). I think it is reallys easy but i could not find any clue how to grep the matches to the same line

File1
ABC
DEF
GHI

File 2
ABC SeqX
ABC SeqY
ABC SeqP
DEF SeqW
DEF SeqO
GHI SeqR
GHI Seql

The output should look like this:

    ABC SeqX SeqY SeqP
    DEF SeqW SeqO
    GHI SeqR Seql

I know it has to be something like: grep -f file 1 file2 > output

I will be gratefu for any help.

Design pattern - Models

In my application there is a model - Drug

class Drug{
  String drugId;
  String name;
  String strength;
}

this interface takes a drugId and returns the Drug Model

interface IProcessor{
Drug getDrug(String drugId);
}

// easy flow
class ProcessorA extends IProcessor{
protected Drug getDrug(String drugId){
  //get Drug from source A
  return Drug
}
}

// From source B, I will be getting additional fields. Am not sure how i can append the new fields to the drug Model

class ProcessorB extends IProcessor{
protected Drug getDrug(String drugId){
//get Drug from source B
// Add few more fields specific to B 
  return Drug
}
}

1) Extend the Drug model (class DrugB extends Drug) for ProcessorB and add the new fields. In this case, I might be ending up typecasting the DrugB. Is this ok?

2) Add the common fields to Drug Class and use it. This is fine, but number of fields for each type of processor could be increasing.

Is there any patterns I should be thinking of. Please advice.

Java 8: Automatically composite default methods of multiple interfaces

I have class implements multiple interfaces which have a same default default method. I am wondering how can I composite the default method from all the interfaces. For example:

interface IA { 
    default void process() { 
        // do something 
    }
}

interface IB { 
    default void process() { 
        // do something 
    }
}

interface IC { 
    default void process() { 
        // do something 
    }
}

// other similar interfaces
....    

class MyClass implements IA, IB, IC, ... {
    public void process() {
       // question: how to avoid iterate all the interfaces? 
       IA.super.process();       
       IB.super.process();
       IC.super.process();
       ...
    }
}

class AnotherClass implements IA, ID, IF, IH, ... {
    public void process() {
        IA.super.process();
        ID.super.process();
        IF.super.process();
        IH.super.process();
        ...
    }
}

I have to call IA.super, IB.super, IC.super explicitly. If the interface list is long it's painfully to write all of them. Also I may have different classes to implement different combination of interfaces. Is there other syntax sugar/design pattern/library that allows me to do it automatically?

Encapsulate the properties design pattern

I want to encapsulate the logic how a document is activated(boolean). When a document is activated it should be added to a list of activeDocuments and the flag should be set to true. I want to forbid the direct access to the isActive property.

class DocumentService {
      private activeDocuments : Map<DocumentModel> = new Map<DocumentModel>();

      // Activates the document and adds it to the list
      activateDocument(document: DocumentModel) {
                document.setActive();
                activeDocuments.set(document.id, document);
      }
}


class DocumentModel {
      private isActive: boolean;

      setActive() {
                this.isActive = true;
      }         
}

class DocumentComponent {
      documentSelected() {
           // this.document.setActive()  - SHOULD BE FORBIDDEN because the document is not added to the activedocument list !
           this.documentService.activateDocument(this.document);
      }
}

The only solution that i figured out for this problem is to create two interfaces DocumentServiceInterface that has a setActive() method and DocumentInterface that doesn't have it so it prevents the |DocumentComponent to activate the document but the service can still activate the document.

Is there a design pattern/ recipe that can solve this ?

mardi 28 mars 2017

Chain of responsibility design pattern configure chain without changing source code

I am working on chain of responsibility design pattern and here I want to configure that chain dynamically , means I should be able to set chain by using properties file or some constant file or without changing source code. And chain should work as I configured . Thanks .

What is the Regex for decimal numbers in Java?

I am not quite sure of what is the correct regex for the period in Java. Here are some of my attempts. Sadly, they all meant any character.

String regex = "[0-9]*[.]?[0-9]*";
String regex = "[0-9]*['.']?[0-9]*";
String regex = "[0-9]*["."]?[0-9]*";
String regex = "[0-9]*[\.]?[0-9]*";
String regex = "[0-9]*[\\.]?[0-9]*";
String regex = "[0-9]*.?[0-9]*";
String regex = "[0-9]*\.?[0-9]*";
String regex = "[0-9]*\\.?[0-9]*";

But what I want is the actual "." character itself. Anyone have an idea?

What I'm trying to do actually is to write out the regex for a non-negative real number (decimals allowed). So the possibilities are: 12.2, 3.7, 2., 0.3, .89, 19

String regex = "[0-9]*['.']?[0-9]*";
Pattern pattern = Pattern.compile(regex);

String x = "5p4";
Matcher matcher = pattern.matcher(x);
System.out.println(matcher.find());

The last line is supposed to print false but prints true anyway. I think my regex is wrong though.

Cordova API Back compatibility

I am trying to establish a interface to handle the back-compatibility in cordova existing as well as custom plugins. I have a few custom plugins, but as the new requirements and new devices are released in market, I need to tweak them. The native side and the non-native side talk to each other on this interface. I am looking for a way to be able to provide easy coding and switching between versions. For eg: If my non-native side is executing version 1 (sending string as a parameter to function call), but my native side (version 2) excepts a number , the app not work. So I am looking for a way to implement versioning such that I can pass in the version and will be able to accept a string even if my native side is on version 2, and vice a versa (if non-native side is at higher version, then it should auto detect the version of native api and send in the correct (datatype) parameter/default value).

Is there a name for a dependency graph that imitates a filesystem?

I find myself doing this when I write really big libraries in a dynamically-typed language and want to aggregate exported features near the root of the project. Doesn't have to be Node/JS, but here is an example filesystem for a Node project...

src/
    index.js -- imports A/index.js and B/index.js
    A/
        index.js -- imports X/index.js
        X/
            index.js -- imports foo.js and bar.js
            foo.js
            bar.js
        Y/
            index.js -- imports snafu.js and whatever.js
            snafu.js
            whatever.js
    B/
        index.js -- imports alpha.js and omega.js
        alpha.js
        omega.js

..where the exported library would imitate the filesystem:

const {
    A: {
        X: {
            foo,
            bar
        },
        Y: {
            snafu,
            whatever
        }
    },
    B: {
        alpha,
        omega
    }
} = require('lib');

Is there a name for this pattern?

Design pattern to implement Database operations

I am trying to implement design pattern in my project and have been reading material over net.

we have a sales application ( in C# ) where in we are storing entities like

Customer 
Contacts
Sales Order
Lead
Opportunity

This is how i am planning to implement design pattern.

Entity would be the base class and it has common variables

namespace DesignModel.Model
{
    class Entity
    {
        protected IDBOperation dbOperation;
        public string id { get; set; }
        public int isSync { get; set; }
        public string timestamp { get; set; }

        public void insert()
        {
            dbOperation.insertData();

        }

        public void update()
        {
            dbOperation.updateData();
        }
        public void delete()
        {
            dbOperation.deleteData();

        }
    }
}

Here is the Contact class that is extending Entity class. Contact class would have its own properties too.

namespace DesignModel.Model
{
    class Contact : Entity
    {
        public Contact()
        {
             dbOperation = new DBOperations();

        }
        public string name { get; set; }
        public string company { get; set; }
        public string jobtitle { get; set; }

    }
}

Now what i have derived from the nature of this application is each entity has following operations for database interaction and to fetch data from server.

for database operation

insert
update
delete

to get and send data from server

getData
sendData

based on that i have created an interface named IDBOperation

namespace DesignModel.Database
{
    interface IDBOperation<T>
    {
        void insertData(T entity) ;
        void updateData(T entity);
        void deleteData(T entity);

        void displayData();

    }
}

and concrete class DBOperations that implements IDBOperation

namespace DesignModel.Database
{
    class DBOperations : IDBOperation<Entity>

    {

        public void insertData(Entity e) {

            Debug.WriteLine("insertData "+e.id );

        }

        public void deleteData(Entity e)
        {
            Debug.WriteLine("deleteData" + e.id);

        }

        public void updateData(Entity e)
        {
            Debug.WriteLine("updateData" + e.id);

        }
        public void displayData()
        {

        }
    }

and at last Contact class

namespace DesignModel.Model
{
    class Contact : Entity
    {
        public Contact()
        {
             dbOperation = new DBOperations();

        }
        public string name { get; set; }
        public string company { get; set; }
        public string jobtitle { get; set; }

    }
}

i am using contact as follows

    Contact contactData = new Contact();
    contactData.id = "1234";
    contactData.isSync = 1;
    contactData.jobtitle = "Sales Manger";
    contactData.insert(contactData);

I am little confused where i have been implementing it correctly or not.

the reason why i kept implementation in DBOperation because if new interface method comes i have to implement it at one place oppose to if i am implementing method in customer, contact and sales order classes.

one thing that worries me is Entity parameter in insertData inside DBOperation not sure whether i will be able to add entire contact into db or not.

so if anyone help me in providing pointers to correctly implement the design pattern in this use case then it will me more helpful

Design for following situation having gtest procedure

In my current implementation i have 2 files (i am stuck and not getting any further)

//firstFile.cpp
class first
{
    //some object of xyz class
};

first f;  //global

TEST(Suite, Testcase
{
//do something
}



//secondFile.cpp
class second
{
public:
//some data members

void function()
}

Task :- I want to call TEST (consider it a special function, when it is called, object of first (i.e. global object defined will be created). In test i want to save some data for latter processing, which obviously i can't do in first class as it will be initialized on every TEST call.

Problem :- I though of having a separate class (in another .cpp file) which have required data structure to be saved. I want a way to access those data structure in TEST procedure and keep on adding the data over previous data with every TEST call. I can't have an object for second class in firstFile.cpp as it will also be created/destroyed on every call.

Any suggestion? Also i can't do anything about TEST procdedure, this is the way it is.

Snake Matrix Pattern

"Snake" Print NxN square matrix, filled with numbers 1,2,3,....NxN arranged according to following scheme. for example N=4

          1  2  6  7
          3  5  8  13
          4  9  12 14
          10 11 15 16

Hiding concrete nested types

I am trying to hide the following types from the end user.

//concrete.hpp
#include <iostream>
#include <vector>
using namespace std;

class Input
{
    public:
        int id;
        string note;
        Input():id(0),note("")  {}

        void printInput()
        {
            cout<<"Input id : "  << id <<endl;
            cout<<"Note :" << note <<endl;
        }

        void set(std::string &update,int id)
        {
            note = update;
            this->id = id;
        }

};

class Event
{
    public:
        int event;
        vector<Input> ins;

        Event():event(0)
        {

        }

        void printEvent()
        {
            cout<< "Event ID " << event <<endl;;
        }

        void addInput(Input &newInput)
        {
            ins.push_back(newInput);
        }

        Input& getInputAt(int index)
        {
            //ignore range check
            return ins[index];
        }
};

So my interface which certainly falls short is :

#include "concrete.hpp"

class InputI
{
public:
    virtual void printInput() =0;
    virtual void set(std::string &update,int id)=0;
};


class EventI
{
public:    
    virtual void printEvent() =0;
    virtual void addInput(InputI &newInput) =0;
    virtual InputI& getInputAt(int index)=0;
};


class InputImpl: public InputI , private Input
{   
    public:
    void printInput()
    {
        Input::printInput();
    }

    void set(std::string &update,int id)
    {
        Input::set(update,id);
    }
};

/*
class EventImpl: public EventI
{
public:
    void printEvent()
    {
        e.printEvent();
    }

    void addInput(InputI * newInput)
    {


    }

   InputI& getInputAt(int index)=0;    
private:
    Event e;    
};
*/




int main()
{
    std::string val("IN1");    
    InputI *inp = new InputImpl();
    inp->set(val,10);
    inp->printInput();
    inp->set(val,20);
    inp->printInput();
    return 0;
}

The problem here is i am unable to figure out how the EventImpl should be designed. Can any one point me in the right direction please.

Workflow System with Azure Table Storage

I have a system where we need to run a simple workflow. Example:

  1. On Jan 1st 08:15 trigger task A for object Z
  2. When triggered then run some code (implementation details not important)
  3. Schedule task B for object Z to run at Jan 3rd 10:25 (and so on)

The workflow itself is simple, but I need to run 500.000+ instances and that's the tricky part.

I know Windows Workflow Foundation and for that very same reason I have chosen not to use that.

My initial design would be to use Azure Table Storage and I would really appreciate some feedback on the design.

The system will consist of two tables

Table "Jobs"
  PartitionKey: ObjectId
  Rowkey: ProcessOn (UTC Ticks in reverse so that newest are on top)
  Attributes: State (Pending, Processed, Error, Skipped), etc...

Table "Timetable"
  PartitionKey: YYYYMMDD
  Rowkey: YYYYMMDDHHMM_<GUID>
  Attributes: Job_PartitionKey, Job_RowKey

The idea is that the runs table will have the complete history of jobs per object and the Timetable will have a list of all jobs to run in the future.

Some assumptions:

  • A job will never span more than one Object
  • There will only ever be one pending job per Object
  • The "job" is very lightweight e.g. posting a message to a queue

The system must be able to perform these tasks:

  • Execute pending jobs

    1. Query for all records in "Timetable" with a "partition <= Today" and "RowKey <= today"
    2. For each record (in parallel)
      1. Lookup job in Jobs table via PartitionKey and RowKey
      2. If "not exists" or State != Pending then skip
      3. Execute "logic". If fails => log and maybe do some retry logic
      4. Submit "Next run date in Timetable"
      5. Submit "Update State = Processed" and "New Job Record (next run)" as a single transaction
    3. When all are finished => Delete all processed Timetable records

    Concern: Only two of the three records modifications are in a transaction. Could this be overcome in any way?

  • Stop workflow Stop/pause workflow for Object Z

    1. Query top 1 jobs in Jobs table by PartitionKey
    2. If any AND State == Pending then update to "Cancelled"
    3. (No need to bother cleaning Timetable it will clean itself up "when time comes")
  • Start workflow

    1. Create Pending record in Jobs table
    2. Create record in Timetable

In terms of "executing the thing" I would be using a Azure Function or Scheduler-thing to execute the pending jobs every 5 minutes or so.

Any comments or suggestions would be highly appreciated.

Thanks!

Error mapping design pattern for Java [on hold]

I'm implementing an application, which receives around 70 error messages or codes from another depending application. I need to map those 70 error messages or code to 5 custom error messages before sending to end user.

Is there any better design pattern to implement this for java? Will chain of responsibility pattern work for this use case?

I want Very Sample Example To use DryIoc with mvc ..any help please?

I used the official site but i didn't understand any thing http://ift.tt/2od3Hnl

Functional programming interfaces in Java

Where can I look for a list of Java standard libraries for functional design patterns? I've heard java.util package contain all of data structures, but I can't find the equivalents of functional interfaces in it:

Monoid -> Appendable

Monad -> Flattenable

Functor -> Mapable

Applicative -> Sequencable

Arrow -> Stateful

Lens -> Damnable

There are also Foldable, Traversable, Parser, Pipe and so on.

Java Command Pattern prepopulate list of Invoker class

I have number of classes that parses String. These Strings are sent by LAS (Laboratory Automation System) machines after performing sample's tests and then parser classes are responsible to parse them and extract results from String.

As every machine sends String in different formats, so can't have single and generic String parser. The class responsible to get String from machine is called Controller. Controller knows all the information of machine and is generic. There is only one Controller and multiple parser.

Now the problem is how Controller will know which parser to invoke for data extraction.

I have implemented Command Pattern but according to the example, private List<Order> orderList = new ArrayList<Order>(); this list needs to be populated before invoke() is called out.

So, it sense that I need to create object of all Parser classes and add them in list in order to know which Parser should be invoked.

Here is my code:

Abstract Parser:

public abstract class Parser {

private final String resultString;
private final String machineId;

  protected Parser(final String result, final String machineId){
    resultString = result;
    this.machineId = machineId;
  }

  /**
   * This method's implementation will parse the output string. The method    @see setResultString(String) must be called before parsing. 
   */
  abstract void  Parse();

  protected String getResultString(){
     return this.resultString;
  }

  protected String getMachineId(){
     return this.machineId;
  }
}

Concrete Parser:

1. COBASParser

public class COBASParser extends Parser{

  public COBASParser(final String resultString, final String machineId){
     super(resultString, machineId);
  }

@Override
 void Parse() {
     System.out.println("This is COBAS's Parse() method");
     System.out.println("ResultString:: "+getResultString());
  }

}

2. E170Parser

public class E170Parser extends Parser {

  public E170Parser(final String resultString, final String machineId) {
     super(resultString, machineId);
  }

  @Override
  void Parse() {
     System.out.println("This is E170Parser's Parse() method");
     System.out.println("ResultString:: "+getResultString());
  }
}

Invoker Class:

public class ParserInvoker {

  private static ParserInvoker me;
  private List<Parser> parsersList;

  private ParserInvoker() {
     parsersList = new ArrayList<>();
  }

  public void addParser(Parser parser) {
     parsersList.add(parser);
  }

/**
 * Invokes concrete class parser.
 * @param machineId 
 */
 public void invoke(final String machineId) {
      for (Parser p : parsersList) {
         if (p.getMachineId().equals(machineId)) {
             p.Parse();
         }
      }
 }
 public static synchronized ParserInvoker getInvoker() {
     if (me == null) {
         me = new ParserInvoker();
      }
      return me;
 }
}

What should I do? Should I adopt any other pattern (Abstract Factory Pattern) or I haven't implemented the Pattern correct?

Here is my Controller

class LASController{

   void OnDataRecieve(String resultString, String machineId){
     // Call Parser here
   }

}

lundi 27 mars 2017

How do I return data from a callback inside an XMLHttpRequest using the JavaScript Exports Module pattern?

I have this,

  var JOHNNY = (function()
    {
        var module = {};
        function getData(id, callback){
                var xhr = new XMLHttpRequest();
                var url = "http://someurl/api/5";

                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && (xhr.status == 200)) {
                        callback(xhr.response);
                    }
                };

                xhr.open("GET", url, true);
                xhr.responseType = 'json';
                xhr.send(null);

        }
        function myCallBack(data){
            return data;  //console.log works;
        }
        module.getStuff=function(id){
            return getData(5, myCallBack);  //just hardcoded id here
        }
        return module;
    })();

Data is returned. I can step through it, but as soon as I run it in the console:

JOHNNY.getStuff(5);
undefined

never get anything else (I'm in the console.) If I change the return in the callback to console.log(data), I get the data, so I know the url is good.

Due to the async nature of the call, I put a callback. But I am also trying to follow an "Exports" pattern variation of the Module pattern.

How do I get the data from the callback? I've seen lots of examples when not using the Exports variation, but nothing else. For example, this, Javascript module pattern with Ajax callback. This one was never answered, Returning data resolved by XMLHttpRequest with module pattern function and I evidently cannot understand this one, Javascript module pattern, ajax functions callbacks.

I can get the data if I do this,

function myCallBack(data){
    module.test = data;
}

and then,

JOHNNY.test;

But I don't know if that's the right way or not. Plus, how does this work when module has already been returned?

I'm not using jQuery (please no jQuery response), just straight JavaScript.

Edit: I was hoping to fix this without Promises. I do not understand why the callback does not fix the problem.

How to manage high level of abstraction in the persistence layer?

I am looking for a way to build an abstraction layer between my business domain (or login) and the persistence layer.

Let me start with an example, lets say we have a user and we want to implement the following features.

User:

getById(String id);
getByName(String name);
getByAge(int age);
getByNameAndAgeLTE(String name, int age);
...

If we want to limit the number of methods to implement and to keep the logic separated from the db, we have to set some boundaries between those layers.

Searching the web, I have came across plenty of methods, such as query-object-pattern, active-record, dal and plenty of ORM examples.

I feel uncomfortable with the data query with all of the solutions I came to so far. Every each and one of them require the developer to write the tool specific API in its business domain.
For example, I liked the idea of active record (and any other ORM), but you have to write the queries using the library (or framework) specific API, and thus leak some separation between the layers.

If we take a look at some ORM (for example, morphia)

datastore.createQuery(User.class)
                     .field("name").equal("Rocky")
                     .field("age").lessThanOrEq(30)
                     .asList();

We see we have to know the Morphia API, and by that mixing the persistence layer with our logic layer. I can't think of a way to achieve this abstraction and separation, and I am very confused with all that information that I have read.
What are the best practices of querying a database? How does enterprise application access and query their data?

Which design pattern suits the best?

I am developing an application that uses 5 different APIs (google, facebook, github, etc...) and my idea is before everything getting complicated to design the structure the best so it can be reusable and easier to extend later. I was thinking about abstract factory, but in this case I am going to have a singular instance of every API "module", as I am not going to create multiple object of a single API client. How would you design a small python / php programm which uses 5 example APIs, so that it is easier to extend and reuse later? I think I am missing some main stuff, so I hope somebody helps me out here

C# MVVM How to dynamically create Views

I'm trying to create a memory game while strictly following the MVVM pattern to learn how to use it. Now I have a problem with creating views at run time.

I've created the following project structure:

  • Model project
  • -MemoryCardModel30
  • -Card
  • ViewModel project
  • -MainWindowViewModel
  • -CardViewModel
  • View project
  • -CardView
  • StartApplication project
  • -MainWindowView

The dependencies are as follows: StartApplication project -> View project -> ViewModel project -> Model project

After clicking a button on the MainWindowView the ICommand function for that button within the MainWindowViewModel will load a MemoryCardModel30 instance from the Model project. For each Card within the MemoryCardModel30 instance a CardViewModel will be created.

Now to the problems I face: How to create the CardView instances, how to link their DataContexts to the CardViewModels and how to arrange/assign the CardViews on the MainWindowView? The ViewModel project can't create Views as it has no dependency to the View project (would create a circular dependency and breaks the pattern). How to solve this issue while following the MVVM pattern?

P.S.: The CardViews need to be positioned exactly by x and y pos. which will require some complicated calculations which should go tho the corresponding CardViewModel. So some basic layouts like grid will not be sufficient I think.

Does Chain of Responsibility work here?

I am designing a solution to a problem where I have list of items which have a score. For eg.

Product    Score
   A       10.4
   B       7.4
   Z       5.4
   D       4.4
   C       4.2
   H       4.1
   G       3.4
   BN      32.41
   CV      2.3
   AV      1.6
   FG      10.7
   .
   .
   .
   .
   ........

These items has to go through set of black box kinda steps..

scored item ----> Step 1 -- (re rank)---> Step 2 --(re rank)----> Step 3 -(re rank)---> Final Result

Each Step will rerank the some products based on their type. For eg. Step 1 will make sure Electronic products land in the top 10 score (it will make top 3 of electronic product fixed in top 10) when step 2 get this list it has to rerank but shouldn't re arrange the products fixed by step 1 but it should consider it while ranking others. I am thinking Chain of Responsibility design pattern. What do u guys think ?

Where is a limit of "overdesign"?

Probably not the best place to ask but eh... here i go:

So a while back i started working on "LimitlessUI" - library for winforms(http://ift.tt/2nsPpAA). And one of the items that i created was "material styed textbox" (Im arent really proud of this one BUT i guess its good enough :) no complains yet :D )

So whats the problem with it? Some of my friends didint even notice quite cool(in my opinion) animation, others say that its amazing, one guy even said "you are just wasting cpu cycles" :D

So anyways, im wondering what are the thoughts of people that have some experience in designing?http://ift.tt/2na1msd

LimitlessUI Textbox demo

and if any1 is intreasted - here is my try(with the same library) on Windows 10 inspired application (still working on it) System Monitoring application

Missing realization in Factory Method?

In the class diagram of the design pattern Factory method I think there should be a realization between the abstract creator class and the interface. The factory method returns an object of the type of the interface but there isn't a realization line. In the following diagram you can see the class diagram generated by the plugin UML in Netbeans: Factory Method class diagram

What is the best way to handle errors in angular 1.5+ in a smart/dumb structure?

I saw a lot of documentation about smart and dumb components. For example:

angular.module('myList', []).component('myList', {
bindings: {
  items: '<',
  onDelete: '&'
},
templateUrl: 'my_list.template.html'  });

When I click on a button with an "onDelete" binding, the smart component execute a function in a service, the service call to the server/API and refresh the items object on the above dumb component. Ok, cool.

My question is, what happend if the server returns an error? I'd like to show that error inside the my_list.template.html template. Do I need to add an '<error' binding?

Another doub. If I have a form on myList component, and I want to reset the form (and many other things...) when the server finish the onDelete execution, what is the more elegant way to do this? (to do it I return a promise in the onDelete function but I don't like it much)

var promise=vm.onDelete({item:item});
promise.then(...);

Thanks

Design patterns for applications with multiple data sources?

I'm currently working on windows form application that needs to operate both offline and online. The idea is that when the device running the application has an internet connection it will fetch from a web service to get its data, however when there is no connection it fetches from a local data source in the form of JSON in the local file system.

I would preferably like to use the Service and Manager design pattern (3-tier). However I am unsure which to give the responsibility to of deciding on the data source to use. Should the managers have access to two different services and each service looks at a different source and understands how to interact with each, or should the services be aware of how to interact with both data sources?

C# Validation Pattern - Best practice to validate an Entity over a certain operation

I might be trying to solve this problem in a wrong way and I've also found lots of solutions but none of them answer my particular question.

In short, I want to validate an object (i.e. argument, entity, etc.) over a an operation (i.e. Insert, Update, Select, etc.).

I've created a small code sample here only for 1 class and 2 operations. But in my actual project, there are many more classes like Person and operations.

Person.cs

public class Person
{
   public int Id {get;set;}
   public string Name {get;set;}
   public DateTime Birthdate {get;set;}
   public BeverageSelectionType BeverageSelection {get;set;}
}

BeverageSelectionType.cs

public enum BeverageSelectionType
{ 
    NotSet,
    Juice,
    Beer,
    Water
}

IService.cs

public interface IService
{
   void Update(Person person);
   Person Add(Person person);
}

PersonSevice.cs (To explain it simple, I chose as service, but in reality I use repository pattern and UnitOfWork which I thought writing them here would be long)

public class PersonService : IService
{
    public void Update(Person person)
    {
        if(person.BeverageSelection == BeverageSelectionType.NotSet
           || (person.BeverageSelection == BeverageSelectionType.Beer && person.Birthdate < DateTime.Now.AddYears(-18))
          )
         throw new MyInvalidException("Parameters NOT valid for UPDATE operation");

         //Do update with expected parameters
    }

    public Person Add(Person person)
    {
        if(person.Birthdate <= DateTime.MinValue || person.Birthdate >= DateTime.MaxValue)
         throw new MyInvalidException("Parameters NOT valid for ADD operation");

         //Do add with expected parameters
    } 
}

I need to design such as generic as possible approach for Validation that helps to validate entities against operations. I just don't want to add validation logic in to each service.

Here is another approach that every Entity knows itself when and how it is valid but I though was useful but still believe not good enough:

Person.cs

public class Person
{
       public int Id {get;set;}
       public string Name {get;set;}
       public DateTime Birthdate {get;set;}
       public BeverageSelectionType BeverageSelection {get;set;}

   public bool IsValid(ModelValidationType modelValidationType)
   {
       switch(modelValidationType)
       {
           case ModelValidationType.Update:
               if(person.BeverageSelection == BeverageSelectionType.NotSet
           || (person.BeverageSelection == BeverageSelectionType.Beer && person.Birthdate < DateTime.Now.AddYears(-18))
          )
          return false;

           case ModelValidationType.Add:
            if(person.Birthdate <= DateTime.MinValue || person.Birthdate >= DateTime.MaxValue)
             return false;
       }

     return true;
   }
}

How would you implement the most proper validation approach?

Thanks in advance

How should the "Model" from MVC be implemented with a DAO design pattern?

I'm writing a web project using MVC design pattern (with DAO to access database) that will run on a Tomcat server.

What is concretely the model on my tomcat server ?

Version 1 My current interpretation is : the Model is a set of java objects that stay on my server using a static java class that will store the objects. Periodically, it uses a DAO to check the DB and update itself. The controller, when called by the view, checks that model and returns the appropriate informations to the view.

Version 2 But a teammate thinks : nothing is persistent on the server. When the controller is called, it calls the DAO that checks the database, create a Java object of the model and gives it to the controller. The controller finds in it the informations it needs, returns these infos to the view (and the java object from the model is destroyed by the garbage collector at the end of the controller).

How does a server work ? What is the right interpretation ? Thanks for any help or advice.

Search space separated input using pattern matcher

I'm performing search operation using pattern matcher. It works very well on single word input like below:

if "I like to eat healthy diet." is my string and I want to search word "eat", it gives me output as "to eat healthy".

, but in case of space separated inputs

if "I like to eat healthy diet." is my string and I want to search "to eat", it doesn't gives me any output.

Below is the code for search

for (Link link : publication.links) {
            String htmlText = fetch.getData(link.getHref());
            Pattern pattern = Pattern.compile(searchQuery);
            Matcher matcher = pattern.matcher(htmlText);
            while (matcher.find()) {
                int start = matcher.start();

                String prev = getTextBefore(start, htmlText);
                String next = getTextAfter(start, searchQueryPath, htmlText);
                String match = prev.concat(searchQueryPath).concat(next);

                Search searchResult = new Search();
                searchResult.setSearchIndex(start);
                searchResult.setResource(link.getHref());
                searchResult.setMatchString(match);
                searchResult.setTextBefore(prev);
                searchResult.setTextAfter(next);

                String title = parseChapterTitle(htmlText);
                if (title != null) {
                    searchResult.setTitle(title);
                } else {
                    searchResult.setTitle("Title not available");
                }
                searchQueryResults.searchResultList.add(searchResult);
            }
        }

In above code, htmltext is string to be searched for searchQuery. And searchQuery is getting for searchView.

Best practice to communicate with Elastic in an application

It will be first time I am going to use Elastic in production.

For databases, I use repository pattern, for example concrete classes of IOrderRepository, IFacetRepository uses SQL and Mongo drivers to communicate with db.

The application is going to get all the products from Elastic, and I use Elastic REST Api to get data.

What can be the best practice to represent elastic provider(?) in code base?

I can continue using Repository pattern,and create ProductRepository that uses ElasticClient and make http calls, but I feel it is not a perfect solution.

I also can't create ProductService as I don't want any business in the code. Single responsibility is getting the products from elastic, that's all.

May be mediator pattern is the right way to implement.

What do you suggest?

dimanche 26 mars 2017

What design pattern is proper for this situation?

I'm learning design patterns and I am confused because I don't know what pattern is best for this situation:

I have String and this String may be various. It may be "123abc", "abc123", "abcdfe" or "123456" and only like those string's.

public void doSomething(String variousString) {
    StringType type = checkType(variousString);
    if(type==StringType.Mixed) doMixedAction();
    if(type==StringType.OnlyLetters) doOnlyLetterAction();
    if(type==StringType.OnlyDigits) doOnlyDigitsAction();
}

Firstly I thought about Strategy pattern but I think that It doesn't match here. Now I think that Chain of Responsibility is matching here very well.

What is the best pattern for remove if statements in this situation? What are your opinions?

Polymer 2.0: where should I place business logic?

I'm starting with Polymer, 2.0, and I have a design question that I cannot find an answer to, and I hope you can help me.

The point is that I'm working on a Task Manager system that consumes an external api (laravel in this case) to start/stop a task, edit or create a new one, etc.

What I'm not able to find is the best approach to handle the business specific logic, because as far as I know the Polymer Elements should be reusable and including the api calls and other funtionality into the Polymer Element doesn't seem to be the best solution, although it's the easiest.

I have several alternatives in mind: - Manage everything using custom events from a top level JS class that make the api calls and update the Polymer Elements. - Use mixins to extend from Polymer Element and a custom Task class containing the needed methods/logic. - pass to the Polymer Element a Task object and save it as a property and call the method through it.

Could anybody tell me which is the best approach? Although I'm sure that is not going to be any of the three I said :)

Thank you!

Which class pattern is better?

Which pattern is better? The first class is more object-oriented, but maybe the second is easier to duplication of code copy, maybe easier to test?

1.

class ClassName {

    public $variable;

    function __construct($variable){
        $this->variable = $variable;
        return funName()
    }

    public function funName() {

        $model = ArrayHelper::getColumn($this->variable); 

        return $this->render('view', [
            'variable' => $this->variable, 
            'model' => $model
        ]);
    }
}

2.

class ClassName {

        function __construct($variable){
            return funName($variable)
        }

        public function funName($variable) {

            $model = ArrayHelper::getColumn($variable); 

            return $this->render('view', [
                'variable' => $variable, 
                'model' => $model
            ]);
        }
    }

Documentation about design of application

I'm preparing myself for bigger project and I will write documentation with chapters like Analysis, Design and Implementation. I know what analysis should contain like functional, nonfunctional requirements..etc.. But I have question what chapter about design should contain.. Like design of process, design or gui and what else? Thank you

Java: Which pattern helps me to implement task properly?

This is what we have at the moment:

interface ReportService {

    Report generate();
  }

and interface implementation:

@Service
public class ReportService_1Impl implements ReportService {

    public Report generate() {

        System.out.println("Report Service 1: generate Report.");
        return new Report();
    }
}

What is the new business requirements for this piece of code:

  • Implement new ReportService_2 that will communicate with the new report engine but new service still have the same generate() method with the same signature;
  • Implement the possibility to switch between these services in Runtime based on some pre-defined configuration;
  • As an option: think about the ability to introduce new ReportServices in the nearest feature.

Okay, let's start to implement all steps that were mentioned above:

Step 1:

new ReportService_2:

@Service
@Qualifier("ReportService_2")
public class ReportService_2Impl implements ReportService {
    public Report generate() {

        System.out.println("Report Service 2: generate Report.");
        return new Report();
    }
}

add @Qualifier("ReportService_1") for ReportService_1Impl

@Service
@Qualifier("ReportService_1")
public class ReportService_1Impl implements ReportService {

    public Report generate() {

        System.out.println("Report Service 1: generate Report.");
        return new Report();
    }
}

Step 2:

How to switch between 2 services in Runtime based on configuration?

Frankly speaking, I am not sure how to implement this task properly, I've just introduced new ReportService that plays the role of Container or Wrapper for ReportService_1Impl and ReportService2_Impl and determines which implementations need to use:

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    @Qualifier("ReportService_1")
    private ReportService reportService_1;
    @Autowired
    @Qualifier("ReportService_2")
    private ReportService reportService_2;

    private ReportService getActiveReportService() {

        return true ? reportService_1 : reportService_2;
    }

    public Report generate() {

        return getActiveReportService().generate();
    }
}

Looks quite ugly, but I believe that we can live with it.

And the last step, where I need to implement the following requirements:

think about the ability to introduce new ReportService's in the nearest feature.

I do not know how to implement this properly because with the current implementation, each time when I will add new ReportService_N I will need to remember, that I definitely need to inject newly created ReportService_Nin ReportServiceImpl and it will look like:

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    @Qualifier("ReportService_1")
    private ReportService reportService_1;
    @Autowired
    @Qualifier("ReportService_2")
    private ReportService reportService_2;
    @Autowired
    @Qualifier("ReportService_3")
    private ReportService reportService_3;
    @Autowired
    @Qualifier("ReportService_4")
    private ReportService reportService_4;
    @Autowired
    @Qualifier("ReportService_N")
    private ReportService reportService_N;

Believe, that this kind of problem was solved multiple times in the past and already defined some pattern that I will need to use.

Can someone give me advice or pattern name that helps me to resolve my problem with the last scenario?

What Patter design to get rid of the type casting in my case?

public abstract class Employee {
    String name;
    String position
    public Employee(String name, String position) {
      this.name = name;
      this.position = position
   }
 }

public class Pilot extends Employee {
      public Pilot(String name,String position) {
         super();
  }
      public void flight() {//flight the plane}
     //getter and setter for the fields
}

public class Attendance extends Employee {
      public Attendance(String name,String position) {
         super();
  }
      public Food servingFood(String foodName) {}

}

// there will be many other positions


public class Company {

   HashMap<String, ArrayList<Employee>> employeeTable; //values is a list of     workers, key is the position

   public Company() {this.employeeTable = new HashMap<>();}
   public initializeEmployeeTable(file) {} //read file, and create keys in map (file contains information of the position)
  public Worker hireEmployee(String position, String name){
      if (position.equals("pilot")) {  
             Pilot p = Pilot(name);    
              employeeTable.get("pilot").add(p);
              return p
  }
      else if (position.equals("flightAttendance")) {// the else if statement continuous to check the other position; }
 } 

 public Worker callEmployee(String position, String name) {
    for ( Employee e : employeeTable.get(position) ) {
          if e.getName().equals(name) {
                return e;
    }
   }
   return null;
}



public static void main(String[] args) {
  Company company = new Company();
  company.initializeEmployeeTable(filePath);
  File eventFile = new File(filePath); // event file describes what's happening in real world; read the lines, and call the program so that program simulates the real world events
  sc = new Scanner(eventFile);
  do {
      String currentEvent = sc.nextLine();
      String[] currentEventParts = currentEvent.split(", ");
     if (currentEvent[0].equals("New Airplane")) { // currentEvent looks like {"New Airplane", "Attendance"// this part can be other position name, "Linda"}
        Worker w = company.hireEmployee(currentEventParts[1], currentEventParts[2]); }
     else if ((currentEvent[0].equals("flying"))) {
        Worker w = company.callEmployee(currentEvent[0], currentEvent[1])
               if (w.getPosition().equals("Pilot")) {(Worker) w.flight()}
                if (w.getPosition().equals("Attendance")) {(Worker) w.serveFood()}
     }
}

The reason there is HashMap for employee because there will be many positions; and reading the event file (when the first index is "New Airplane"); I don't want to go check the following index (would be name and position) with so many if statements to create corresponding employee. But when comes to calling specific methods, I need type casting now; since each method can be different (different type parameter, return type); so it's not ideal to have this methods be abstract method in super class employee and have the subclass implements the body.

Any advices: employee data structure; reading file strategy, pattern design would be appreciated. thanks

ES6 - How to get array item (function) of a specific context

Given a publish-subscribe pattern using ES6 as follows (extracted from http://ift.tt/20wYK9e):

class PubSub {
    constructor() {
        this.handlers = [];
    }

    subscribe(event, handler, context) {
        if (typeof context === 'undefined') {
            context = handler;
        }
        {
            if (this.getHandler(event, handler) == null) {
                this.handlers.push({event: event, handler: handler.bind(context), key: Guid()});
            }
        }
    }

    unsubscribe(event, handler) {
        let filteredHandler = this.getHandler(event, handler);
        if (filteredHandler != null) {
            let idx = this.handlers.indexOf(filteredHandler);
            if (idx > -1) {
                this.handlers.splice(idx, 1);
            }
        }
    }

    publish(event, args) {
        this.handlers.forEach(topic => {
            if (topic.event === event) {
                topic.handler(args)
            }
        })
    }

    getHandler(event, handler) {
        if (this.handlers == null || this.handlers.length < 1) {
            return null;
        }

        let filtered = null;

        this.handlers.forEach(topic => {
            if (topic.event === event && topic.handler === handler) {
                filtered = topic;
            }
        });

        return filtered;
    }

    getNumOfSubsribers() {
        if (this.handlers != null && this.handlers.length > 0) {
            return this.handlers.length;
        }

        return 0;
    }
}

The subscribe and publish methods work. However, the getHandler and unsubscribe method do not work as expected (getHandler seems returning null). I have tried to search around but could not get a satisfactory solution to this problem (not sure how a function bound to a given context can be filtered out from an array).

What have I done wrong in the code? Kindly advise me on getHandler and also unsubscribe part of the code.

Appreciate some kind help.

iOS - News feed app client/server code design

  • Am working on app which will display a list of news feed (posts) returned from the server side, each post will display as (post owner user, title, description, users list who like this post).
  • the app will be news based (not users based)

what is the best design approach to return the the list of posts from the server ??

Suggested options to be discussed:-

1- option (1):-

Each post in the posts list contains (title, description, a list of users who like this post) But the disadvantage of this option is the data for users will be redundant (because may be the same user liked many posts so its object will return in many post)

{
   postsList: 
   [
      title:"title 1",
      description:"description 2",
      postOwnerUser: { user },
      likersUsers: [
                       {
                            userId: "1",
                            userName: "aaa", ...
                       },
                       {
                             userId: "2",
                             userName: "bbb", ....
                        }
                   ]
   ]
}

2- option (2):-

Each post in the posts list contains users ids only, but this needs to make alot of calls to get each user details

3- option (3):-

To cache the users objects in users service for example. but by this we will keep in the memory many users objects may be not useful all the time (we can solve this by clearing the no needed users objects from the cached uses service)

Please share with me the best practices for this design issue or references related

Detect mouse action while clicking on rectangle in Swing

I'm new to Java. I'm developing a small 2D game and trying to learn MVC design pattern. I have a Menu Panel with Play button (which is just a rectangle with some text, not JButton).

The problem is that my controller does not detect any action (It should print something to the console) and I can't find any bug in this code.

That's a Panel class:

package game.flappybird.view;

import java.awt.event.ActionListener;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Created by david on 3/23/17.
 */
public class MenuPanel extends JPanel {

    public java.awt.Rectangle playButton;

    public MenuPanel() {

        this.playButton = new Rectangle(250, 275, 100 , 50);
    }


    public boolean contains(Point point){

        return this.playButton.contains(point);
    }



    public void paintComponent(Graphics graphics){

        Graphics2D graphics2D = (Graphics2D) graphics;

        Font buttonFont = new Font ("arial", Font.BOLD, 20);

        graphics.setFont(buttonFont);
        graphics.drawString("Play", playButton.x + 25, playButton.y + 25);
        graphics2D.draw(playButton);

    }

}

That's a controller class:

package game.flappybird.controller;

import game.flappybird.view.MenuPanel;
import game.flappybird.view.MenuView;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

/**
 * Created by david on 3/22/17.
 */
public class MouseInMenuController implements MouseListener {

    MenuPanel menuPanel;


    public MouseInMenuController(){

        this.menuPanel = new MenuPanel();
    }


    @Override
    public void mouseClicked(MouseEvent mouseEvent) {
        int mousePositionX = mouseEvent.getX();
        int mousePositionY = mouseEvent.getY();

        if (this.menuPanel.contains(mousePositionX, mousePositionY)){
            System.out.println("you clicked on menu button");
        }

    }

    @Override
    public void mousePressed(MouseEvent mouseEvent) {

    }

    @Override
    public void mouseReleased(MouseEvent mouseEvent) {

    }

    @Override
    public void mouseEntered(MouseEvent mouseEvent) {
        int mousePositionX = mouseEvent.getX();
        int mousePositionY = mouseEvent.getY();

        if (this.menuPanel.contains(mousePositionX, mousePositionY)){
            System.out.println("you are inside menu button);
        }

    }



    @Override
    public void mouseExited(MouseEvent mouseEvent) {

    }
}

Refactoring legacy mixin-based class hierarchies

I'm currently working on a huge javascript project which has a huge class hierarchy and heavily uses mixins to extend functionality of base classes. Here is an example of how mixin looks like, we're using compose library to create class-like objects:

// Base.js
var Base = compose({
  setX: function (x) {
    this.x = x;
  },

  setY: function (y) {
    this.y = y;
  },

  setPosition: function (x, y) {
    this.setX(x);
    this.setY(y);
  }
})

// SameXAndY.js - mixin
var SameXAndY = compose({
  // Executes after setX in Base.js
  setX: compose.after(function (x) {
    this.y = x;
  }),

  // Executes after setY in Base.js
  setY: compose.after(function (y) {
    this.x = y;
  }),

  // Overrides setPosition in Base.js
  setPosition: compose.around(function (base) {
    return function (x, y) {
      if (x !== y) {
        throw 'x !== y';
      }
      return base.call(this, x, y);
    }
  })
})

We have the following problems with this solution:

  • Mixins heavily depend on each other - you can break something by changing mixins' order in base classes.
  • There is no easy way to ensure that you can safely include some mixin in your class, you may need to implement additional methods / include additional mixins into it.
  • Child classes have hundreds of methods because of the various mixins.
  • It's almost impossible to rewrite mixin in Flow or Typescript.

I'm looking for better plugin-like alternatives which allow to gradually refactor all existing mixins. I understand that there is no "easy" answer to my question, but I would really love to hear your thought on this topic. Design pattern names, relevant blog posts, or even links to the source code will be greatly appreciated.

Cheers, Vladimir.

Pattern Dispatch and Pattern Matching

I have been reading about pattern dispatch and pattern matching. I know that Mathematica and other languages uses pattern dispatch for pattern matching. I wanted to know how is pattern dispatch used in pattern matching for expressions?

Thanks

Is there any design pattern for this? (Builder, Inheritance)

I have following structure:

public class MyClass {

    public static class DefaultBuilder {
        private int config1;
        private String config2;

        public DefaultBuilder configMethod1(int config1){
            this.config1 = config1;
            return this;
        }

        public DefaultBuilder configMethod2(String config2){
            this.config2 = config2;
            return this;
        }
    }

    public static class SpecialBuilder extends DefaultBuilder {
        private long specialConfig1;

        public SpecialBuilder specialConfigMethod1(long specialConfig1){
            this.specialConfig1 = specialConfig1;
            return this;
        }

    }
}

...

public class Main {

    public static void main(String[] args){
        new MyClass.DefaultBuilder().configMethod1(1).configMethod2("Test"); // Works great
        new MyClass.SpecialBuilder().specialConfigMethod1(10).configMethod1(1).configMethod2("Test"); // Works great
        new MyClass.SpecialBuilder().configMethod1(1).configMethod2("Test").specialConfigMethod1(10); // Does not work
    }
}

I only can use the specialConfigMehthod1 when using it as the first method. But because this should be an API for a library I don't want to tell the user how he has to order his call. I could override every method in my SpecialBuilder but I don't like that solution because then the inheritance is senseless. I also have thought about Interfaces but have not found any good solution there. Is there any design pattern or anything extremely simple I did not thought about (in Java if possible :) ):

If you want to see this in a working example you can go here: GitHub This is my first open source library and I don't like the API the way it is.

Singleton Design Pattern-Java

Does the class below implement the singleton pattern? I'm really confused.

class Customer {

    static private Map costumers = new HashMap();

    private Customer() {
    }

    public static Customer getInstance(String name) {
        Customer instance = (Customer) costumers.get(name);
        if (instance == null) {
            instance = new Customer();
            costumers.put(name, instance);
        }
        return instance;

    }
}

Thanks.

What is the best pattern that would suit, sending notifications for respective actions?

Here is my servlet which does too many actions like the following

public class SampleServlet extends HttpServlet {
      public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {
        ServletActions.valueOf("action1").execute(params);  //Invoking respective action    
}
}

Since my servlet handles too many actions, I have implemeneted them with enum following Strategy Pattern.

Like,

public enum ServletActions {

   ACTION_1 {
      //Do some actions
      //Notify `a` regarding the actions
      //Notify `b` regarding the action performed
      //Construct response json
   },

   ACTION_2 {
      //Do some actions
      //Notify `d` regarding the actions
      //Notify `e` regarding the action performed
      //Construct response json
   },

   ACTION_3 {
      //Do some actions
      //Notify `d` regarding the actions
      //Notify `b` regarding the action performed
      //Construct response json
   },

   ACTION_4 {
   },

   ACTION_5 {
   },

   ACTION_6 {
   },

   ACTION_7 {
   };
}

a, b, c here are like sending in-progress notification, success notification, sending notification to agent, sending notification to client etc.

Handling all my notification sending task within the action makes the code too clumsy. So thought of implementing the same with

   public enum ServletActionsNotifier {

       ACTION_1_NOTIFIER {
          public void sendNotification() {
               //Send agent notification
               //Send progress notification
          }
       },

       ACTION_2_NOTIFIER {
         public void sendNotification() {
               //Send task notification
               //Send progress notification 
         }
       },

       ACTION_3_NOTIFIER {
          public void sendNotification() {
               //Send feed notification
               //Send success notification 
         }
       },

       ACTION_4_NOTIFIER {
       },

       ACTION_5_NOTIFIER {
       },

       ACTION_6_NOTIFIER {
       },

       ACTION_7_NOTIFIER {
       };
      abstract void sendNotification();
    }

Someone suggest me an alternative for implementing the notification processor in a better way in this case.

samedi 25 mars 2017

Circular dependencies between classes: why they are bad and how to get rid of them?

I feel that circular dependencies mean bad design and harm the project. How can I convince my teammates and my manager?

My project is a dependency mess. Is there a methodology to get rid of wrong dependencies and then maintain the clearness?

Best practices: Should a query rely on existing client-side loaded data?

In the context of a debate I'm having with a coworker:

Let's say we're loading categories on a certain page. Then there's a search function that allows you to load a category's items on the same page.

Since you're not on the category/slug page when you search (i.e., you haven't click into a category), you need to tell the user which category the items belong to by displaying the category name of the item.

The category items query already has a join that loads category Ids on the item (join is on the item_category_item table). But you'd need to perform a 2nd join on the item_category table to then retrieve the category name by Id and return it with the category items.

So, which is the better approach?

A) We're pulling the categories already (with name and ID) on category view page load. When we search for category items, the items are returned with the category Id. We can then pair the already loaded categories by Id, and add the category name attribute to the items. This saves an extra join on the category items query.

Or

B) Add the 2nd join to the category items search query so we can return the category items with the category name.

My thought is, a query shouldn't rely on what's been loaded/not loaded on the front-end. It should load the stuff it needs for the query in question (even if an additional join is required).

AKA, even though X has already been loaded at some point to the page, we shouldn't need to retroactively add attributes to objects based on existing information because what happens if the client-side data that it's relying on changes or is removed?