samedi 30 septembre 2017

What are the most important JavaScript Design Patterns?

Specifically, which design patterns are most important to Front End Developers in 2017?

I'm coming from an iOS background and have a thorough understanding of OOP, Functional Programming, Decorator/Delegate Pattern. I'm learning the module pattern right now.

Where should I go from here? Which books/sites would you recommend the most?

IOC principle - Servlet Container Vs Spring IOC container

IOC can be implemented, using either:

  • Dependency Injection

  • Service locator pattern


Spring IOC container follow IOC principle using Dependency injection, where implementations can be injected at runtime as constructor-based or setter-based

Servlet container(Ex: Apache tomcat) follow IOC principle to pick servlet class implementation based on the configured data given in web.xml with url pattern matching rules.


The purpose of both containers differ. But,

What design pattern does servlet container follow to implement IOC principle?

Separate operation class to work with data classes

I've noticed two different design patterns for strings.

  1. The one in PHP that strings are just a bag of bytes, with a lot of extentions to work with them (standard string functions, multibyte string, iconv, intl)

  2. The one in JavaScript where strings are classes that have methods to work with the string.

Obviously the 2nd method is easier to maintain. But to my surprise the 1st design pattern is found more often in PHP. I've also seen a PEAR package for complex numbers, but also here the complex numbers have:

  • there own data class
  • a single operation class

But why? Is there some performance penalty that really matter nowadays with PHP 7?

UML Graphic Turtle in Java

I need to create a Graphic Turtle model before programming.

For now, I have this UML:

enter image description here

Have you got some ideas to add like design pattern? (For now I'm using Factory design pattern and I will use MVC) or maybe to improve my UML?

I don't really know what I can add to get my Turtle efficient, performent and right.

I'm thinking to get only one JFrame with 2 general Panel (the display of turtle and the command line) like this example:

enter image description here

Actually, my turtle is based on rewriting code from L-System but anyway.

Best Practices for Writing Reusable Javascript Libraries

I wonder as a developer if someone asks me:

"What are the best practices to use when creating a reusable javascript library?"

what would I answer?
I have my own answer to this question, but I thought it would be very nice to share it and see where did I got it wrong, or could do it better and etc.
I am thankful to anyone who takes time to read and share his/her ideas.

What I've been doing so far:

I- Anytime that I wrote a Javascript library, which I want to have new instances of it every time that I want to use it, I do the following:

var MyNamespace = (function(){

    var MyFirstClass = (function(){
        function MyFirstClass(){
            var self = this;
            var class_configuration_object = {
                first_property: 'default value'
            };

            // configuration getter
            this.GetConfiguration = function(){
                return class_configuration_object;
            }; 

            // I NEVER use a setter for whole of my configuration object
            this.SetConfiguration = function(){};

            // I write setters and getters for whatever is inside the configuration object, like so:
            // BTW, I Love Chaining Setters.
            this.SetFirstProperty = function(first_property){
                class_configuration_object.first_property = first_property;
                return self;
            };

            this.GetFirstProperty = function(){
                return class_configuration_object.first_property;
            };
        }

        // static methods:
        MyFirstClass.StaticMethod1 = function(){};
        .
        .
        .

        // private functions:
        // when using private functions inside instance methods,
        // I pass this to the private functions always as the first argument.
        // because then self always safely points to the MyFirstClass object.
        var privateFunction1 = function(self){};
        .
        .
        .

        // instance methods:
        MyFirstClass.prototype.InstanceMethod1 = function(){
            // method logic here
            return this;
        };
        .
        .
        .


        return MyFirstClass;
    }());

    var MySecondClass = (function(){
        .
        .
        .
    }());

    return {
        MyFirstClass: MyFirstClass,
        MySecondClass: MySecondClass
    };

}()) ;

then simply you can use MyFirstClass like so:

// instantiating MyFirstClass with default config
var obj = new MyNamespace.MyFirstClass();

// setting configuration object properties:
obj.SetFirstProperty('some value');

// calling instance methods:
obj.InstanceMethod1();

// now because the setters return the object itself, you can also do:
var obj = new MyNamespace.MyFirstClass()
                        .SetFirstProperty('some value')
                        .InstanceMethod1();

II- those times that I want to have a consistent and shared behavior everywhere, I use the following:

var MyLib = (function(){
    // private variables:
    var privateVariable1 = 'default value';

    // public variables:
    var PublicVariable1 = 'default value';

    // private functions:
    var privateFunction1 = function(){};

    // public methods:
    var PublicMethod1 = function(){};

    return {
        PublicVariable1: PublicVariable1,
        PublicMethod1: PublicMethod1
    };

}());

So you can use it like:

// I use this pattern when I want to have a consistant behavior
// that always does the same thing for all of it pointers
// for example:

var a = MyLib;
var b = MyLib;

console.log(a.PublicVariable1); // outputs 'default value'
console.log(b.PublicVariable1); // outputs 'default value'

MyLib.PublicVariable1 = 'new value';

console.log(a.PublicVariable1); // outputs 'new value'
console.log(b.PublicVariable1); // outputs 'new value'

// here MyLib always returns an object, not a constructor.
// that's why you can never do the following here:
var obj = new MyLib(); // a TypeError obviously!

Simple factory and Factory Method Design pattern difference

I am learning design patterns newly & I am trying to understand the difference between Simple Factory & Factory Method Pattern. First I want to clear that , I tried reading lot of articles from Stack-overflow and other sites regarding the same but that doesn't helped me.

Here is my question: Lets consider I have a product hierarchy as shown below: enter image description here

I have written a simple Factory class as shown below

public class SimpleItemFactory {

    static Item getItem(String type) {
        if(type.equals("Cake")) {
            return new Cake();
        }else if(type.equals("Chocolate")) {
            return new Chocolate();
        }else {
            return null;
        }
    }
}

so now I have all the object creation in one place , so if tomorrow any changes occurs[Like constructor needs one parameter] we need to change in only one place. But it breaks OPEN CLOSED principle as if tomorrow we add more item we need to change getItem() methods if condition. So we go for Factory Method Pattern enter image description here

We create Factory class as shown below:

public abstract class ItemFactory {
    abstract Item getItem();
}

class CakeFactory extends ItemFactory {
    @Override
    Item getItem() {
        return new Cake();
    }
}

class ChocolateFactory extends ItemFactory {
    @Override
    Item getItem() {
        return new Chocolate();
    }
}


class Client{
    public static void main(String[] args) {

        Item chocolate = new ChocolateFactory().getItem();
        System.out.println(chocolate);
    }
 }

Now when the client want to add new Item called IceCream, they just create new Factory called IceCreamFactory and create IceCream from that as shown below:

class IceCreamFactory extends ItemFactory{

    @Override
    Item getItem() {
        return null; // new IceCream();
    }

}

class Client{
    public static void main(String[] args) {
        Item iceCream = new IceCreamFactory().getItem();
        System.out.println(iceCream);

    }
}

Is my understanding correct? We satisfied Open closed principle here, but for product we need one Factory class Does not it become manageable nightmare?

NOTE: Article I was referring http://ift.tt/2yzLPrl

vendredi 29 septembre 2017

i want to print the a number when the range is provided

i want the following pattern to be printed in java when we provide a no it print the following pattern here n = 4 output:

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

for (int i=0; i<n/2 ; i++) {
            for (int j=0;j<n ;j++ ) {
                k++;
                System.out.print(k+" ");

            }
            l=k+n;
            k = l;
            System.out.println();
            for (int s=0; s<n;s++ ) {
                System.out.print(l+" ");
                l--;
            }
            System.out.println();
        }
        if (n%2!=0) {
            for (int i=0;i<n ;i++ ) {
                k++;
                System.out.print(k+" ");

            }
        }

here is a code which print

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

Difference between writing OOP and a design pattern and being a top developer [on hold]

Is their a difference of writing a design pattern or some classes that will allow or accomplish a problem ones facing . I know that for example a command pattern would be suitable for a login of course . I decided to go along with a strategy pattern for a login system of mine that implemented Google login Facebook login and the Main login . Using the strategy pattern . I know that an iterator pattern can be used in a search engine example . And also I am just curious as to can one simply write extravagant code like those those of great developers with out the use of design patterns . obviously following Object oriented programming and its principles and concept . But same with algorithms even though its more for searching and sorting :) . But I'm focusing this question on OOP because I want to know is it okay for programmers to write really good code without design patterns or must one memorize and learn these patterns in order for code to come out clean on the fly and in minutes. For example I tried making a search engine without any documentation or without any examples just the php manual since I was using php and such . I got as far as I could and made like 6 classes ones that mostly get and set things . and am going back for another try . To actually make it do stuff without documentation since I read that it isn't good to use it nor copying and paste code :( . I find it very hard to work without copying and modifying code . But I want to be a top developer . How can I accomplish this ? How can I be a top developer . Does have to do with the skill level ? Or maybe just code until something happens without using docs . and more reading ? I just feel like am doing to much without copying and pasting code as I was before and getting things done but its not what I want . I want success . basically I know how to use design patterns even though I went with a strategy pattern instead and I know I can always look it up on examples on how to use them . But how can i be a top developer . amongst others .

Why do some methods belong to the subject/observer interface, while others to the subject/observer concrete subclass?

From Design Pattern by Gang of Four enter image description here

Why are field observers, and methods Attach, Detach and Notify are in the interface Subject, while methods GetState and SetState and field SubjectState are in the concrete subclass ConcreteSubject? Why are the members distributed in the subject interface and concrete subclass as they are?

Why is method Update in the interface Observer, while fields subject and observerState in the concrete subclass ConcreteObserver? Why are the members distributed in the observer interface and concrete subclass as they are?

There doesn't seem to be symmetry between subject and observer. For example, why does field observers belong to interface Subject, while field subject belong to ConcreteObserver?

Thanks.

Why does the builder pattern not have a method `GetResult()` in the builder interface?

From Design Pattern by Gang of Four, enter image description here

Example:

enter image description here

Why doesn't the interface Builder have a method GetResult(), which is overridden in the concrete class ConcreteBuilder?

In the example, the concrete builders have GetXXX() methods, where XXX is different for different concrete builders, which doesn't promote "programming to interface" at all.

Is this "omission" deliberate in the builder pattern?

Thanks.

Design pattern observer useful?

For my example:

I do a graphic turtle. So, I have 2 JFrame, one to display the turtle and its movement and some button like "Return", "Change mode". The other one is still a command where user can write commande like "Move forward".

Before I develop, I need to do an UML for the conception.

I will use design pattern MVC and i'm thinking about design pattern Observer for this which will help me to notify thanks to my second JFrame (command interface) to the first JFrame (turtle screen).

I don't know if it's the good idea because I think Observer is when you have dynamic or a lot of View to manage no? (I have only 2 in this example).

Maybe, i'm a little bit confuse with the Observer pattern

C# recognize number pattern in string

I need a regular expression to check if a number pattern exists within a string. I want to check if a string contains for example 4 sequenced numbers

Frame0001
Frame_0001
Frame_0001_1
Frame_0001(1)
Frame_0001_AA

Result should be 0001 for each of the strings.

Examples which do NOT match pattern would be Frame01 or Frame_01 e.g.

Thanks for any assistance.

best regards, Mark

C# Class Structure to Ensure Certain Filters Are Always Applied

So I'm currently working on a project with a team, and my team and I have come across a certain design scenario that we are trying to come up with a solution for.

Background Info of Current Project Implementation:

This problem involves three main projects in our solution: Repository, Models, and Services project. In case it isn't obvious, the purpose of each project is as follows. The Models project contains models of all the data we store in our database. The Repository project has one main database access class that uses generics to interact with different tables depending on the model passed in. Lastly the Services project contains classes that interface data between the front-end and repository, and in general each service class maps 1-to-1 to a model class. As one would expect, the build dependencies are: Repository relies on Models, and Services relies on both projects.

The Issue:

The current issue we are encountering is that we need a way to ensure that if a developer attempts to query or interact with a specific type of object (Call it ModelA), then we want to ensure that a specific set of filters is always included by default (and these filters are partially based on if a particular user has permissions to view certain objects in a list). A developer should be able to override this filter.

What we want to avoid doing is having an if clause in the repository classes that says "if you're updating this model type, add these filters".

Solutions we have thought of / considered:

One solution we are currently considering is having a function in ServiceA (the service corresponding to ModelA) that appends these filters to a given query, and then to make it so that if anyone requests for the db context of a model, they must pass in a function that manipulates filtering in some fashion (in other words, if they want to interact with ModelA, they would pass in the filter function from ServiceA). The issue with this solution is that a developer needs to always be aware that if they ever interact with ModelA, they must pass in the function from ServiceA. Also, because we don't want every model to enforce certain filter options, we would likely want this to be an optional parameter, which might then cause issues where developers simply forget to include this function when interacting with ModelA.

Another solution we considered is to have an attribute (let's call it DefaultFilterAttribute) on ModelA that stores a class type that should implement a particular interface (called IFilterProvider). ServiceA would implement this interface, and ModelA's attribute would be given ServiceA as a type. Then the repository methods can check if the entity passed in has a DefaultFilterAttribute on it, and then simply call the method implemented by the class attached to the attribute. Unfortunately, as some of you might have noticed, the way our project dependencies are currently set up, we can't really implement a solution like this.

So I'm wondering if there is a clean solution to this problem, or if potentially we are thinking about the problem and/or design pattern incorrectly, and should be taking a completely different approach.

Constructor argument vs get method argument

The problem:

Say we have EmailInterface like this

interface EmailInterface {
  public function getContent(): string;
}

The interface is nice and I like it, but the thing is that 90% percents of concrete emails classes look like this

class NewPostEmail implements EmailInterface {
   private templateEngine;
   public function __construct(TemplateEngine templateEngine) {
     this.templateEngine = templateEngine;
   }
   public function getContent(): string {
     return this.templateEngine.render('some-template');
   }
}

Which makes me wonder about declaring the interface this way:

interface EmailInterface {
   public function getContent(TemplateEngine templateEngine): string;
}

I have faced this dilemma several times and still do not what is better to do. In the first case my interface is perfect and independent, on the other hand every component which need to create an EmailInterface needs to get the TemplateEngine and pass it along, which I do not really like since it makes the code cumbersome.

Is there a pattern for the second approach? I'd like very much to hear about the other ways to solve the problem.

Designing Token Based Authorization Server Request/Response

Identity in our services are based on a token stored in a database. This are acquired by the client by logging in with a user name and password.

Each time a resource is requested, we plan to validate the token and determine if the user is authorized to access that resource.

Our services are deployed separately, and the authorization server can be reached via http.

What's the best practice/common way in authorizing the requests?

Sending token with requested permission and role

I was thinking of passing in the token with the role and requested permission of the user in the token validation request to the authorization server.

{
 token: 'xyz',
 role: 'ROLE_ADMIN',
 permission: 'SAVE_USER'
}

and respond with: 200 for success, 401 for invalid token, 403 if they are not authorized to use the permission.

Sending only the token in authorization request

Another approach in mind is sending just the token in the token in the token validation request to the authorization server.

{
 token: 'xyz'
}

and respond with all the permissions and roles the user have:

{
 roles: ['ROLE_ADMIN', 'ROLE_USER'],
 permissions: ['SAVE_USER', 'DELETE_USER', 'SHOW_USER']
}

Which of these are more advisable? Or are there any other/patterns approaches I can consider?

Do I need to visitor pattern in my design

I am working on designing html parser for study purpose. Where I am first creating a overall design.

Data structure to store html element.

Base : HtmlBaseElement

Derived : HTMLElement, PElement, HtagElemement, ImgElement, BodyElement, StrongElement

Basically I will create derived class for each type of element in html.

I need to write this html file back to a file and allow user to add element in already parsed html file.

This is what I am thinking :

First Approach:

  1. Create a BaseVisitor which is having visit function for each type of element.

  2. Create a Derived Visitor Class WriteHtmlVisitor to write whole file which will visit each element in HTML datastructure.

Second Approach:

I can also use a class WriteHtmlFile , having object of HTMLElement and then write this using getter of all elements.

Which is best way to write html file and adding new elements in file.

I am just looking for suggestion, as this is in design phase.

Thanks.

Do I need to visitor pattern in my design

I am working on designing html parser for study purpose. Where I am first creating a overall design.

Data structure to store html element.

Base : HtmlBaseElement

Derived : HTMLElement, PElement, HtagElemement, ImgElement, BodyElement, StrongElement

Basically I will create derived class for each type of element in html.

I need to write this html file back to a file and allow user to add element in already parsed html file.

This is what I am thinking :

First Approach:

  1. Create a BaseVisitor which is having visit function for each type of element.

  2. Create a Derived Visitor Class WriteHtmlVisitor to write whole file which will visit each element in HTML datastructure.

Second Approach:

I can also use a class WriteHtmlFile , having object of HTMLElement and then write this using getter of all elements.

Which is best way to write html file and adding new elements in file.

I am just looking for suggestion, as this is in design phase.

Thanks.

jeudi 28 septembre 2017

must a subclass of a singleton class be a singleton class?

According to Design Pattern by Gang of Four, a singleton class can have a subclass.

Must a subclass of a singleton class be a singleton class?

Can a singleton class have any number of subclasses?

Thanks.

Are `final` on `class Singleton` and `private` on `Singleton()` redundant with each other? [duplicate]

This question already has an answer here:

From http://ift.tt/2fCihW2

An implementation of the singleton pattern must:

  • ensure that only one instance of the singleton class ever exists; and
  • provide global access to that instance.

Typically, this is done by:

  • declaring all constructors of the class to be private; and
  • providing a static method that returns a reference to the instance.

The instance is usually stored as a private static variable; the instance is created when the variable is initialized, at some point before the static method is first called. The following is a sample implementation written in Java.

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

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

Are final on class Singleton and private on Singleton() redundant with each other?

Does only either of them suffice?

Thanks.

What are the purposes of other members of a Singleton class besides the instance and its get method?

From Design Pattern by GoF

enter image description here

Participants

Singleton

  • defines an Instance operation that lets clients access its unique instance uniqueinstance. Instance is a class operation (that is, a class method in Smalltalk and a static member function in C++).

  • may be responsible for creating its own unique instance uniqueinstance.

Collaborations

• Clients access a Singleton instance uniqueinstance solely through Singleton's Instance operation.

In Class Singleton, uniqueinstance is the unique instance, and Instance() is its get method.

What are the purposes of the other members:

  • method SingletonOperation(),
  • method GetSingletonData(), and
  • field singletonData?

Thanks.

write file metadata information to db for each file transfer

I have a requirement by which I have to sftp files to a destination:

I have written a simple Spring boot app which has a Component like this with Services that do different things:

@Component
public class FileExportSchedulerTask {


    @Autowired
    private FileService fileService;

    @Autowired
    private SFTPService sftpService;


    public void run(String schedule) {
        logger.info("Running Export Scheduler Task...{} " + schedule);
        //gets list of files as Metadata objects which fileService deals with and send to sftpService to extract file path and  initiate transfer
    }
}

The FileService returns the list of files concerned that need to be taken care of by the SftpService and publish to destination. This is in the form of FileMetaData object that has the file path as a field.

After I send each file, I need to write some file metadata information to the database. I have the following metadata object:

public class FileMetaData {

    private String reportId;
    private String reportName;
    private String customer;
    private String format;
    private Date cobDate;
    private String filePath;
}

For each metadata objects received by SFTPService will extract the path and send to destination. The quantity of report is about 50-100 for each of my schedules.

I am having difficulty in thinking how to write to the Database the metadata object SftpService received. Can you guys please give me suggestion what approach is best and how I can implement jdbc inserts for each transfer or if transferred objects should be queued and then one insert to the database.

I am not sure how to persist this information for each file transferred and then how to write to the database. Some recommendations and examples with code sample would assist very much :)

Layered pattern example

I need a project that uses layered pattern, but that is not MVC or client-server layers. Could someone send me a project link on github or another site with a project like this?

Thank you.

How shall I understand the motivation of abstract factory?

From Design Pattern by GoF

ABSTRACT FACTORY

Intent

Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Motivation

Consider a user interface toolkit that supports multiple look-and-feel standards, such as Motif and Presentation Manager. Different look-and-feels define different appearances and behaviors for user interface "widgets" like scroll bars, windows, and buttons. To be portable across look-and-feel standards, an application should not hard-code its widgets for a particular look and feel. Instantiating look-and-feel-specific classes of widgets throughout the application makes it hard to change the look and feel later.

We can solve this problem by defining an abstract WidgetFactory class that declares an interface for creating each basic kind of widget. There's also an abstract class for each kind of widget, and concrete subclasses implement widgets for specific look-and-feel standards. WidgetFactory's interface has an operation that returns a new widget object for each abstract widget class. Clients call these operations to obtain widget instances, but clients aren't aware of the concrete classes they're using. Thus clients stay independent of the prevailing look and feel.

I was wondering what do the following mean:

To be portable across look-and-feel standards, an application should not hard-code its widgets for a particular look and feel.

and

Instantiating look-and-feel-specific classes of widgets throughout the application makes it hard to change the look and feel later.

In particular, without using an abstract factory class, what does the code look like and why is it bad? Thanks.

enter image description here

Mediator pattern with objects that self-manage

I have an object called UpdateManager that is used to collectively provide update ticks to objects it knows about. Think of this in a game context, where objects need regular update invocations to perform behavior within a scene based on time.

An object that wishes to be attached to UpdateManager has to derive from a class named UpdateReceiver. This object also maintains attaching/detaching to the UpdateManager, to eliminate some boilerplate code required by clients that are using this system.

Example code is below (live sample here):

class UpdateManager;

class UpdateReceiver
{
public:

    UpdateReceiver(std::shared_ptr<UpdateManager>& update_manager);

    virtual ~UpdateReceiver();

    virtual void Update(float dt) = 0;

private:

    std::weak_ptr<UpdateManager> m_updateManager;
};

class UpdateManager
{
public:

    void AddReceiver(UpdateReceiver& receiver)
    {
        std::cout << "Adding Receiver\n";
        m_updateReceivers.push_back(&receiver);
    }

    void RemoveReceiver(UpdateReceiver& receiver)
    {
        auto it = std::find(m_updateReceivers.begin(), m_updateReceivers.end(), &receiver);
        if (it != m_updateReceivers.end())
        {
            std::cout << "Removing Receiver\n";
            m_updateReceivers.erase(it);
        }
    }

    void Update()
    {
        for (auto& receiver : m_updateReceivers)
        {
            receiver->Update(1.f);
        }
    }

private:

    std::list<UpdateReceiver*> m_updateReceivers;
};


UpdateReceiver::UpdateReceiver(std::shared_ptr<UpdateManager>& update_manager)
    : m_updateManager(update_manager)
{
    update_manager->AddReceiver(*this);
}

UpdateReceiver::~UpdateReceiver()
{
    auto update_manager = m_updateManager.lock();
    if (update_manager)
    {
        update_manager->RemoveReceiver(*this);
    }
}

class Timer : public UpdateReceiver
{
public:

    Timer(std::shared_ptr<UpdateManager>& update_manager)
        : UpdateReceiver(update_manager)
    {}

    void Update(float dt) override
    {
        std::cout << "Updating Timer\n";
    }
};

And an example using the code above:

int main()
{
    auto update_manager = std::make_shared<UpdateManager>();

    {
        Timer t{update_manager};

        update_manager->Update();
    }
}

The idea is, the user creates a Timer (which implements UpdateReceiver) and provides it the required shared pointer to UpdateManager. The base class takes care of invoking AddReceiver and RemoveReceiver for clients of Timer, since this is considered boilerplate and this is less error-prone.

The code smell here that I want to be double-checked on is the circular dependency. I know that with the Mediator pattern, it's typical that the objects know about the mediator, and the mediator knows about the objects. But is it justified in this case? Is this design acceptable for the goals it is trying to solve?


Disclaimer: I originally posted this question on Code Review SE, but was told that SO might be a better fit. Originally I felt this question was a bit too open-ended, but I decided to post here anyway in hopes that it is mostly a good fit and doesn't get closed.

What does "a class instantiates another" mean?

From Design Pattern by GoF:

Another useful thing to show is which classes instantiate which others. We use a dashed arrowheaded line to indicate this, since OMT doesn't support it. We call this the "creates" relationship. The arrow points to the class that's instantiated. In Figure B.lc, CreationTool creates LineShape objects.

enter image description here

What does "a class instantiates another" mean here?

Thanks.

How to dynamically choose what html template to render. What type of design pattern is it?

Don't be confused with 'template type' definition. It is not related to angular. It only means that it's a template for concrete page, e.g. HomePageTemplateOne, HomePageTemplateTwo, etc

I have a home page, which I want to make dynamic, depending on what type of theme(template type) I requested for

Let me explain in details: I have one type of template for home page, which has title with orange background, 600px width logo, and footer with text: "This is footer." And data which I get from server would be:

{ 
   title: "Title", 
   titleBackground: "green", 
   logo: "someUrlForLogo",
   logoWidth: "600px",
   footer: "This is footer"
   templateType: "SimpleTemplate"
}

Also I want to have another theme(template type) for home page. Which data would be:

{ 
   title: "Title", 
   title-background: "orange", 
   topLogo: "someUrlForLogo",
   leftSideLogo: "antoherUrlForLogo",
   topLogoWidth: "600px",
   leftLogoWidth: "300px "
   description: "Here is my description",
   footerImagesUrls: [ "firstUrl", "secondUrl", "thirdUrl" ],
   footerImagesSize: "100px"
   templateType: "ComplexTemplate"
}

If I make check for every property in data - it will not be scalable. Something like:

switch(data.TemplateType) {
   case TemplateType.Simple {
      // renderSimpeTypeTemplateView with data
      break;
   },
   case TemplateType.Complex {
      // renderSimpeTypeTemplateView with data
  }
}

And could you please tell me what type of design pattern it would be

Thanx

Defining more models in a decorator

I have a pattern that I'd like to make as reproducible as possible, it goes something like this:

class TranslatedThing(models.Model):
  name = models.Charfield(max_length=100)

class Thing(models.Model):
  translation = models.ForeignKey(TranslatedThing)
  name = models.Charfield(max_length=100)

The idea being that in my raw data I have some Things, which map to a reduced set of translated Things. Across many different data sets I have many different types of Things.

I already use an Abstract class to reduce the complexity of this pattern:

class AbstractThing(models.Model):
  name = models.CharField(max_length=100)

  class Meta:
    abstract = True

-------

class TranslatedThing(AbstractThing):
  pass

class Thing(AbstractThing):
  translated = models.ForeignKey(TranslatedThing)

But I'd like to automate the creation and linkage to TranslatedThing. Is this possible with a decorator? e.g.

@translate
class Thing(AbstractThing): pass

----

Thing.objects.filter(translation__name="foo") #works

I've read through but it looks like maybe not. Is there any other way to reduce the repetition of code while using this pattern?

Is there a name for a group of views that are related by state, and hierarchical?

Example: I have an SPA Angular app.

There is a sale process which includes views for:

  1. Choose Customer
  2. Add Items to Work Order
  3. Cash Out Sale

These are related. You have to access them in order. I am confronting things like, state between routing, how to handle someone inputting URL to step 3, etc..

To research I would like to know if there is a name to this grouping?

Do Decorators in Python necessarily implement the Decorator Pattern?

In Python,

  1. Is it correct that decorators in Python can change the interface of the decorated function/class, e.g. change the signature of the decorated functions and methods of decorated class? For example:

    >>> def MyDecorator(func):
    ...     def NewFunc():
    ...         pass
    ...     return NewFunc
    ... 
    >>> @MyDecorator
    ... def MyFunc(a, b, c):
    ...     print(a,b,c)
    ...
    
    
  2. So decorators in Python are not necessarily used for implementing the decorator design pattern as described in the book "Design Pattern" by GoF?

  3. Is it a bad practice to write a decorator which change the interface of the decorated function/class?

Thanks.

Which pattern apply for versioning dto

I'm working witch different XML messages on my Grails application. The XML messages have this structure:

<tag>
    <head>
        <param></param>
        <param></param>
    </head>
    <a1xx>
        <param></param>
        <param></param>
        <param></param>
    <a1xx>
</tag>

where xx are diferent type of messages such as 01,02,03,04,etc...

Now I have to work with two different versions of this messages, so I will have the same structure but with different params, and I build this:

class XmlMessageFactory {
   A1XXMessageDto createMessage (MessageType type, MessageVersion version, Params params) {
       A1XXMessageDto a1xxMessage
       if(version==1){
           switch(type) {
           case type.1:
               a1xxMessage = new A102MessageDtoV1(params)
           case type.X:
               a1xxMessage = new A10XMessageDtoV1(params)        
           ....
           }
       } else {
           switch(type) {
           case type.1:
               a1xxMessage = new A102MessageDtoV2(params)
           case type.X:
               a1xxMessage = new A10XMessageDtoV2(params)        
           ....
           }
   }
}

A1XXMessageDto

class A1XXMessageDto {

    HeaderDto header
    BodyDto body

    public A1XXMessageDto(Params params) {
    }
}

A1XXMessageDtoV1/V2 (build the header for the version since the header is common on all the messages with same version)

class A1XXMessageDtoV2 extends A1XXMessageDto {   
    public A1XXMessageDtoV2(Params params) {
        super(params)
        header = new HeaderDtoV1/V2(paramas)
    }
}

HeaderDto

class HeaderDto {

    String commonParam1
    String commonParam2
    public HeaderDto(Params params) {
        commonParam1 = param.commonParam1
        commonParam2 = param.commonParam2
    }

}

HeaderDtoV1/V2 (specific header for each version with specific params)

class HeaderDtoV17V2 extends HeaderDto {
    String commonParamV2
    public HeaderDtoV2(Params params) {
        super(switchingProcess, message)
        commonParamV2 = param.commonParamV2  
    }

}

BodyDtoV1/V2 (specific body for each version with specific params)

class BodyDtoV1/V2 extends BodyDto {
    String extrainfo
    BodyDtoV2(Params params) {
        super(params)
        extrainfo = ""
    }
}

A101BodyDtoV1/V2 (specific data for each message and version)

class A101BodyDtoV2 extends BodyDtoV1/V2 {
    String specificParam1
    String specificParam2

    public A102BodyDtoV2(Params params) {
          commonParam1 = params.specificParam1
          commonParam2 = params.specificParam2
    }

}

A101MessageDtoV1/V2 (this class build the body for each message and version)

class A102MessageDtoV2 extends A1XXMessageDtoV2 {

    public A102MessageDtoV2(Params params) {
        super(params)
        body = new A102BodyDtoV2(params)
    }
}

And I have more classes like this last, for all other messages types.

But I think should be a best way to implement this, and get the posibility to extend it in the future.

So, Which pattern fit best with this structure?

Thanks!

JAVA Wrapping Socket as a Singleton class in a multiscreen Swing app

I am writing a chat application in Java swing which has a custom protocol and server backend using sockets. I am in the process of making the ClientSide connection handler. Here is my code up to this point:

package Client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.*;

import Common.Message;

public class ConnectionHandler {
    Socket socket;
    DataInputStream input;
    DataOutputStream output;

    public ConnectionHandler() throws UnknownHostException, IOException {
        socket = new Socket(Client.HOST_INET,Client.PORT);
        input = new DataInputStream(socket.getInputStream());
        output = new DataOutputStream(socket.getOutputStream());
    }

    public void sendMessage(Message message) throws IOException {
        output.writeUTF(Message.disasseble(message));
    }

    public Message getMessage() throws IOException {
        String message;
        message = input.readUTF();
        return Message.assemble(message);   
    }

    public void closeConnection() {

    }

    private void reconect(){

    }
}

The app is composed of a CardLauut holding the Login, Registration and and Chat JPanels. Each JPanel needs the connection and the connection should be maintained as long as the app is functioning. Login screen sends Login message/answer the same with Registration and of course the Chat screen.

QUESTION Should I use a singleton design pattern for the connectionHanler? And would the referece also work if it was on a separate thread like a connection thread with a que? (I know that I need to ping the server every now and then or connection can be lost so I need to reconect and let the UI know)

Persist items in list in C#

I am stuck with finding a solution for this scenario:

I have two datagrids (DevExpress). On left-side grid I have some templates values (rows). I have one move button between two grids, which on click event should perform moving selected item from left grid to right grid. Before it copy that value it should check does maybe that value already exists in right grid. If does: Show message that it already exists, if not, add selected value to right grid.

In code I have collections that are holding this values:

private void btnMove_Click(object sender, EventArgs e)
{
    ClosingStockTemplateModel _mClosingStockTemplateModel = (ClosingStockTemplateModel)gridViewAvailableTemplates.GetRow(gridViewAvailableTemplates.FocusedRowHandle);
    ClosingStockTemplateModel currentTemplateRow = new ClosingStockTemplateModel();
    ModelCollection<ClosingStockTemplateModel> currentTemplateList = new ModelCollection<ClosingStockTemplateModel>();

    for (var i = 0; i < currentTemplateList.Items.Count; i++)
    {
        currentTemplateRow = (ClosingStockTemplateModel)gridViewTemplatesToPrint.GetRow(i);
        currentTemplateList.Items.Add(currentTemplateRow);
    }

    if (currentTemplateList.Items.Contains(_mClosingStockTemplateModel))
    {
        MessageBox.Show("Item has already been selected.");
        return;
    }
    else
    {
        currentTemplateList.Items.Add(_mClosingStockTemplateModel);
        grdTemplatesToPrint.DataSource = null;
        grdTemplatesToPrint.DataSource = currentTemplateList.Items.OrderBy(i => i.TEMPLATE);
    }
}

gridViewAvailableTemplates - is left side grid. gridViewTemplatesToPrint - is right side grid.

What I am doing in this code is:

  1. Get currently selected row in left grid:
  2. Create new collection where I will add all items from right grid (I will use this later for comparing and checking what I have already selected).
  3. Add items to temporary collection with looping through right grid rows.
  4. Checking does currentTemplateList contains selected value.
  5. If yes, show message, if not add it to right grid by setting it's DataSource to currentTemplateList.Items.

The problem happens here:

ModelCollection<ClosingStockTemplateModel> currentTemplateList = new ModelCollection<ClosingStockTemplateModel>();

I need to make and instance of ModelCollection, but every time I click button Move list gets instantiated and it is cleared. So I've tried something like this:

ModelCollection<ClosingStockTemplateModel> currentTemplateList;
if(gridViewTemplatesToPrint.RowCount == 0)
{
    currentTemplateList = new ModelCollection<ClosingStockTemplateModel>();
}
else
{
    for (var i = 0; i < currentTemplateList.Items.Count; i++)
    {
        currentTemplateRow = (ClosingStockTemplateModel)gridViewTemplatesToPrint.GetRow(i);
        currentTemplateList.Items.Add(currentTemplateRow);
    }
}

Only to make a clean instance of currentTemplateList when move button is clicked for the first time and right side grid is still empty, but then I have problem with currentTemplateList being unknown local variable in else part. Is there some clean way to solve this? Because with this code, new items are not added to right sided grid, they are cleaned every time and on the right side I have only last moved item. I need to find a way to persist already selected items in collection when grid was not empty.

design pattern for masking group of objects as one

I'm working on a simple messaging app using Django. here is a problem I encountered.
I want users to be able to send message to a group of other users. I also want to show the last sent and received messages for each user.
the problem is when you send out a message to a lot of people. your messages Interface will be filled with the same message (one for each receiver).
what I want to do is have the same UI as group messaging in smartphones meaning all the messages in a group message will be shown as one unless someone answers the message in which case a new conversation will be displayed for that user. I don't want to create a new model (class) for group messages and it would be inefficient to manage this in front end level. is there any design pattern that helps me do this? how can I do this without iterating over all the messages and finding the ones that belong to the same group? thanks in advance.

what I have now:

  • message for person 1: hi
  • message for person 2: hi
  • message for person 3: hi
  • message for person 4: hi
  • message for person 5: hi | message from person 5: hello
  • message for person 6: hi

what I want:

  • message for person 1,2,3,4,6: hi
  • message for person 5: hi | message from person 5: hello

Reveal Module Pattern Counter Not Updating

I am struggling with the Modular Reveal Pattern. This small example illustrates the issue I am having. When the 'Add' button is clicked the 'counter' value increases by 1. When the 'Show' button is clicked Module_2 logs the change to Module_1's counter value. Unfortunately Module_2 doesn't detect the change.

Is there a way to get Module_2 to 'see' the change to the 'counter' in Module_1?

  var Module_1 = (function() {
    $("#test1").on("click", add);
    var counter = 0;
    function add() {counter += 1;}
    return {counter : counter};
  })();

  var Module_2 = (function() {
    $("#test2").on("click", Show);
    function Show() {console.log(Module_1.counter);}
  })();

mercredi 27 septembre 2017

Best way of handling socket.io events in node.js

Implementing a simple turn-based board game in node using websockets and my design for this is starting to look a little messy.

Basically i have the following questions

  • handle reconnects?? on connect im mapping socket ID -> express session ID... deleting it on disconnect and remapping on connect again.
  • Cleaning up inactive users, i.e. user has been disconnected for n time.
  • Nesting all socket event listeners inside on('connection')?? is there an alternative/what are pros/cons of it.

It just seems like too much manual tracking of state where i'm likely to miss something as it gets more complex, is there a cleaner way of handling this

  class GameManager {
    constructor(io) {
        let self = this;
        self.io = io;
        self.lfg = {};
        self.games = {};
        //socket ID -> session ID
        self.sockets = {}
        //sessionID -> gameID
        self.disconnected = {};
        io.sockets.on('connection', function (socket) {
            let sessionID = getSessionID(socket);
            self.sockets[socket.id] = sessionID;
            this.reconnect(sessionID);
            socket.on('disconnect', this.disconnect);
            socket.on('findMatch', this.findMatch);
        });
    }

    disconnect(socket) {
        let sessionID = this.sockets[socket.id];
        delete this.sockets(socket.id);
        //only add user if they were in-game
        self.disconnected[sessionID] = game ID
    }

    findMatch(socket){
        //match user in lfg, create new game, place users into socket room
    }

    reconnect(sessionID){
        if (sessionID in this.disconnected) {
            delete this.disconnected[sessionID];
            //remove disconnected expiry
        }
    }
}

Can someone explain how to do numpy correlation matrix?

I have two sets of values ranging from 3-27, that have 20 finite values:

A = [(0,21),(1,12),(2,15),(3,3),(4,21),(5,15),(6,28),(7,21),(8,9),(9,27),(10,12),(11,9),(12,12),(13,3),(14,9),(15,12),(16,6),(17,3),(18,9),(19,15)]

B = [(0,15),(1,3),(2,9),(3,9),(4,6),(5,15),(6,28),(7,21),(8,15),(9,24),(10,9),(11,12),(12,3),(13,12),(14,6),(15,15),(16,6),(17,6),(18,12),(19,18)]

And I have the one that has index/keys that are a reference in place if the first value were set to 0:

Z = [(0,16),(0,16),(2,20),(0,16),(4,28),(0,16),(6,9),(0,16),(0,16),(0,16),(10,11),(11,3),(,(13,8),(16,29)]

I was told that I could create 'bins' for the integers in 'A' and 'B', and I was told I could turn those bins into ranges (-1,+1) for each integer. So I would then create 10 bins '(2,3,4),(5,6,7),(8,9,10),..(26,27,28)'.

I'd like to learn how to do a pattern match of Z over A and B, iterating through both until the most values match the pattern in index/key and integer range and it giving me the number of matches as well as the place in A and B that those matches start.

Could someone teach me how I would do such a thing?

how the logger{36} working here

I have user above code in my log4j2 xml file to filter the logs. But I don't know how the pattern is working. Especially logger{36}. Please help me some to know how the logger{36} is working.

Multi-Rendering API Engine shader file management

I am developing a 3D engine that is designed to support the implementation of any given graphics API. I would like your feedback on how I'm planning to manage the shader files:

I thought about creating a struct that contains 3 string variables, the directory and the file name (both vertex and fragment), something like this:

class ShaderFile : public SerializableAsset
{
    std::string nameID; //Identifier
    std::string directory;
    std::string vertexName;
    std::string fragmentName;
};

The user would be able to set these variables in the editor. Then, my engine would load the shader files in like:

void createShader(RenderAPI api)
{
    ShaderFile shaderFile //Get it from some place
    std::string vertexPath = shaderFile.directory + shader.vertexName + api.name + api.extension;
    std::string fragmentPath = shaderFile.directory + shader.fragmentName + api.name + api.extension;
    //Create shader...
}

Which would create something like: Project/Assets/Shaders/standardVulkan.spv.

Am I thinking in the right direction or is this a completely idiotic approach? Any feedback

What design pattern is this? Adapter?

I am having a hard time defining a pattern. My colleague says it's adaptor pattern. I'm not sure. We're stuck mainly because we want to correctly name our components.

Question: Is it adapter pattern? If not what is it?

To put it in summary, it is a main component(is this the adapter?) that shares an interfaces with sub-components (are these providers?). The main components decides/orchestrates which of the sub-components are called.

Assumptions:

  1. For simplicity, we will ignore DR/IoC for now, but we understand and apply the pattern/principle.
  2. The code is not the best implemented form...feel free to suggest.
  3. My use of the words main/sub does not infer some kind of inheritence...just bad naming on my part, if confusing.
  4. It's language-agnostic, because I love contributions from C# and Java guys, and the knowledge they share.

I am using a Social Networking scenario where a main component gets stats on a hastag and instantiates the appropriate Social Sub Component ( There is a Social Component interface:

ISocialComponent
{
    SomeStatsObject GetStats(string hashTag);
}

Social Sub-Components implement ISocialComponent Interface

Twitter Sub-Component

public class TwitterSubComponent : ISocialComponent
{
    public SomeStatsObject GetStats(string hashTag)
    {
        return SomeMethodThatReturnsStatsObject(hashTag);   
    }

    private SomeMethodThatReturnsStatsObject(string hashTag)
    {
        //... Twitter-specific code goes here
    }
}

Facebook Sub-Component

public class FacebookSubComponent : ISocialComponent
{
    public SomeStatsObject GetStats(string hashTag)
    {
        return SomeMethodThatReturnsStatsObject(hashTag);
    }

    private SomeMethodThatReturnsStatsObject(string hashTag)
    {
        //... Facebook-specific code goes here
    }
}

Instagram Sub-Component

public class InstagramSubComponent : ISocialComponent
{
    public SomeStatsObject GetStats(string hashTag)
    {
        return SomeMethodThatReturnsStatsObject(hasTag);
    }

    private SomeMethodThatReturnsStatsObject(string hashTag)
    {
        //... Instagram-specific code goes here
    }
}

Main Component

There is a main social component object that calls any one of the Sub-Components (defined below) that implement the shared ISocialComponent interface

public class MainSocialComponent : ISocialComponent
{
    //this is an enum
    private RequestedNetwork _requestedNetwork{ get; set;}

    public SomeStatsObject GetStats(string hashTag) 
    {
        switch(_requestedNetwork)
        {
            case RequestedNetwork.Twitter:
                var twit = new TwitterSubComponent();
                return twit.GetStats(hashTag)
                break;

            case RequestedNetwork.Facebook:
                var fb = new FacebookSubComponent();
                return fb.GetStats(hashTag)
                break;

            case RequestedNetwork.Instagram:
                var in = new InstagramSubComponent();
                return in.GetStats(hashTag)
                break;

            default:
                throw new Exception("Undefined Social Network");
                break;
        }
    }
}

VBA Access - 'Design Patterns' / Best Practices

Our office got an Access/SQL_Server database that has been used and developed over several years. I am tasked with rewriting the system section by section using design principles to achieve better maintain & upgrade ability.

Question: If you are forced to use MS Access VBA, is there 'Design Patterns' or Best Practices that can be followed to deal with VBA development?

View Classes: I'm thinking of building "view" classes for entities and invoking these classes from a switchboard or from any form anywhere as needed.

Model Classes: How do you handle "model" classes? - I don't think creating a private class variable for every column is a good idea especially if you are going to make use of SQL, then again complicated computations or automated tasks could benefit form this. However this would slow down processing if you say use DAO to read the records into the model class

Passing a Class Variable to SQL: What if I got a class and I want to run a method like a.showReport(ID as Long). How would I pass an ID variable to the SQL query underneath the report?

Option A.) Write the SQL for such a report in VBA - but doesn't this obfuscate the SQL? And if a developer later on make changes to the table structure then he got to search all the classes through to update the SQL written in VBA, which in my eyes is harder than updating a saved access query.

Option B.) Write a set class method that then set a public variable used in a module function which in turn is then called by the SQL query! - Needless to say this might complicate things and the SQL will have to make a call to the function for every record which could cause performance issues (if only SQL had a way to directly call an class method?)

Option C.) Just build a simple query(saved in access outside the class) to filter on say a variable in a Form with a report on top - but then I would need to write a new query and report for every new scenario and build that into the class, also another big drawback is that the query/report is now closely coupled with the form and cant be used with out it

Naming Standards(especial query names): What are good practices? - As one can imagine after a few years of ad-hoc development there are objects all over the place, especially queries. The current db got queries that is stacked on queries which is stacked again and again (in cases where there are a lot of computations such as a payment advice) and just to add to the mess if a developer missed something and had to squeeze a query in to the middle of the query stack... let me just say the way we are naming objects now, it is not working

How is data binding different from using an interface?

With MVVM, the ViewModel replaces the Presenter in driving the View. The differece is that the ViewModel drives the view with DataBinding, while the Presenter drives the view with an interface.

The quote is taken from this site.

I'm having trouble finding good explanations of:

  1. What is an interface?
  2. What is data Binding?
  3. How are they different?
  4. How do their differences translate to MVVM vs MVP?

Why do we need service layer?

I'm currently learning Spring Boot and I've seen how people create a controller, inject the service class and in the service class inject the repository.

Why do we need the service class as a middleman and why can't we just inject the repository into controller?

Here's the tutorial that confused me: https://www.youtube.com/watch?v=lpcOSXWPXTk&list=PLqq-6Pq4lTTbx8p2oCgcAQGQyqN8XeA1x

is it wrong to set viewModel as table views datasource?

I have seen many applications that set ViewModel as a table view data source, and many which don't.

1.Setting data source to the ViewModel some time makes sense as the data source methods mainly deal with the presentation logic.

2.On the other hand setting the ViewModel as the data source implies that you are implementing "cellForRowAtIndexPath" etc which makes it not independent of UIkit.

What is the best way to architecture your apps, Kindly clarify?

Which framework or design patterns to use

I have 3 web applications of 3 different regions running in 3 different server. These 3 applications are more or less same .it has some region specific customization.say for member page if user is from gulf then we will show 5 fields, if user is from other region then we will show 10 fields and so on. So we are managing three different codebase for three different region. Say these 3 applications is devOpgulf, devopUK, devOpUSA.

Now we want to merge these applications in one code base.thought is that we will provide a drop down at the time of login where user can select the region gulf, uk, usa and based on that user will be logged in to a particular region and we will show the region specific page.

node socket app new instance scope

it is a simple socket app using event base pattern

const invitation = require('./invitation');
module.exports = function(io){
    io.on('connection', (socket)=>{
        var prepareGame = new PrepareGame(socket)
        socket.on("sendInvitation",(data, ack)=>{
            prepareGame.sendInvitation(data,ack)
        });
    });
}

and in prepareGame.js

const events = require('events');
const util = require('util');

class PrepareGame extends events {
    constructor(socket) {
        super();
        this.user = socket.user
        var self = this

        draftInvitation(data){
            this.newInvitation = {
                from_user: self.user.id,
                to_user: data.to_user,
                message:data.message,
                created_at:moment().unix(),
            }
            return this
        };

        self.on("toSocket", (eventName, clientId, data) => {
            console.log(` ===>>>> sending to listener ${eventName}`, clientId);
            var client  = users[clientId]
            if(client)
                client.emit(eventName, data)
        });

    }

    // public function
    sendInvitation(data, ack) {
        // console.log(this);
        var self = this
        data.message = 'New Invitation'
        draftInvitation(data)
        .emit("toSocket", "getInvitation", data.to_user, self.newInvitation)

        setTimeout(()=>{
            data.message = 'Invitation timeout'
            draftInvitation(data)
            .emit("toSocket", "getInvitation", self.user.id, self.newInvitation)
        }, 15000)

        if(typeof ack == 'function')
            ack({
                status:200,
                message: "invitation sent",
            })
    }
}

util.inherits(PrepareGame, events.EventEmitter )

module.exports =  PrepareGame

code is sum of different design pattern. it's working fine but I've some queries

  1. io.connection called once to connect to socket and prepareGame instance created. considering two instance for two user then how sendInvitation automatically bound correct instance when calling
  2. what happen with new prepareGame instance when socket disconnect ?
  3. i want to remove (data, ack)=>{ } encloser from socket.on mean it should socket.on ("sendInvitation",prepareGame.sendInvitation) then how to manage this reference in sendInvitation function

mardi 26 septembre 2017

Dynamic builder pattern for test fixture workflows

I am writing an automated testing framework for a web application in which the central domain object is shared between users through different independent workflows. These workflows generate data elsewhere in the system, leaving a wake of data that references the domain object, and only in some cases update properties on that object.

It is impractical and redundant to automate a user's actions on the front-end through the same workflow more than once to test some number of follow-up actions after that workflow has been executed.

In order to create data fixtures to run my tests, I would like to implement something like a builder pattern to build both the domain object and the "wake" of data that would result from following some workflow involving that object.

However, I would like to limit the callable methods on the builder in such a way that corresponds to the business logic of the system, such that only methods that make sense from a business perspective could be chained together. I am thinking of creating an extension method that casts the underlying object to some subclass which implements an interface that defines the methods on that workflow, but I'm not sure if this is possible, or even a decent way to solve the problem.

In the example below, if I am building something spoon-like in my workflow, I should not be able to call DrillButtonHoles(). Doing so should modify the object being built into something "ButtonLike," and upon which only methods pertaining to the "Button workflow" can be called. Likewise, if I am building something button-like in my workflow, I should not be able to call SandSpoonHandle().

The ProductBuilder class:

public class ProductBuilder
    {
        private BlockOfWood _blockOfWood;

        public ProductBuilder(int blockNumber)
        {
            _blockOfWood.BlockNumber = blockNumber;
        }

        public ProductBuilder Create()
        {
            _blockOfWood = new BlockOfWood();
            return this;
        }

        public ProductBuilder WithBuildStart(DateTime buildStart)
        {
            _blockOfWood.OperationsStarted = buildStart;
            return this;
        }

        public ProductBuilder AddButtonHoles(int numberOfHoles)
        {
            // The methods here create data with FK to the blockNumber.
            DrillingOperations.DrillButtonHoles(_blockOfWood.BlockNumber, numberOfHoles);
            // ...
            // save changes to database
            // Here the type of Product should change 
            // to something like Button : BlockOfWood 
            return this;
        }

        public ProductBuilder SandSpoonHandle(string grit)
        {
            // The methods here create data with FK to the blockNumber.
            SandingOperations.SandSpoon(_blockOfWood.BlockNumber, grit);

            // save changes to database
            // Here the type of Product should change 
            // to something like Spoon : BlockOfWood 
            return this;
        }
    }

Some domain object:

public class BlockOfWood
{
    public int BlockNumber { get; set; }
    public DateTime OperationsStarted { get; set; }
    // ...
}

Some test requiring a specific workflow to have been executed:

    public void User_Can_Eat_Cereal()
    {
        // I can do this:
        var spoon = new ProductBuilder(123);
        spoon.SandSpoonHandle("Fine");

        // but I wouldn't like this to be possible:
        spoon.SandSpoonHandle("Fine").AddButtonHoles(2);

        // Some action
        // Some assertion
    }
}

what is the best algorithm for two way binding?

what is the best algorithm for two way binding??

DAO as Service vs DAO as Library

I have 3 different services which needs to access same database. Each of these service will serve different purpose and different queries. I can generalize them in following way

  1. Service 1 -> Customer Inquires
  2. Service 2 -> Order Processor (e.g.workflow for placed orders)
  3. Service 3 -> Reporting

I have written a DAO to expose data. I am evaluating two system designs for scalability and maintenance.

Option 1: Write one more service to expose DAO functionality as Data Service.

Pros: - Load on database will be controlled and easy to scale-in/out as needed - Easy to maintain for future updates - Access control for various actions - clients doesn't have full access on underlying database

Cons: - single point of failure - management of extra service - Need to enforce backward compatibility rules - In case of DataService downtime every service is affected (factors other than database downtime)

And

Option 2: Create a storage library out of DAO and use these library in above mentioned three services.

Pros: - distributed, impact radius is very small

Cons: - Every service get full access on database - Needs to update all three services for new features

Which option is good and why? Any other ideas/architecture designs to consider? What are the things I need to consider when choosing architecture?

Role of Creator in Factory Pattern

I couldn't understand the role of defining an abstract class / interface for the factory class, which is something i always see in all tutorials on the web. Can somebody please put some light on the importance of CreatorInterface ? Reference UML Diagram of the Factory Pattern

To put in code form, here's what i have :

// Product
public abstract class Vehicle
{
     public string VehicleType { get; set; }
}

// Concrete Product
public class Bike : Vehicle
{
    public Bike()
    {
        VehicleType = "Two Wheeler";
    }
}

// Concrete Product
public class Car : Vehicle
{
    public Car()
    {
        VehicleType = "Four Wheeler";
    }
}

// Concrete Factory
public class VehicleFactory
{
     public Vehicle GetVehicle(string VehicleType)
    {
        if (VehicleType == "Bike")
            return new Bike();
        else if (VehicleType == "Car")
            return new Car();
        else
            return null;
    }
}

// Client class
public class ClientClass
{
    public void Main()
    {
        VehicleFactory VehicleFactoryObj = new VehicleFactory();
        Vehicle BikeObj = VehicleFactoryObj.GetVehicle("Bike");
        Vehicle CarObj = VehicleFactoryObj.GetVehicle("Car");
    }
}

The above code doesn't contain any abstract class for the 'VehicleFactory' class. But it works fine. Now, what can be the reasons for adding an abstract class for the 'VehicleFactory' ?

Thanks in advance !! :-)

What classes and architecture to be used for following requirement

I have to implement a requirement using C# language. The requirement is as follows.

  1. Take data from different locations : I will use inbuilt API for fetching the data, hence do not worry about this part. The data is to be fetched for 10 different tables and these data are not related.
  2. Create 10 different csv files with different 1st column names
  3. Write data to different csv files.

I have to use C# language to develop code.

I know a basic idea as follows, but i require a better method for solving the requirement.

Method 1 :

abstract CsvParent
{
    public void SaveToCsv(String x);
    ...           
}

Nested switches or multiple functions, what would be a better design?

I have a large method that looks something like this

void operate(Provider provider, Method method) {
    switch (provider) {
        case PROVIDER_1:
            //TODO Do common things to provider 1
            switch (method) {
                case METHOD_1:
                    break;
                case METHOD_2:
                    break;
                case METHOD_3:
                    break;
            }
            break;
        case PROVIDER_2:
            switch (method) {
                case METHOD_1:
                    break;
                case METHOD_2:
                    break;
                case METHOD_3:
                    break;
            }
            break;
    }

So each time I need to add a provider I'll need to add a case to that provider and then repeat the method switch for this new provider.

I got a suggestion from a fellow that should be split into methods for each method so for example instead of the above, it'll be

void operateByMethod1(Provider provider) {
    switch (provider) {
        case PROVIDER_1:
            //TODO Do common things to provider 1
            break;
        case PROVIDER_2:
            break;
    }

void operateByMethod2(Provider provider) {
    switch (provider) {
        case PROVIDER_1:
            //TODO Do common things to provider 1
            break;
        case PROVIDER_2:
            break;
    }

void operateByMethod3(Provider provider) {
    switch (provider) {
        case PROVIDER_1:
            //TODO Do common things to provider 1
            break;
        case PROVIDER_2:
            break;
    }


Personal thoughts: Maybe splitting into multiple methods makes it more cleaner but if I need to do common stuff to PROVIDER_1 (despite the method) then this common thing will need to be repeated/duplicated in each method (as indicated by the //TODOs in the above code) which kinda means more lines of code but that's a bit irrelevant maybe.

I'd like to hear some thoughts about this, which would you consider more readable and more clean? Any better alternatives?

lundi 25 septembre 2017

Generic Factory Pattern

Trying to convert a multiple DTO objects to the respective entities. Source is an excel document, each worksheet has unrelated to each other DTO objects. Let's assume that the first worksheet has name = "Products" and the related classes are:

class Product
{
    public int Id { get; set; }
    public string Description { get; set; }
}

class ProductDto
{
    public string Description { get; set; }
}

There are multiple sheets, each sheet has the DTO and I am trying to map it to the respective entity.

And the FactoryPattern will be:

public class FactoryPattern<K, T> where T : class, K, new()
{
    public static K CreateInstance()
    {
        K o;
        o = new T();
        return o;
    }
}

public class FactoryClass<T> where T : class
{
    public static IGenericReader<T> CreateInstance(string identifier)
    {
        switch (identifier)
        {
            case "Product":
                return (IGenericReader<T>) FactoryPattern<IGenericReader<Product>, ProductReader>.CreateInstance();
            //case "Business":
            //    return (IGenericReader<T>)FactoryPattern<IGenericReader<Business>, BusinessReader>.CreateInstance();
            default:
                throw new ArgumentException();
        }
    }
}

A reader implements this interface:

public interface IGenericReader<T>
{
    IEnumerable<T> Read(string item);
}

The implementation of the ProductReader is:

class ProductReader : IGenericReader<Product>
{
    public IEnumerable<Product> Read(string workSheetName)
    {
        return new List<Product>
        {
            new Product{Id = 5, Description = "ProductE"}
        };
    }

}

Currently my client code is like:

var reader = FactoryClass<Product>.CreateInstance("Product");
var values = reader.Read((List<ProductDto>)productDtos);

Could I abstract it somehow even more, in order for it to be like:

var reader = FactoryClass.CreateInstance(workSheet.Name);
var values = reader.Read(workSheet);

in order to have the code mentioned above in a tight loop that will iterate the worksheets of the excel document. I feel that having the worksheet name is enough identifier to instantiate the proper reader that gets the dto object or list of dto objects, and returns the entity object or list of entity objects.

Thanks

Good design for converting a String to different type in Java

I have a class Data that stores a single piece of data in form of a String, it also stores type to which this data should be converted, the type is stored as an enum constant (to allow only for specyfic types). Data objects that describe one item are stored in DataItem class. Intention is that the Data object corresponds to a field in a table and DataItem represents a full row. It is also important to mention that Data objects are created from DataTemplate class which specifies where to look for this kind of data and its type (so the type of each Data should be known at compile time).

I want this program to be very flexible when it comes to database choice so method "save" comes from Storage interface that allows to use any type of storage (file/RDB/Document database...) after implementing it.

I wonder about a good way of converting those String values from Data objects to the appropriate types so I can save them to database. An easy way would be to use something like this:

public void save(DataItem dataItem) {
    for (Data data : dataItem) {
        if (data.getType() == DataType.BOOLEAN) {
            // Convert to String to boolean and save
        }
        else if (data.getType() == DataType.DOUBLE) {
            // Convert to String to double and save
        }
        ...
    }
}

But it's not a very good design as I would have to repeat this code for each implemenation of save. It also violates open/closed principle, because if I add some new types I would have to modify all the save methods.

I have also tried using generics or reflection but none of those implementations was satisfactory.

One generic solution that I came up with would require user to to use one of the provided enum constants but then instead of storing enum constant, Data class would store Class instance of corresponding type. That way I stil control what types can be used and get compile time errors if wrong class is picked. This would allow me to implement converter method that works this way.

public <T> T convert(Data data, Class<T> clazz) {
    if (data.getType() == Boolean.class) {
        // Convert String to Boolean
        return (T) 
    }
    else if (data.getType() == Double.class) {
            // Convert to String to Double
            return (T)
    }
    ...
}

Then I could also use similar pattern and store converting methods in DataType enum alongside allowed data types. Using abstract method that every type would have to specify. Something like:

public enum DataType {
    BOOLEAN(Boolean.class){
        @Override
        public <T> T convert(Data data, Class<T> clazz) {
            return clazz.cast(Boolean.parseBoolean(data.getContent()));
        }
    },
    DOUBLE(Double.class){
        @Override
        public <T> T convert(Data data, Class<T> clazz) {
            return clazz.cast(Double.parseDouble(data.getContent()));
        }
    },
    ...;
    ...
    public abstract <T> T convert(Data data, Class<T> clazz);
}

In that case I would just have to modify the DataType enum when adding a new type, provided that underlying storage has a method accepting all of the allowed types.

So finally, my questions: 1. Is there a better way to do this? 2. If no, which design should I choose?

Strategy design pattern in swift

I am currently learning design patterns with the Head First Design Patterns: A Brain-Friendly Guide book. I was trying to replicate their java code onto swift code like so:

protocol Flyable: class {
    func fly()
}

class Duck {

    weak var flyBehavior: Flyable?

    func fly() {
        flyBehavior?.fly()
    }
}

class MallardDuck: Duck {

    func LoadBehaviors() {
        self.flyBehavior = FlyWithJet()
    }
}

class FlyWithJet: Flyable {

    func fly() {
        print("Fly with a jet on my back!")
    }
}

class FlyWithWings: Flyable {
    func fly() {
        print("Fly with my wings!")
    }
}

let md = MallardDuck()
md.LoadBehaviors()
md.fly() //*Nothings*

I have a super class called Duck and MallardDuck inherits from it. In my Duck class, I have a fly() method and the implementation of it is delegated out to a class that conforms to the flyable protocol. Howcome, in the MallardDuck class, when I assign my flying behavior to FlyWithJet(), and when I call the fly() method on MallardDuck, I got a nil back?

Any feedbacks are welcome!

WPF: Mechanism or design pattern for property meta data

I'm starting a big WPF project and I'm thinking about how to manage a specific aspect of it, which is data validation.

The way I see it, any property in a Model should have some basic properties of its own, such as MaxLength, MinLength, IsRequired, AcceptsNulls, etc. These properties will often be bound to some aspects of a XAML file, such as custom ControlTemplate for controls bound to properties where IsRequired = true, setting MaxLength automatically on TextBoxes, etc.

I could create a class similar to this one:

public class PropertyMetaData<T> {
    public int MaxLength { get; set }
    public bool IsRequired { get; set; }
}

and then my model will have something like:

public MyClass {
    public PropertyMetaData<string> Name { get; set; }
}

Now I can bind a XAML element like this:

<TextBox Text="{Binding Name}" MaxLength="{Binding Name.MaxLength}" DataTemplateSelector="{Binding Name.IsRequired, ValueConverter={...}}"/>

  • etc.

This makes general sense to me, but when you get down to implementation, there are a few little caveats that I need to resolve.

Now, I simply don't want to re-invent the wheel. So I looked it up on Google and couldn't find out: Is there some built-in mechanism for this in WPF? Perhaps a design pattern?

Any help will be appreciated!

Effect in application performance by Repository pattern and Unit of work with entity framework in asp.net mvc

I am working with a database where I have more than 75 tables and I am using repository pattern and unit of work with entity framework on asp.net mvc project. I am little bit confuse and some query in my mind about object creation. when unitofwork initialize, it create object for all table's entity which is present in unitofwork. so it can be heavy for application load.

Here is the interface of unit of work:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Application.Repository;
using Application.Repository.General;

namespace Application.UnitOfWorks
{
    public interface IUnitOfWork : IDisposable
    {
        IGeneralRegionMasterRepository GeneralRegionMasters { get; }
        IGeneralSubRegionMasterRepository GeneralSubRegionMasters { get; }
        IGeneralCountryMasterRepository GeneralCountryMasters { get; }
        IGeneralStateMasterRepository GeneralStateMasters { get; }
        IGeneralCityMasterRepository GeneralCityMasters { get; }



        int Complete();
    }
}

Implementation:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Application.EntityFramework;
using Application.Repository;
using Application.Repository.General;

namespace Application.UnitOfWorks
{
    public class UnitOfWork : IUnitOfWork
    {
        public readonly MSBMInventoryDbContext _context;
        public UnitOfWork(MSBMInventoryDbContext context)
        {
            _context = context;
            GeneralRegionMasters = new GeneralRegionMasterRepository(_context);
            GeneralSubRegionMasters = new GeneralSubRegionMasterRepository(_context);
            GeneralCountryMasters = new GeneralCountryMasterRepository(_context);
            GeneralStateMasters = new GeneralStateMasterRepository(_context);
            GeneralCityMasters = new GeneralCityMasterRepository(_context);
        }

        public IGeneralRegionMasterRepository GeneralRegionMasters { get; private set; }
        public IGeneralSubRegionMasterRepository GeneralSubRegionMasters { get; private set; }
        public IGeneralCountryMasterRepository GeneralCountryMasters { get; private set; }
        public IGeneralStateMasterRepository GeneralStateMasters { get; private set; }
        public IGeneralCityMasterRepository GeneralCityMasters { get; private set; }

        public int Complete()
        {
            return _context.SaveChanges();
        }

        public void Dispose()
        {
            _context.Dispose();
        }
    }
}

I want to know about performance effect of it on application. thank you in advance for help.

Factory pattern - how to avoid switch construction?

I use simple Factory pattern, look at screen, please:

enter image description here

As you can see I use switch operator to choose object and create instance.

But if there are over 100 classes? Problem is came. How to avoid switch construction? Using interface?

Ninject error: More than one matching bindings are available

I'm messing around with Ninject and MVC and design partterns. In my simple application I have a structure like this:

(the abstract classes)

  • interface ICoffee
  • abstract class Coffee: ICoffee

(couple of classes)

  • public class Espresso : Coffee, ICoffee
  • public class Cappuccino: Coffee, ICoffee
  • public class Late: Coffee, ICoffee

(couple of decorator classes)

  • public class Milk : ICoffee
  • public class Chocolate: ICoffee

The decorator classes accept a parameter of type ICoffee , change some settings and then return it.

Then I have the following classes:

  public abstract class CoffeeStore : ICoffeeStore
{
    private readonly IProcessedOrderFactory processedOrderFactory;
    private readonly IDictionary<string, Func<ICoffee, ICoffee>> condimentsStrategies;

    public CoffeeStore(
        IProcessedOrderFactory processedOrderFactory,
        IDictionary<string, Func<ICoffee, ICoffee>> condimentsStrategies)
    {
        if (condimentsStrategies == null)
        {
            throw new ArgumentNullException(nameof(condimentsStrategies));
        }

        if (processedOrderFactory == null)
        {
            throw new ArgumentNullException(nameof(processedOrderFactory));
        }

        this.processedOrderFactory = processedOrderFactory;
        this.condimentsStrategies = condimentsStrategies;
    }

    public IProcessedOrder ProcessOrder(IOrder order)
    {
        ICoffee coffee;

        var coffeeType = order.SelectedCoffeeType;

        CoffeSizeType coffeeSize;
        Enum.TryParse(order.SelectedCoffeeSize, out coffeeSize);

        coffee = this.CreateCoffee(coffeeType, coffeeSize);

        foreach (var condimentAsString in order.SelectedCoffeeCodimentsList)
        {
            if (!this.condimentsStrategies.ContainsKey(condimentAsString))
            {
                throw new ArgumentException(condimentAsString);
            }

            //error occurs on the following line:
            coffee = this.condimentsStrategies[condimentAsString](coffee); 
        }

        var processedOrder = this.processedOrderFactory.CreateOrder(coffee);

        return processedOrder;
    }

    // abstract factory method
    protected abstract ICoffee CreateCoffee(string coffeeType, CoffeSizeType size);
}

and

 public class SofiaCoffeeStore : CoffeeStore
{
    private readonly IDictionary<string, Func<CoffeSizeType, ICoffee>> strategies;

    public SofiaCoffeeStore(
        IProcessedOrderFactory processedOrderFactory,
        IDictionary<string, Func<ICoffee, ICoffee>> condimentsStrategies,
        IDictionary<string, Func<CoffeSizeType, ICoffee>> strategies)
        : base(processedOrderFactory, condimentsStrategies)
    {
        if (strategies == null)
        {
            throw new ArgumentNullException(nameof(strategies));
        }

        this.strategies = strategies;
    }

    protected override ICoffee CreateCoffee(string coffeeType, CoffeSizeType size)
    {
        if (!this.strategies.ContainsKey(coffeeType))
        {
            throw new ArgumentNullException();
        }

        return this.strategies[coffeeType](size);
    }
}

also the ninject registering module looks like this:

private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind(x => x
         .FromAssemblyContaining<ICoffee>()
         .SelectAllClasses()
         .Excluding<ICoffee>()
         .BindAllInterfaces());

        kernel.Bind(x => x
        .FromAssemblyContaining<ICoffee>()
        .SelectAllInterfaces()
        .EndingWith("Factory")
        .BindToFactory());

        kernel.Bind<ICoffee>().To<Americano>().NamedLikeFactoryMethod((ICoffeeTypeFactory f) => f.GetAmericano(default(CoffeSizeType)));
        kernel.Bind<ICoffee>().To<Cappuccino>().NamedLikeFactoryMethod((ICoffeeTypeFactory f) => f.GetCappucino(default(CoffeSizeType)));
        kernel.Bind<ICoffee>().To<Espresso>().NamedLikeFactoryMethod((ICoffeeTypeFactory f) => f.GetEspresso(default(CoffeSizeType)));
        kernel.Bind<ICoffee>().To<Latte>().NamedLikeFactoryMethod((ICoffeeTypeFactory f) => f.GetLatte(default(CoffeSizeType)));
        kernel.Bind<ICoffee>().To<Ristretto>().NamedLikeFactoryMethod((IPlovdivStoreCoffeeTypeFactory f) => f.GetRistretto(default(CoffeSizeType)));
        kernel.Bind<ICoffee>().To<Doppio>().NamedLikeFactoryMethod((ISofiaStoreCoffeeTypeFactory f) => f.GetDoppio(default(CoffeSizeType)));

        kernel.Bind<ICoffee>().To<Caramel>().NamedLikeFactoryMethod((ICondimentsFactory f) => f.GetCaramel(default(ICoffee)));
        kernel.Bind<ICoffee>().To<Chocolate>().NamedLikeFactoryMethod((ICondimentsFactory f) => f.GetChocolate(default(ICoffee)));
        kernel.Bind<ICoffee>().To<Cinnamon>().NamedLikeFactoryMethod((ICondimentsFactory f) => f.GetCinnamon(default(ICoffee)));
        kernel.Bind<ICoffee>().To<Milk>().NamedLikeFactoryMethod((ICondimentsFactory f) => f.GetMilk(default(ICoffee)));
        kernel.Bind<ICoffee>().To<WhippedCream>().NamedLikeFactoryMethod((ICondimentsFactory f) => f.GetWhippedCream(default(ICoffee)));

        var sofiaStoreStrategies = new Dictionary<string, Func<CoffeSizeType, ICoffee>>
        {
            { "Americano", kernel.Get<ICoffeeTypeFactory>().GetAmericano },
            { "Capuccino", kernel.Get<ICoffeeTypeFactory>().GetCappucino },
            { "Espresso", kernel.Get<ICoffeeTypeFactory>().GetEspresso },
            { "Latte", kernel.Get<ICoffeeTypeFactory>().GetLatte },
            { "Doppio", kernel.Get<ISofiaStoreCoffeeTypeFactory>().GetDoppio },
        };

        var plovdivStoreStrategies = new Dictionary<string, Func<CoffeSizeType, ICoffee>>
        {
            { "Americano", kernel.Get<ICoffeeTypeFactory>().GetAmericano },
            { "Capuccino", kernel.Get<ICoffeeTypeFactory>().GetCappucino },
            { "Espresso", kernel.Get<ICoffeeTypeFactory>().GetEspresso },
            { "Latte", kernel.Get<ICoffeeTypeFactory>().GetLatte },
            { "Ristretto", kernel.Get<IPlovdivStoreCoffeeTypeFactory>().GetRistretto },
        };

        var condimentsStrategies = new Dictionary<string, Func<ICoffee, ICoffee>>
        {
            { "Milk", kernel.Get<ICondimentsFactory>().GetMilk },
            { "Caramel", kernel.Get<ICondimentsFactory>().GetCaramel },
            { "Chocolate", kernel.Get<ICondimentsFactory>().GetChocolate },
            { "Cinnamon", kernel.Get<ICondimentsFactory>().GetCinnamon },
            { "Whipped cream", kernel.Get<ICondimentsFactory>().GetWhippedCream },
        };


        kernel.Bind<IDictionary<string, Func<CoffeSizeType, ICoffee>>>().ToConstant(sofiaStoreStrategies)
            .WhenInjectedInto<SofiaCoffeeStore>();
        kernel.Bind<IDictionary<string, Func<CoffeSizeType, ICoffee>>>().ToConstant(plovdivStoreStrategies)
            .WhenInjectedInto<PlovdivCoffeeStore>();
        kernel.Bind<IDictionary<string, Func<ICoffee, ICoffee>>>().ToConstant(condimentsStrategies)
                .WhenInjectedInto<CoffeeStore>();

       //some more bellow
    }

An error occurs in method ProcessOrder (class CoffeeStore).

Ninject.ActivationException occurred
HResult=0x80131500
Message=Error activating ICoffee
More than one matching bindings are available.
Matching bindings:
1) binding from ICoffee to Caramel
2) binding from ICoffee to Chocolate
3) binding from ICoffee to Cinnamon
 .....
22) binding from ICoffee to WhippedCream
Activation path:
2) Injection of dependency ICoffee into parameter coffee of constructor of type Cinnamon
1) Request for ICoffee
Suggestions:
1) Ensure that you have defined a binding for ICoffee only once.

I'm collecting user input as string from 3-stage wizard form and then use it at once for object initialization. Hope the code I shared is enough to get an idea what i'm trying to do next: First I want to initialize one of the coffee type classes and then to decorate the object with one or more of the decorator classes. The error occurs on the second step - when I try to initialize a decorator class, the first step goes ok. Any idea how to overcome this ?

Interface segregation principle - Java

I have an interface

interface XXXCommandHandler(){
    void parse(String something);
    String response();
    String additionalResponse();
}

  1. Some of the classes that implement XXXCommandHandler do not implement additionalResponse().
  2. I am using ApplicationContextManager.getInstance().getBeansOfType(XXXCommandHandler.class) to get the classes that implement XXXCommandHandler
  3. Then call parse, response and additionalResponse
  4. Since some do not implement additionalResponse I am forced to return null.

I can think of the following

  1. Instead of returning null on classes that do not implement additionalResponse, declaire additionalResponse as default method and return null / or make it return Optional etc and override it on the classes that implement additionalResponse method.
  2. Ugly way :- return null in all the classes that do not implement additionalResponse
  3. Create two different interfaces XXXCommandHandlerParser() with parse and response method and XXXCommandHandlerAddtionalresponse() with additionalResponse method extending XXXCommandHandlerParser i.e

    interface XXXCommandHandlerParser(){

        void parse(String something);
        String response();
    
    }
    
    

    interface XXXCommandHandlerAddtionalresponse() extends XXXCommandHandlerParser {

        String additionalResponse();
    }
    
    
  4. But if I do #3 I had to change ApplicationContextManager.getInstance().getBeansOfType(XXXCommandHandlerAddtionalresponse.class).

  5. If I do #4 then classes that do not implement additionalResponse or that do not implement XXXCommandHandlerAddtionalresponse will not be picked up.

Can you think of any elegant way?

Micro service architecture for Angular2

If we take an enterprise angular 2 web app it has several modules(screens) such as Customer management, Reservations, Booking management, Reporting and etc....

What we normally do is we create common components in a component library and use them on main angular application. The main angular app contains all the modules(screens) with REST API integrations(assuming backed is REST). When app is getting bigger & bigger compile time and rendering consuming more time & resources. Also if one particular area is having a issue we cannot have a release since all are bundle to one app.

As you all know Micro service architecture is a method of developing software systems that has grown in popularity. So, my question is can we apply same architecture for these type of enterprise angular 2 apps?.

It is like this. We have a customer management as a separate angular app. Again Booking management is another angular app. Reporting is another app. These apps are going to be separate war files when deploying to the web server.

Once we have developed such loosely coupled apps this will reduce the over head of project size, compile time & resources. Also this will make unit testing more easier. Particular set of developers are only considering the only one unit of the module.

Kindly share your expert thoughts about this

Thanks.

Access Base Class Member from Composition Member Class

I have the following Classes,

Public Class Department

     Public Property ID as Integer
     Public Property MaxEmployeesAllowed as Integer 'Maximum No. of Employees allowed in this Department
     Public Property MaxAllowedSalaryPerMonth as Double 'This Department Employees Total Salary should not exceed this Amount
     Public Property Employees as List(of Employee)

End Class

Public Class Employee

     Public Property ID as Integer       
     Public Property No as String
     Public Property Salary as Double

End Class

Questions are as follows :

Q01. while updating Employees Salary, I need a validation to check whether departments all employees salary should not cross MaxAllowedSalaryPerMonth.

Q02. While Adding New Employee I should check the No. of Employees Limit should not be crossed than the Limit in the Department.

How can i do this through Design Pattern, Am trying to achieve this through Decorator Pattern ?

Thanks

Iyyappan R