vendredi 31 août 2018

Which design pattern to serialise object Builder vs Visitor ?

I am trying to learn OOPS by examples. So I try to implement a object serialiser.The object is same but it can be serialised to either XML, JSON etc. I see two types of suggestions out there.

In this blog, they say we can use visitor/double dispatch to serialise objects.

http://codebetter.com/jeremymiller/2007/10/31/be-not-afraid-of-the-visitor-the-big-bad-composite-or-their-little-friend-double-dispatch/

But, by definition we are building a serialised object from a complex object, so it make sense to create a XMLBuilder and JSONBuilder.

Now, which is the right way to do it ?

Inject Configuration into Python Applications

I'm looking for patterns for parameterizing Python applications.

Approaches I can think of are:

  1. pass configuration objects or parameters down deep call hierarchies
  2. have a singleton configuration object (eg. a package that's initialized at application startup)
  3. register configurable parts of the application upon load (import), then call them once the configuration is read
  4. every configurable component parses its own configuration

They all feel weird in one way or another.

The question is: is there a better alternative, what are the pros and cons of these methods, is there a best practice and are there standard implementations that I'm not aware of?

How to choose from Observable or regular value

I've been confusing with Observable since getting started with Angular (not AngularJS) and rxjs.

Observable is convenient and provided a FP way of organizing information. However it becomes very cumbersome when mixed with regular values.

For example, suppose we have a data table, in which each row has a checkbox and there is a "select all" checkbox in the header row. A very common use case.

The data source of the data table is an Observable. So the pseudo-code will be like:

// sample.component.ts, suppose data source comes from ngrx store
rows$ = this.store.pipe(select(selectRows)); 
// sample.component.html
<table [dataSource]="rows$">

With this setup, we can implement the check box for each data row as follow, storing the on/off status in local state:

// sample.component.ts
state = { selection: {} };
handleSelect(id, event) {
    this.state.selection[id] = event.checked;
}

Now here are the problems:

  1. In order to calculate the "all selected or not" state, I need to know both rows$ and this.state.selection so that I can tell whether all rows are selected or not. However rows$ is an Observable while this.state.seletion is a regular object. My options are:

    a) Convert this.state.selection into an Observable by creating an rxjs.Subject and update its value in each handleSelect() event handler, then merge this new Observable with rows$ to compute the "all selected" state

    b) Subscribe rows$ and convert it to a regular array rows, then compute the all selected state in handleSelect()

  2. When user clicks the "select all" checkbox, I need to update this.state.selection to assign all ids to true or false. Again all the ids have to be retrieved from rows$, which is an Observable. So there are two options as well:

    a) Convert "select all" event to an Observable, then merge it with rows$ and update this.state.selection as a side effect

    b) The same as 1.b), subscribe rows$ to rows and do the calculation in handleSelectAll() handler

For me it looks like the easiest way is to first convert rows$ to rows and DON'T use Observable at all in the component. Because in order to use Observable I need to convert everything else (state, events, ...) into Observable.

But if I am correct, why ngrx provides Observable interface only?

So I believe I'm thinking soemthing wrong.

I appreciate if anyone could share some light on this.

Architecture design problem: List of items to be fetched from server

I am creating a simple e-commerce android application. Basically, My business requirement is to show a list of items. Where each item will have a thumbnail image, name, description and few more details like price etc.

I know the basic server client interaction and how json can be fetched from server. My question is what is the best approach for fetching the images?

Few of approaches that comes to my mind are :

  • Have a field in json with BASE64 encoded image with in each item and save images as BASE64 text in DB.
  • Upload images(in S3 or likewise) and refer them by a URL. Whenever an item is fetched from client(Android app), return URL in item. And once app receives item, it will again send a request to fetch the image.

Pros and Cons

  • Latency: Basically, first approach, I am not sure about if how will it perform but certainly encoding and decoding is going to degrade the performance. With the second approach, the major issue is that to fetch the images for items, more network requests are to be made. Like if 10 items arrives for page 1, then 10 more requests to fetch images. And because images will arrive later, there will be empty thumbnails in the list of items.

What should be the best approach to design the system? You are welcome to suggest an alternate beside the above two.

Using the Builder Pattern to returned a transformed argument

I have a script that passes many optional flags on a text image and saves the resulting transformations as an output. However, the script is written in bash and I need it to fit into our Java stack.

So I looked around and I heard that a Builder pattern is great for optional arguments (I've used them before without even realizing it). So I'm trying to create a Builder to solve my problem but Builders only return themselves. They aren't supposed to return any other type. One person recommended I just call .getImage() instead of .build() but I'm not sure if that's proper. This is what I have now for my theoretical TextCleaner class:

BufferedImage img = new TextCleaner.Builder("Capture1.png")
        .convertGreyScale()
        .enhance(Enhance.STRETCH)
        .filterSize(15)
        .offset(20);
        .getImage();

What should I do?

It's Mediator Pattern. Airport [on hold]

#include<iostream>
#include<vector>
#include<string>
using namespace std;

class AFlight;
class Flight747;
class Flight1011;
class Flight112;
class Flight7E7;

class ATCMediator /// this is air traffic controller, which i use as a mediator in this case.../// 
{
protected:
    vector<AFlight*> flight;
public:
    ATCMediator() = default;
    void Add(AFlight*f) {
        flight.push_back(f);
    }
    void Send(string msg) {
        //if(SetDistance()<500)
        for (int i = 0; i < flight.size(); i++)

            flight[i]->Notify(msg);   //  this is where i get "use of underfined type'Flight' "..... Eroor C2027.//

    }

    friend class AFlight;
    friend class Flight747;
    friend class Flight1011;
    friend class Flight112;
    friend class Flight7E7;
};

class AFlight  // this is virtual class that i use for other planes types.///
{
protected:
    ATCMediator *m;

public:
    //AFlight() {};
    virtual void Send() = 0;
    virtual int SetDistance() = 0;
    virtual void Notify(string msg) = 0;

};

class Flight747:public AFlight
{
protected:
    string name;
    int distance;
public:
    Flight747(ATCMediator *m, int distance) { this->distance = distance; this->m = m; };
    void Send() {
        m->Send("");
    }
    int SetDistance() {
        return distance;
    }


    void Notify(string msg) 
    { 
        cout << msg << endl;
    };
};

class Flight1011 :public AFlight
{
protected:
    string name;
    int distance;
public:
    Flight1011(ATCMediator *m, int distance) { this->distance = distance; this->m = m; };
    void Send() {
        m->Send("");
    }
    int SetDistance() {
        return distance;
    }


    void Notify(string msg)
    {
        cout << msg << endl;
    };
};

class Flight112:public AFlight
{
protected:
    string name;
    int distance;
public:
    Flight112(ATCMediator *m, int distance) { this->distance = distance; this->m = m; };
    void Send() {
        m->Send("");
    }
    int SetDistance() {
        return distance;
    }


    void Notify(string msg)
    {
        cout << msg << endl;
    };
};

class Flight7E7:public AFlight
{
protected:
    string name;
    int distance;
public:
    Flight7E7(ATCMediator *m, int distance) { this->distance = distance; this->m = m; };
    void Send() {
        m->Send("");
    }
    int SetDistance() {
        return distance;
    }


    void Notify(string msg)
    {
        cout << msg << endl;
    };
};

void main()
{
    ATCMediator *M = new ATCMediator();
    AFlight *f1 = new Flight747(M, 345);




    system("pause");
}

Would be kindly appreciated if someone can tell me how to fix this issue and continue on my project... thank you in advance .

It's my patter mediator graph

This was the first idea, of making it like this, but then i switched to make more like first picture.

Air traffic controller , in the airport is a mediator of all planes that are in a distance of 500 kilometers of the airport. Mediator can receive massages and can send it to specific aircraft or send it to all of them at once. When Plane try to take off, it send massage to mediator and mediator send it to all that that plane is taking off. If it can or can not take off then its will be simply bool operator.Pretty much is for landing, mediator is in control of all planes around the airport. and Sometimes plane want to contact the plane next the him or something like that , it send massage to mediator and mediator send it only to specific plane . But i got stuck on this error. please help me , so i can move on with this project.

DTOs that are too heavy to be shared

I have a domain entity currently within my application which exposes functionality via wcf and restful api - where the properties are decorated with various attributes - like SwaggerWCF for example, and some validation rules like [Mandatory].

Now this is fine, however I am now working on a client library to faciliate consuming the services. The typical pattern I follow here is to break the DTOs out into a separate nuget package which is then used by the service and the client.

However these DTos are heavy - hell they probably aren't arent even dtos.

How can I expose my lovely POCOS as Dtos and then layer up the extra stuff on the service side?

I can only see duplication on the road ahead....

How to merge two functions with same conditions?

I quickly wrote the below class for this question.

I'm looking for a way to merge addFruit() with removeFruit().

They both use identical conditions but just different function call at the end.

My Code :

#include <iostream>
#include <string>
#include <vector>

class MyClass
{
public:
    void addFruit(const std::string &str, int count)
    {
        if (str == "apples")
            addToVec(apples, count);
        else if (str == "oranges")
            addToVec(apples, count);
        else if (str == "lemons")
            addToVec(apples, count);
        else if (str == "melons")
            addToVec(apples, count);
        else if (str == "bananas")
            addToVec(apples, count);
        else
            std::cout << "Unknown Fruit : " << str << '\n';
    }
    void removeFruit(const std::string &str)
    {
        if (str == "apples")
            removeFromVec(apples);
        else if (str == "oranges")
            removeFromVec(apples);
        else if (str == "lemons")
            removeFromVec(apples);
        else if (str == "melons")
            removeFromVec(apples);
        else if (str == "bananas")
            removeFromVec(apples);
        else
            std::cout << "Unknown Fruit : " << str << '\n';
    }
private:
    void addToVec(std::vector<int> &vec, int count)
    {
        vec.push_back(count);
    }
    void removeFromVec(std::vector<int> &vec)
    {
        vec.pop_back();
    }
    std::vector<int> apples;
    std::vector<int> oranges;
    std::vector<int> lemons;
    std::vector<int> melons;
    std::vector<int> bananas;
};

Any clever way to nicely merge the two functions?

jeudi 30 août 2018

Create complex class with factory and builder

background: I build a class diagram for shopping on the net. For creating a user interface with tow type (golden-User and silver-User) I use the factory pattern.
But the User class become to be very complex.

How can I create this class by bulider and on the other hand the ability to specify the user type such as the factory will remain on the class name (will help me to recognize which type is by polymorphism and not by if&else)

use getters in ViewModel instead of subscribing to Model

That week I learn that we can use getters/setters in javascript. So I tried to use it in my current code.

For now my ViewModel register to the Model in order to get notified when Model has changed.

Using getters I can get RID of that and simply returns the value of the field in model to the viewModel.

ex:

Model = {
field: aValue
}

ViewModel = {}
 Object.defineProperty(ViewModel , aField{
      get: function () {
        return Model.field;
             });
         }
    });

Am I right? is it ok?

Decoupling mode from the GUI

I am working on a project. I have finished the back-end code and now I am trying to get a GUI working, using Swing. I am interested in decoupling the GUI from the code. I have read a lot of posts about the Model-View-Controller pattern, but I cannot seem to be able to apply it. Those examples used getters and setters to do the job.

About my project: it's a banking application (sort of). I am taking into account currencies, monetary indexes, rates, commissions, forfeits, exchange-rate from one currency to another, etc.... All of those are objects, stored in serialized containers (each serialized container contains a bunch of objects of the same type -> think it as a list of objects).

The problem: how am I supposed to pass those objects to the GUI without getters and setters? I know there is an MVC framework built-in into Java (Observer/Observable) but I cannot understand how I can pass objects from a so-called "controller" to GUI.

P.S.: I have already stormed google with searches, but I was unable to find something I can use. P.S.S.: I am still a newcomer to design-patterns, don't hate

Chain of responsibility pattern rookie attempt

I'm trying to find understanding of Chain of responsibility pattern, and, as an exercise, I've wrote some code. This code

class SomeObject:
    def __init__(self):
        self.integer_field = 0
        self.float_field = 0.0
        self.string_field = 'hi'


class EventGet:
    def __init__(self, data_type):
        self.data_type = data_type

class EventSet:
    def __init__(self, value):
        self.value = value


class NullHandler:
    def __init__(self, successor=None):
        self.__successor = successor

    def handle(self, obj, event):
        if self.__successor:
            self.__successor.handle(obj, event)


class IntHandler(NullHandler):
    def handle(self, obj, event):
        if isinstance(event, EventGet) and event.data_type is int:
            return obj.integer_field
        elif isinstance(event, EventSet) and isinstance(event.value, int):
            obj.integer_field = event.value
        else:
            super().handle(obj, event)


class FloatHandler(NullHandler):
    def handle(self, obj, event):
        if isinstance(event, EventGet) and event.data_type is float:
            return obj.float_field
        elif isinstance(event, EventSet) and isinstance(event.value, float):
            obj.float_field = event.value
        else:
            super().handle(obj, event)


class StrHandler(NullHandler):
    def handle(self, obj, event):
        if isinstance(event, EventGet) and event.data_type is str:
            return obj.string_field
        elif isinstance(event, EventSet) and isinstance(event.value, str):
            obj.string_field = event.value
        else:
            super().handle(obj, event)

But it doesn't work as I'm expecting. Being invoked in the following manner

obj = SomeObject()
chain = IntHandler(FloatHandler(StrHandler(NullHandler())))

print(chain.handle(obj, EventGet(int)))
print(chain.handle(obj, EventGet(float)))
print(chain.handle(obj, EventGet(str)))

chain.handle(obj, EventSet(1))
print(obj.integer_field)    

chain.handle(obj, EventSet(1.1))
print(obj.float_field)

chain.handle(obj, EventSet('str'))
print(obj.string_field)

it produces the confusing output:

0 # That's ok
None # Why not 0.0?
None # Why not hi?
1 # That's ok
1.1 # That's ok
str # That's ok

I can't figure out why calling the chain.handle(obj, EventGet(float)) and chain.handle(obj, EventGet(str)) produces None. After all, there's a return statement in corresponding positions (i.e. return obj.float_field and return obj.string_field).

Can you please explain to me what is wrong in this code and how to make it work as expected? Many thanks in advance!

fork and cascade patterns and when should I use which

I keep hearing about the design patterns fork and cascade in software engineering but don't know what they really are and when should I use which. So what are these patterns and what are they for?

Design pattern required

A customer can place one order. Each order till its delivered goes trough different phases. Lets say there are many phases A,B,C,D,E. Moving through these phases will be done manually from a single client. From A-> B (or) E , B -> C , C -> D (or) E

Each phases require different inputs from user to move to next phase. All these inputs are different entities as modelled in system.

In UI level I have a dropdown. If current status is A then dropdown shows B and E. If B then C. Value for dropdown is coming from database from a master table. On choosing different option I am showing different forms to user using JQuery.

I have multiple ifs stacked up in my code both on .cshtml page and server side. Is there any better approach to do this? Any design pattern that will help me in this scenario?

If I am doing anything wrong then please suggest.

Single Responsibility (SOLID PRINCIPLES) [duplicate]

This question already has an answer here:

My question is about the following. I know that classes should have only one responsibility and not even two. for example in user class, we shouldn't have function which registers users and another one which sends emails. It's better to make email sending in seperate classes, since if we don't, user class will have two responsibility.

Question 1) have you used MVC framework for example Laravel? there, if i make a class, there'll be 5 functions(insert,create,get,put,delete). Do you think this is the single responsibility? since it has 5 functions. I think yes because it still handles users.

Question 2) Why do you think this principle is good? I think the following:

a) because it's better to have different kind of responsibilities separately as It's super better to test those codes differently.

b) we can use those separated classes in other contexts.

c) It's said that class should have only one reason to change. Why is it bad that if user class has two responsibilities, and I need one of them to change, I always come to users's class. why is this bad?

Please if you don't mind, just agree with me and provide me more world-life scenario if possible. Thank you so much.

C++ memory and design question on small project

I try to create a small library to listen for multiple mice on MAC and PC. (right now MAC)

I have started something simple that does not work ATM. Since I am a noob in C++ I wanted to ask the community for help in this matter. How should I design it in code? I wanted to use smart pointers here is my code, feedl free to download it:

Github: Open Source Project

Everything in one file:

Device Class

class Device;

class Device {

public:
Device(){
    std::cout << "###### Create Device - Empty" << std::endl;

    this->x_previous = 0;
    this->y_previous = 0;
    this->x_current = 0;
    this->y_current = 0;
}

Device( size_t _deviceID, std::string _device_name){
    std::cout << "###### Create Device - 0.0/0.0" << std::endl;

    this->device_id = std::make_shared<size_t>(_deviceID);
    this->device_name = std::make_shared<std::string>(_device_name);

    this->x_previous = 0;
    this->y_previous = 0;
    this->x_current = 0;
    this->y_current = 0;
}

Device(size_t _deviceID, std::string _device_name, float _xStart, float _yStart){
    std::cout << "###### Create Device - " << _xStart << "/" << _yStart << std::endl;
    this->device_id = std::make_shared<size_t>(_deviceID);
    this->device_name = std::make_shared<std::string>(_device_name);

    this->x_previous = _xStart;
    this->y_previous = _yStart;
    this->x_current = _xStart;
    this->y_current = _yStart;
}

~Device(){
    std::cout << "###### Destroyed Device" << std::endl;
}

const size_t getId () const{
    return (size_t)this->device_id.get();
};
const std::string getName() const{
    return "Not Implementet yet"; //this->device_name.get() does not work because of std::basic_string wtf?
};

const float getDeltaX() const{
    return x_previous - x_current;
};
const float getDeltaY() const{
    return y_previous - y_current;
};

private:
std::shared_ptr<size_t> device_id;
std::shared_ptr<std::string> device_name;

float x_previous;
float y_previous;

float x_current;
float y_current;

};

Devices Class

class Devices{

public:
Devices(){
    std::cout << "###### Created Empty Devices List" << std::endl;
    this->list = std::unique_ptr<std::list<Device> >();
}

explicit Devices(std::unique_ptr<std::list<Device> > _list){
    std::cout << "###### Created Moved Devices List" << std::endl;
    this->list = std::move(_list);
}

~Devices(){
    std::cout << "###### Destroyed Devices List" << std::endl;
}

std::unique_ptr<std::list<Device> > list;

void getDevicesArray() {

    CFMutableDictionaryRef usb_dictionary;
    io_iterator_t io_device_iterator;
    kern_return_t assembler_kernel_return_value;
    io_service_t device_id;

    // set up a matching dictionary for the class
    usb_dictionary = IOServiceMatching(kIOUSBDeviceClassName);
    if (usb_dictionary == NULL) {
        std::cout << "failed to fetch USB dictionary" << std::endl;
        return; // still empty
    }

    // Now we have a dictionary, get an iterator.
    assembler_kernel_return_value = IOServiceGetMatchingServices(kIOMasterPortDefault, usb_dictionary, &io_device_iterator);
    if (assembler_kernel_return_value != KERN_SUCCESS) {
        std::cout << "failed to get a kern_return" << std::endl;
        return; // still empty
    }

    io_name_t device_name = "unkown device";
    device_id = IOIteratorNext(io_device_iterator); // getting first device

    while (device_id) {

        device_id = IOIteratorNext(io_device_iterator); //set id type: io_service_t
        IORegistryEntryGetName(device_id, device_name); //set name type: io_name_t

        this->list.get()->push_back(Device(device_id, device_name));
    }

    //Done, release the iterator
    IOObjectRelease(io_device_iterator);
}

void printDeviceIDs(){

    for (auto const& device : *this->list.get()) {
        std::cout << "#" << device.getId() <<  std::endl;
        std::cout << "| name: " << "\t" << device.getName() <<  std::endl;
        std::cout << "#-----------------------------------------------#" << std::endl;
    }
}
};

main

int main(int argc, const char *argv[])
{
std::shared_ptr<Devices> devices;

devices->printDeviceIDs();
devices->getDevicesArray();
devices->printDeviceIDs();
}

Someone knows of a good pattern for that?
Also maybe I use smart pointers completely wrong?
Also the iOKit library is from 1985 or something so it is not very descriptive...

Thanks in advance.

Creating new instance in every function call against have only one classmember

We have an C++ importer, which imports a big amount of xml-data into a database. Usually, the number of records in the xml are between 500 000 and 2 000 000.

The importer was refactored from the following code into the new code:

Legacy Code

class DataHandler
{
   public:

    handleStartTag()
    {
         _value.clear();
    }

    handleAttribute(const std::string& attribute)
    {
        _attribute = attribute;
    }

    handleValue(const std::string& value)
    {
        _value += value;
    }

    handleEndTag()
    {
        _record.set(_attribute, _value);

        RecordProcessor rp(_record);
        // rp.setSomeProperties
        rp.run();
    }

   private:

    std::string _attribute;
    std::string _value;

    Record _record;
};

New Code

class DataHandler
{
   public:

    handleStartTag()
    {
         _value.clear();
    }

    handleAttribute(const std::string& attribute)
    {
        _attribute = attribute;
    }

    handleValue(const std::string& value)
    {
        _value += value;
    }

    handleEndTag()
    {
        _record.set(_attribute, _value);

        _processor.setSomeProperties();
        _processor.run(record);

        _processor.clear();
    }

   private:

    std::string _attribute;
    std::string _value;

    Record _record;
    RecordProcessor _processor;
};

The main difference is, that we don't create a new instance of RecordProcessor in every call of the handleEndTag(). This was implemented, because (they say) for 2 million records it needs a lot of time to create/destroy the RecordProcessor instance.

My personal opinion is, that the legacy code is the better pattern to implement this functionality. The RecordProcessor will be created directly with the corresponding record.

Questions

Is this really a performance boost?

What are the advantages/disadvantages of both implementations?

What pattern should I use for similar projects in future?

DB2 LIKE matching Pattern

My question is simple.

In a DB2 Database, I have my table

Table (Id integer, name varchar)

I want to select entries which names like 'ac1%' or 'ac2%' or 'ac3%', so which names match regex

'^ac[123]*' 

Is there any method to have this select query without write :

WHERE name LIKE 'ac1%' OR name LIKE 'ac2%' OR name LIKE 'ac2%'

Best Practice to Get 1 object from Database using WebApi C# Layered Architecture

So I know my question seems basic but I want to know something that's been bugging me for a while, My backend is done following the Layered Architecture(repo-services-controllers)

I have an api call that should return a json of an employee after providing his id, so the url is something like api.mywebsite.com/api/employees/1

and my controller will look like this:

public async Task<EmployeeDto> GetEmployee([FromUri] int eId)
{
    return GetService<IEmployeeService>().GetEmployeeById(eId);
}

my question is, what are the checks I'm supposed to do when I get this object? Should I do a check if the employee is deleted (soft deleted that is)? I obviously should do a check if it returns a null (didnt find an employee with such an id)

But if I want to do a check if the entity is deleted, should I do it in the repository layer or the service layer? repo layer:

public Task<Employee> GetSingle(int id)
{
    return GetDatabase().Employees.Where(x => x.EmployeeId== id && !x.Deleted).SingleOrDefaultAsync();
}

or on the service layer:

var emp= await GetTenantRepository<IEmployeeRepository>().GetSingle(eId);
if (emp==null)
{
    throw ...
}
if (emp.Deleted)
{
    throw ...
}

Am I too overthinking it and it doesnt matter if I put it here or there?

How to convert the list to glob style pattern in python

I need to copy the files using shutil copytree with certain pattern. The patterns I am having as list. I converted the list to string using below method to pass in the copy tree ignore_pattern as below.

def convert_list_to_str(pattern):
    patter = ','.join("'{0}'".format(x) for x in pattern)
    return patter

copytree(sourcedir, target_dir,ignore=ignore_patterns(pattr))

If I hard code the pattern as below

copytree(sourcedir, target_dir,ignore=ignore_patterns('*.bat','*.jar')) 

It is working fine, Here I cannot iterate the pattern because in first run it will create the folder. So I need to convert the list to glob pattern so that it can be passed as a parameter. But don't know how to convert the list to glob pattern.

How to achieve this?

Design Pattern to find if method parameter is typecast inside the method

I am writing a UT generator, which will generate Junit Test Cases for Java files already present.

I am running into problems when the parameter of a method is type casted to a child type inside the method. This is because my test case is generated using the method signature, but when the generatedtest case is run, the type casting fails from supertype class to subtype class.

I need to understand how I can parse the method to find if the parameter is typecasted inside the method.

I have got the method body using getDeclarationAsString() method and method parameters using getParameters() method of MethodDeclaration class.

mercredi 29 août 2018

Detect Moire Pattern in an image - iOS Swift

Is there any way to find Moire Patter in an image I can use in my iOS app using Swift and maybe OpenCV?

Any help would be appreciated.

Confused about structure of android project and MVC pattern

I can't get my head around how to apply the model-view-controller design pattern in an android studio project.

I understand that the view is the .xml layouts and that the activity classes are supposed to be the controllers, but I'm confused about whether general programming logic should be a part of the controller or model.

Can the programming logic related to a particular activity be included within the activity class or should they be separated into two classes? i.e. the activity handling just user input and a second class dealing with the associated programming logic.

How to rewrite this pseudocode to make it easier to read and maintain?

interface TableCreator {
    void createTable();
}

interface UserWriter {
    void updateUser(User user);
}

interface UserReader {
    User getUser(string id);
}

// This is like Golang interfaces, where UserClient implicitly inherits other interfaces.
interface UserClient {
    TableCreator();
    UserWriter();
    UserReader();
}

function void createUser(User user, UserClient client) {
    error = createUser(client, user);

    // If attempting to create a user in database failed, table does not exist so create one and try again.
    if error != null {
        createTable(client);
        error = createUser(client, user);
        if error != null {
           print("Tried to create a table and a user, but failed again.")
        }
    }  
}

createUser(UserWriter writer, User user) {
    writer.updateUser(user);
}

createTable(TableCreator creator) {
    creator.createTable();
}

Is there a way to make this code cleaner? Especially in regards to interfaces and createUser function?

I will write this either in Java or Golang if we need proper language implementation.

Thanks :)

iOS design pattern for multi-mode app

I will explain my question by way of example.

  1. I'm writing a iOS app, that have 4 type of users. For every type of users i need to show different controller, and sometimes the same controller but with some changes.
  2. It is possible to change role of user runtime. For switching between users i think to use Decorator pattern.

So what is the best solution to create (1) and (2) situations?

Java ORM/OGM/Persistence frameworks for data schema unknown until runtime?

I've got a design/architecture question.

I'm developing an ETL application in Java (which I'm relatively inexperienced with). I'm leveraging Spring Boot as a base framework for component autowiring, dependency injection, etc. My application is intended to be ran on a scheduled basis in a batch manner. (FYI I've looked at Spring Batch, but it falls short of what I need).

In order to maximize flexibility, when my application is executed, it reads a user/developer-defined JSON configuration file at runtime. This is called the "job configuration." The job configuration file contains an array of 1 or more datasources from which to extract data, and each datasource configuration defines a specific query for what data to extract (along with various other parameters). Each of these datasource configurations also define an array of transforms, which define how to convert the extracted data into a desired data structure. Finally, the configuration defines an array of output datasources, which is where the data gets loaded after it has been joined (if needed) and merged into its final output structure(s). Pretty straight forward right?

Part of the challenge that I need help with is that, as the developer, I don't know what the structure of the final output structure will be, since it's configured, not hard-coded. So I can't just slap an ORM framework like Hibernate in around some predefined POJO / DOA's to help me avoid having to write a bunch of my own complex persistence logic. Does anyone know of an existing design pattern or perhaps a framework to help address challenges like these?

Any help is much appreciated. Thanks!

(How) can I put an apply_to_all_members_of_class object/method between child and parent methods in command chain?

How can I easily apply the methods of a parent to all instances (registered in a child)?

For ease of programming, I am looking to implement something like this:

SpecialCaseChildClass.apply_to_all_members_of_child_class.any_method_of_parent()

Even more awesome would be an implementation in which I can supply a list of arguments that allows me to iterate arguments:

SpecialCaseChildClass.apply_to_all_members_of_child_class.any_method_of_Parent(
argument1_of_parent_method = range(x), argument2_of_parent_method = range(y))

I have tried to implement this functionality with a class method:

class SpecialCaseChildClass(Parent):

    registry = []

    def __init__(self, *child_argv):
        super().__init__(self, *child_argv)
        registry.append(self)

    @classmethod
    def apply_to_all(function, *parent_argv):
        for child in registry:
            function(child, *parent_argv)

which would (hopefully) allow something like this:

SpecialCaseChildClass.apply_to_all_members_of_child_class(any_Parent_method, *argv)

but that is not pretty, and requires me to add named lists etc.

Implement interface in methods (the best practice)

I have some callback interace:

public interface FooCallback {
    boolean doSomething(Foo fooArg);
}

which is implemented as anonymouos block in methods in service layer:

public void methodA(Bar barArg) {
    // some bussiness logic like parsing Foo object from Bar for example

    FooCallback cb = new FooCallback() {
        @Override
        public boolean doSomething(Foo fooArg) {
            // some calculation with fooArg and barArg and return boolean value
        }
    }
    saveBar(barArg, cb);
}

saveBar is method which is also in that class and is using to save Bar object into database depends on result of doSomething method of FooCallback;

public void saveBar(barArg, cb) {
    // get Foo object from database

    if (cb.doSomething(fooFromDB)) {
        // save barArg into DB
    } else {
        // antother logic
    }
}

I have a lot of methods like methodA in my service class. Anonyme code block is also bad testable. Can you tell me what is the best practice with similar implementation? I figure out move content from doSomething to another method, but it means every method will be self methodCallback. What do you think? I am using java. Thank you in advice.

How to design a elegant IP check API

In my project, there are a lot of requirements about IP check. Because we write many functions for network devices. In some case, we don't need loopback IP and broadcast IP, and in some other case, it's valid.

So I design some basic APIs:

function isLoopback(ip){
}

function isMulticast(ip){
}

function isBroadcast(ip, mask){
}

//etc

Now, Developers have to call like this:

isIpv4(ip) && !isLoopback(ip) && !isBroadcast(ip, mask) && !isMulticast(ip)

Is it possible to design a more elegant API for potential developers?

Constant = {
  BROADCAST : 0x0001,
  MULTICAST : 0x0002,
  LOOPBACK  : 0x0004,
  ANY     : 0x0008,//0.0.0.0
};

/**
checkIp('10.180.0.1', 16, Constant.BROADCAST|Constant.MULTICAST|Constant.LOOPBACK|Constant.ANY)
*/
function checkIp(ip, mask, excludes);

I use Extjs to do this, which is a JavaScript framework. Any good ideas?

Design a Singleton class

Need to write a class which remains singleton across different JVM. How could this be done? How can a single object be used across different JVM?

Java Pattern regex search between strings

Given the following strings (stringToTest):

1 -

G2:7JAPjGdnGy8jxR8[RQ:1,2]-G3:jRo6pN8ZW9aglYz[RQ:3,4]

2 -

G2:7JAPjGdnGy8jxR8[RQ:3,4]-G3:jRo6pN8ZW9aglYz[RQ:3,4]

And the Pattern:

Pattern p = Pattern.compile("G2:\\S+RQ:3,4");
if (p.matcher(stringToTest).find())
{
    // Match
}

For string 1 I DON'T want to match, because RQ:3,4 is associated with the G3 section, not G2, and I want string 2 to match, as RQ:3,4 is associated with G2 section.

The problem with the current regex is that it's searching too far and reaching the RQ:3,4 eventually in case 1 even though I don't want to consider past the G2 section.

It's also possible that the stringToTest might be (just one section):

G2:7JAPjGdnGy8jxR8[RQ:3,4]

The strings 7JAPjGdnGy8jxR8 and jRo6pN8ZW9aglYz are variable length hashes.

Can anyone help me with the correct regex to use, to start looking at G2 for RQ:3,4 but stopping if it reaches the end of the string or -G (the start of the next section).

I've been trying for hours, thanks in advance.

Steve.

Regex for password is not working

@NotNull
@Pattern(regexp = "(?=.*[0-9])", message = "Password must contain one digit.")
private String password;

the regex that i wrote for password is not working, the problem is not the regex i think @Pattern seems not working, any idea ?

python copying the files with include pattern

I need to copy the files with include pattern using python script. Since shutil supports ignore_patterns to ignore the file. Is there any method to include the pattern to copy the files. Otherwise do I have to write the code explicitly?.

Thanks in advance

mardi 28 août 2018

Are there any functional design patterns?

I have been reading the GoF and Head first design pattern books. These books help you to abstract out your problem solutions to a design pattern. But all the design patterns seem to apply only to object oriented programming. I am a Scala developer and would like to design in a functional way. Does it make sense? Is this possible? Are there any books that help you understand design patterns in functional programs?

How would you refactor this switch-case in Ruby?

How would you refactor this switch-case in Ruby?

I was thinking about hashes, but I am not sure if it would be the best strategy.

def execute_command(input)
   case input.split[0]
   when 'I'
     create(create_hash)
   when 'C'
     clear
   when 'L'
     color(color_hash)
   when 'V'
     line(line_hash)
   when 'S'
     print
   when '?'
     help
   when 'X'
     exit
   else
     error_message
   end
end

Filters Design Pattern

I really like the 'filters' in ASP.MVC. They are briliant.

I would like to use somekind of filter design pattern for my business logic.

Consider the following:

var shippingFilterCost = {
  "Name": "CalculateShippingCostsFilter",
  "InjectedServices": "product, shoppingBasket, CalculateProductShipping",
  "MainMethod": function (product, shoppingBasket,CalculateProductShipping) {
    var shippingCost = CalculateProductShipping(product.weight, shoppingBasket.locationToShipTo);
    product.ShippingCost = shippingCost;
    return product;
  }
}


var checkIfBuyerHasAVouche = {
  "Name": "CheckVoucher",
  "InjectedServices": "product, shoppingBasket, CheckVoucherValid,CalculateVoucher",
  "EntryCondition": function (product, shoppingBasket, CheckVoucherValid, CalculateVoucher) {
    var isVoucherValid = CheckVoucherValid(shoppingBasket.voucherCode);   
    return isVoucherValid;
    // we only go to the 'MainMethod' if entryCondition returns true;
  },
  "MainMethod": function (product, shoppingBasket, CheckVoucherValid, CalculateVoucher) {
    var voucherPrice = CalculateVoucher(shoppingBasket.voucherCode);
    product.voucherPriceReduction = voucherPrice;
    return product;
  }
}

So we will have a base product, and that base product will go through those 2 filters that will add 'information to it'.

One filter calculates shipping cost and another the voucher.

Advantages:

1) We can easily see what 'services' are used where by their references.

2) We can easily track what method mutates what property with ease because

3) The services are just pure methods that return something.

4) All the mutations are centralized inside mainMethod

5) We also have 'EntryCondition' method we can separate and see what filters runs and what filter does not.

I am not sure how better to explain what is happening here. Obviously this logic is very simple but if i had multiple suppliers, customer types and so on, each with their own logic we can see how this declarative way can help me out.

If you have a better idea how can I explain this better, please edit my post.

match a timestamp based on regex pattern matching scala

I wrote the following code :

val reg = "([\\d]{4})-([\\d]{2})-([\\d]{2})(T)([\\d]{2}):([\\d]{2})".r
  val dataExtraction: String => Map[String, String] = {
    string: String => {
      string match {
        case reg(year, month, day, symbol, hour, minutes) => Map(YEAR -> year, MONTH -> month, DAY -> day, HOUR -> hour)
        case _                                                           => Map(YEAR -> "", MONTH -> "", DAY -> "", HOUR -> "")
      }

    }
  }
val YEAR = "YEAR"
  val MONTH = "MONTH"
  val DAY = "DAY"
  val HOUR = "HOUR"

this function is supposed to be applied to strings having the following format: 2018-08-22T19:10:53.094Z

` when I call the function :

dataExtractions("2018-08-22T19:10:53.094Z")

Is this design correct?

I've made a design for the exercise below (I've attached an image), and I'd like to know if it's well designed (I've tried to apply SOLID principles on this)

Sketch Design

Problem - Blobs:

Blobs are slimy little creatures who have been at war for the last 300 years that have special abilities in the form of behaviors and special attacks.

You are given a partly finished library, which contains some models (Blob, Behavior and Attack). Refactor the given code and complete an application which supports creating blobs and simulating fights between them.

Task 1 - Implement the Game Objects

A blob has a name, health and damage.

A blob also has a behavior. A behavior is triggered when a blob falls to less or equal to half its initial health. The following behaviors should be supported:

Aggressive Behavior - doubles the blob's damage. Each consecutive turn the blob loses 5 damage. The unit's damage cannot fall below its initial value (the damage before the behavior was toggled).
Inflated Behavior - The blob gains 50 health. Each consecutive turns the blob loses 10 health.

A behavior can only be triggered once. It should be triggered even if the blob falls to 0 health. If it is triggered a second time, an error should be raised.

A blob can attack another blob. The following attacks should be supported:

Putrid Fart - the blob produces an attack with damage equal to its own damage
Blobplode - the blob loses half its current health (e.g. from 55 health loses 27 health = 28 health left) and produces an attack with damage equal to double its own damage
    The blob cannot fall below 1 health from attacking with Blobplode

A blob can perform an attack multiple times (only once per turn). A blob can have only a single attack (either Putrid Fart, Blobplode or any other attack) and a single behavior (either Aggressive, Inflated or any other behavior). Other Notes

If a blob's attack triggers a behavior, the behavior should be applied immediately (i.e. a behavior triggered by an attack can affect the attack that triggered it)
A blob should not fall below 0 health
Dead blobs cannot attack / be attacked

Task 2 - Flexible Blobs

Design the blobs so they can work flexibly with any behavior and any attack.

Task 3 - Improve the Models

Encapsulate all internal behavior. The implemented classes should not reveal any internal logic.

Avoid code repetition and promote code re-usability by applying the good practices of OOP.

Task 4 - Application Logic

From the standard input you will receive commands, each on a separate line. The application should support the following commands:

create <name> <health> <damage> <behavior> <attack> - adds a new blob with the specified behavior and attack
attack <attacker> <target> - forces a blob to perform an attack on another blob

The attacking blob produces an attack that deals damage to the target blob's health.

pass - does nothing, skips the turn and progresses the game
status - prints data about the current state of the game in the following format:

Blob {name}: {health} HP, {damage} Damage

...

Blobs should be printed in order of entry in the game.

If a blob has been killed, the format should instead be:

Blob {name} KILLED

drop - ends the program

Each command should progress the game with 1 turn after it is executed.

Task 5 - Loose Coupling

The application should support the creation of blobs with any behavior and attack.

Task 6 - Input / Output Independence

The application should be designed to work with any input source and output destination. In other words, it should NOT depend on the console.

Bonus Task 7 - Blob Events

Implement a fifth command:

report-events - if passed as first command in input the engine should print detailed information when blobs attack each other:
When a blob toggles its behavior

Blob {name} toggled {behavior-type}

When a blob is killed (its health drops to 0 after all effects are taken into consideration)

Blob {name} was killed

The blobs should NOT directly interact with the engine or any input/output classes.

This task is not part of the automated tests in the Judge system. Input

The input will be read from the standard input. On each line a command will be given (one of the described above). Output

The output should be printed on the console. Upon receiving the status command, print the current status of the game as described above. Constraints

The health and damage will be valid 32-bit integer numbers
The input will always end with the drop command
The report-events command will always come first if present in the input

Any suggestion, critic or comment is welcome,

Thanks in advance!!!

Which is better performance global 'private static final String' or local final variable, if the variable is used only in one method

class A{ private static final String patternStr = "abc";

public void m1(){ final String local patternStr = "abc"; ..... /* Code dealing with pattern matching*/ } }

Is it ok to have multiple models for REST API?

In my project, there is one model for a user in the database. Now, I have multiple requests to get specific users. I can get bestUsers which response contains list of JSON's with fewer fields (only these which are needed) - the list of these users is calculated by the server-side algorithm. Now, in the client-side: should I have two models User - for general usage and UserBest - to list the best users or just have one model and serialize only the fields which appear in the JSON (the rest will be null).

I'm writing in Java and using the retrofit library.

What's the models responsibility in MVC pattern in Java?

I'm would like to apply the MVC pattern to my application in Java. Actually, I was researching a lot.. but I could not find a clear definition for the responsibility of each component (model / view / controller).

Of course, my model holds the data as well as the getter and setter methods. Now I'm not sure where I should put the logic of my application. Should the logic belong to the model or to the controller?

Also I came across the term "business logic", which should be implemented in the model. Could you please also give some examples of what is ment by "business logic"?

lundi 27 août 2018

Object binding and events in factories

Factories are used to create objects. I was wondering if it's against the purpose of a factory, if I would bind couple of objects together in the factory. Let me illustrate this with an example.

Let's say I have a factory that produces modal dialogs. The factory can instantiate a view, which will display on screen. Also I need some buttons to be present on the view and which should provide some functionality, let's say call a service via some delegation.

Depending on type of the modal dialog I want to be able to provide different buttons and different behaviours.

class ModalFactory {

       static func createWeatherModal() -> ModalWindowProtocol {
           let modal = SomeModal()
           let closeButton = CloseButton() 
           let verifyWeatherButton = WeatherButton()
           modal.addButton(verifyWeatherButton)
           modal.addButton(closeButton)
           let service = RemoteApi()

           verifyWeatherButton.performAction {
                 service.calculateWeatherConditions()
           }

           closeButton.performAction {
                 modalal.dismiss()
           }
        }

        static func createAdvancedWeatherModal() -> ModalWindowProtocol {
           let modal = AdvancedWeatherModal()
           let service = AdvancedWeatherService()
           let weatherButton = WeatherButton()
           let closeButton = CloseButton()
           modal.addButton(weatherButton)
           modal.addButton(closeButton)
           weatherButton.performAction {
                service.getAdvancedWeatherInfo()
           }
           closeButton.performAction {
                modal.dismiss()
           }
        }
     }

So, there you have it. The binding of an tap event happens in factory. Is this a good practice? And if not, then what would you suggest for this kind of dynamic modal creation and binding?

Thank you

Pattern for downloading data

The API call return data that has a following structure: {id:"z", "data":{},previous:"y"} I want to: a) download 20 records b) do it in a way that I can report/catch errors, basically best practice c) how would you unit test it ?

So far I have a following pseudo code

int max_records = 20 
var results =[Record]()

func get_results(id){
   if results.count == 20{
      //stop
   }
   else{
       //URL, Session download code
       download(result,error){
       if (error){
            //should I throw error here?
        }else{
            //recursive call 
             get_results(record.id)
      }
   }

    }

}

How to redirect to new url, passing on old url, without session or query-string

The main key-feature I want here is the you were redirected from "old-url.html"

Check at what Wikipedia does when taking me to a canonical url of an article (which is exactly what I want to do):

enter image description here

Notice in the screenshot that I accessed old-url.html (united states of america article) but I was redirected to new-url.html (united states article), however, they didn't use any method for redirecting that I know of.

There are 3 main ways that I know how to redirect from old-url.html to new-url.html and let new-url-html know what was the old-url.html:

  1. store the old url in session, then redirect to new-url.html and there (with php for example) check if $_SESSION["redirected-from"] exists
  2. redirect to new-url.html?redirected-from=old-url.html (but with an ugly url)
  3. just update the document.title property and perhaps make a window.history.replaceState(...) to make it look like I redirected the request.

But none of those solutions look like what wikipedia did right there. Now, I can continue to try to hack my way through this requirement, or... I could ask the internet about perhaps a common http pattern that I could be unaware of...

Thanks in advance for your help :-)

MVVM. How to transfer of complex data / commands from Domain to View

Briefly, the question is: in MVVM (AAC), how can Domain (business logic) manage the display of complex states / data in the View layer?

Now in more detail.

It means that inside the Domain: 1) received, calculated some data that need to be shown; 2) the state has changed, it is necessary to react to this (hide / show a group of widgets, call a new fragment, show / update progress, etc.). And it's harder to do than just show a message or a dialog, or just send LiveData to the RecyclerView.

Therefore, examples like "hello world" or "2 + 2 = 4" do not fit, everything is clear in them. In MVP, this is simply done. But here I was able to find the weak point of MVVM.

Now I did the following.

By means of RxJava2 (as an option, it can be LiveData from AAC) from Domain to View (via ViewModel AAC) an object that contains the type of command (enum) is passed and has a bunch of fields for data for all occasions (different fields for different commands of course ). And further, View contains a large switch-case, depending on the type of command where all this is handled.

Variant 2. To create a bunch of specific objects, and then in the View will sit a large if-instanceof.

Variant 3. Store data for View in ViewModel AAC (for which it is actually intended), and send from the Domain only the type of command, then View takes all the necessary data from the ViewModel.

Variant 4. A heap (in case of complex UseCases) a specific Observables in Domain and a heap of subscribers in the View.

So: is there (if any) a more elegant way? There may be some architecture pattern. Maybe I'm in vain reflexing, and this is the right way(s).

ps. 1) the "Command" pattern here does not exactly fit, 2) the "State" pattern has already been implemented by me, and it does not solve the problem either.

Which pattern to use in order to execute new code by just adding new subclasses of a base class?

I am trying to figure out a pattern to avoid code duplication in a situation similar to the one bellow:

std::list<int> error_list;
void validate()
{
    if( validate_0001() == false )
    { error_list.push_back(1); }

    if( validate_0002() == false )
    { error_list.push_back(2); }

    ...
}

The method 'validate' is public in a class responsible for performing different actions, in the example validations, each one with an unique id. I want to be able to add a new action by just extending a base class, without the need to create a new method and add its call and its error handling inside the validate method.

make dictionary to objects of class in python

i made the class for making dict keys to object accessor but this is not working in nested case

d= {'c': {'v': {'a'}}, 'e': 'x', 'r': 'e'}
class A:
     def __init__(self, dicti):
         self.__dict__.update(dicti)
o = A(d)
# i want something like o.c.v=a , o.e=x, o.r=e
# i'm unable to make nested dict object accessor  

looking for help

Which design pattern is best suited to write a wrapper to multiple APIs?

I want to create a wrapper class or an API simple enough for a few open source libraries that can individually talk to different hardware devices or sensors and get some data which essentially is a set of data points and most of these libraries may provide some data in common but slightly different data structure.

For instance, Library A provides a vector of RGB frames from hardware A and Library B provides a vector of thermal image frames from sensor B and Library C provides machine learning algorithms that can be applied on these data streams.

So,

  1. Which design pattern should I follow to achieve the above mentioned wrapper class or API?
  2. Can anyone provide a tutorial resource or a relatively simpler open source API or wrapper class that I can refer to for it?

Using queues to handle asynchronous callbacks

The application I'm working on has to fire off multiple requests to an external API. It will receive the results of those requests asynchronously, but then I need to handle each response in a synchronous way. My research tells me there are multiple ways of doing this, but I am considering this idea and wondering if it will work:

Every time I make a call to the external API, its response is entered into the queue as soon as it asynchronously comes back:

function genericFetchFunction(url, callback) {
    makeAsyncRequest(url, (result) => {
        addToHandlingQueue({
            data: result,
            callback
        });
    });
}

The queue handler pushes the response onto the queue, and initiates the queue firing process.

const responseQueue = [];

function addToHandlingQueue(response) {
    responseQueue.push(response);
    if (responseQueue.length == 1) {
        fireQueue();
    }
}

function fireQueue() {
    let item = responseQueue.shift();
    item.callback(item.data);
    if (responseQueue.length > 0) {
        fireQueue();
    }
}

Would this code work how I expect? Will all results get into the queue and their callbacks fired in sequence? If not - why not?

How is the chain of responsibility design pattern used with regard to the handling of mouse-click and keyboard events in Windows?

I've just finished working my way through the Head First Design Patterns book and I noticed that the chain of responsibility pattern is "Commonly used in windows systems to handle events like mouse clicks and keyboard events."

To what extent is this pattern used for these events and in what way?

I understand that the chain of responsibility pattern can act like a sort of filter, but what exactly would be filtered? Or in other words what different ways might these events be handled by the chained objects?

The first thing that comes to mind is some sort of mapping system but that doesn't seem to likely, and would surely be pretty inefficient?

Perhaps something to do with combinations of keys (Ctrl + Alt + Del etc.)?

Maybe I'm missing something obvious or have misunderstood something, but it's not instantly apparent to me why this pattern would be useful in this situation.

Good practice: API and MVC - where should I put method / function with SQL query for API

I've done project according to MVC pattern, now I'm looking to add API. I have a separate package for the myresource, and this package contains functions that should return data in JSON (just placeholder text for now). Now I am at the moment where I want to create function/method with the MySQL query and return requested data from MySQL DB. I want to create another method within my model file to keep MVC pattern. However, I do not know, for API should I crate this function in the API servlet or is it good to place this in the model and keep API servlet only to return requested data?

Alternatives to code duplication on add/edit Activities

Say I am developing an app for an Object. The app lets user add Object, open its details and edit Object - a very common setup. I would create an AddObjectActivity which would contain all the input fields required to create Object. Once the Object is created - it can be edited and the edit activity should contain all the fields that create had. That means binding all the fields that create activity has and doing any layout setup - the same as create activity.

It seems to be that I have two options here: duplicate the code completely - create separate activities for add and edit actions OR reuse as much as possible and extend/introduce some kind of indicator indicating which of the actions(add or edit) is being performed.

Duplicating that much code feels wrong and the second option brings a lot of unneccessarty complexity.

This is a very common pattern in applications so I was wondering what is the best way of doing this in Android?

dimanche 26 août 2018

Which design pattern is appropriate

I have a class with these methods:

public List<Vegetables> getVegetablesFromSupermarket(A a, B b);

public List<Vegetables> getVegetablesFromFarm(A a, C c);

public List<Vegetables> getVegetablesFromNeighbour(D d);

Is there a design pattern that allows for this? Factory? Strategy? Parameters are all different, which makes it a little more complicated.

MVP to MVVM Android

One guy from here told me that MVVM is better than MVP he told me many pros and many conts, but I'd like to know if my MVP is well done or if you know any other way maybe to convert to MVVM. It's a Sign in with Google MVP. I won't put all of the code but I'll put the folders and little explanation :

-Model

  • User (Simple user pojo class)

-Presenter

  • I have an object of my IGoogleLoginView where I call the methods, but here I have the logic createGoogleClient(),signIn(),onActivityResult(),onStop(), onStart(), onDestroy() all of those methods are from my interface inside the same package IGoogleSignIn
  • IGoogleSignIn - All of the methods from the Presenter class

-View

  • googleSignIn()
  • goToMainActivity()

And then I have my MainActivity where I call the methods...

I'm wondering how different could be to do that on MVVM and what would be the changes to do it, and also is something that it's not on the good place?

Pattern Match Username

I am trying to make a pattern match a username that has the following rules:

  • No more than 15 characters
  • Must have a full stop in between two strings
  • Digits can only be at the end of the string
  • Only 2 digits allowed

Example Fails

  • .asdfa
  • dadad.
  • 1apple.pear
  • apple.pear123

Example Success

  • apple.pear
  • ben.peach12

Best practice for threshold argument design in an svd function

Sorry for the confusing title but I really can't come up with anything better. I wish to do an SVD decomposition to a matrix and find out some of its largest singular values. To do this, I can write something like this (pseudocode in python):

def singular_values(matrix, num):
    u, s, v = svd_lib.svd(matrix)
    return s[:num]

in which num is an integer, indicating the number of singular values I want. Another approach is:

def singular_values(matrix, thresh):
    u, s, v = svd_lib.svd(matrix)
    num = 0
    for s_value in s:
        thresh -= s_value
        num += 1
        if thresh <= 0:
            break
    return s[:num]

In which thresh is a float from 0 to 1, indicating the proportion of singular values I want. If I want both functions, a good plan (Plan A) seems to be writing the 2 functions separately as I had done here. But it would be rather painful If I want to decide which function to use in the caller function:

def singular_values_caller(matrix, num=None, thresh=None):
    if (num is None and thresh is None) or (num is not None and thresh is not None):
        raise ValueError
    if num is not None:
        return singular_values(matrix, num)
    else:
        return singular_values(matrix, thresh)

A better way to do this might be rewriting singular_values (Plan B):

def singular_values(matrix, thresh):
    u, s, v = svd_lib.svd(matrix)
    if 0 < thresh < 1:
        num = 0
        for s_value in s:
            thresh -= s_value
            num += 1
            if thresh <= 0:
                break
    else:
        num = thresh
    return s[:num]

In this way, the caller function should be easier to write but the argument thresh has two meanings which I also find uncomfortable.

I wonder which of the plan is better? If both are not sound plans, what can I do to improve the code in order to make it easier to read/write/use/modify?

Thank you all for reading this question. It should be quite common because svd is so widely used and my two needs here are also typical.

Understanding the adaptor pattern (c#)

I have a scenario I am coding, where I feel the Adaptor Pattern would be useful. I have a service that has multiple possible providers I want to switch when I like, so as long as each "Adapter" follows the same rules (interface) the underlying code is hidden from the caller.

With this in mind, I've been looking at a number of examples. This code snippet is taken from this stack overflow example:

Interface ITarget
{
  public void GetData();
}

//Decision to use MSDAO
class AdaptorMS : ITarget
{
  public void GetData()
  {
    MSDAO objmsdao = new MSDAO();
    objmsdao.GetDataMethod();
  }
}

// calling code
class Client
{
  static void Main(string[] args)
  {
    ITarget objAdaptor = new AdaptorMS();
    object dummyObject = objAdaptor.GetData();
  }
}

Then we decide to create a new adaptor that we will change to:

//After a month, the decision to use OracaleDAO was taken, so create a new adapter
class AdaptorOracle: ITarget
{
  public void GetData()
  {
    OracleDAO objrracledao = new OracleDAO();
    objoracledao.GetSomeData();
  }
}

// Calling code
class Client
{
  static void Main(string[] args)
  {
    ITarget objAdaptor = new AdaptorOracle();
    object dummyObject = objAdaptor.GetData();
  }
}

I've also seen this example:

public class AdaptorA : ITarget
{
     private TargetA A { get; set; }

     public AdaptorA( TargetA a )
     {
           this.A = a;
     }

     public void GetData() { 
          return this.A.SomeGetDataCall(); 
     }
}

public class AdaptorB : ITarget
{
     private TargetB B { get; set; }

     public AdaptorB( TargetB a )
     {
           this.B = a;
     }

     public void GetData() { 
          this.B.MakeDataCall(); 
     }
}

We have two new adaptors but what I don't understand about the above example, is the fact the Adaptor class takes a parameter for the underlying system it will call (TargetA or TargetB). What's the difference in the two examples? I get the first example, hiding all implementation from the calling code (instance of OracleDAO is inside the adaptor), but not the second. Is there a fundamental difference or have I misunderstood the pattern?

Thanks in advance for any advice!

VSCode: TextMate Regex in User Settings

I'm trying to alter a theme to be more suitable for my daily use but I'm having some trouble trying to customize a specific word or pattern.

I'm using this format at the moment;

"editor.tokenColorCustomizations": {
    "textMateRules": [
        {
            "scope": "comment",
            "settings": {
                "foreground": "#ff0000",
            }
        },
    ]
}

Is it possible to format specific keywords or patterns?

samedi 25 août 2018

Increasing elements in a data structure that follows the Composite pattern

I have often read/heard that the composite pattern is a good solution to represent hierarchical data structures like binary trees, which it is great to explain this pattern because internal nodes are composite objects and leaves are leaf objects. I can appreciate that using this pattern, it is easy to visit every element in an uniform way.

However, I am not so sure if it is the best example if you are considering that a tree is filling on demand (every time an insert method is executed) because we have to convert a leaf to composite object many times (e.g. when leaf has to add a child). To convert a leaf object, I imagine a tricky way like (inspired by become: from Smalltalk I guess):

aComposite = aLeaf.becomeComposite();
aComposite.addChild(newElement);
//destroy aLeaf (bad time performance) 

To sum up, Is a good example the use of a tree-like structure to illustrate the composite pattern if this kind of structure is born commonly empty and then you have to add/insert elements?

Ionic Angular Validator Pattern

I am trying to prevent the user from typing symbols and emojis on the keyboard, for this I am using the pattern validator, but when I type something in the input, this appears

can not read property 'required' of null

how to solve this?

   <form [formGroup]="instituicao">
     <p>Informe os dados:</p>
      <ion-item>
        <ion-label stacked>ONG:</ion-label>
        <ion-input type="text" formControlName="ong"></ion-input>
      </ion-item>
      <ion-item *ngIf="!instituicao.controls.ong.valid & 
      (instituicao.controls.ong.dirty || instituicao.controls.ong.touched)">
      <div [hidden]="!instituicao.controls.ong.errors.required">
        O campo é obrigatório
      </div>
    </ion-item>
    <ion-item text-center *ngIf="
      instituicao.controls.ong.valid">
      <div [hidden]="
        !instituicao.controls.ong.valid">
        <button ion-button outline large color="danger" 
          (click)="createAccount()">Cadastrar</button>
      </div>
      </ion-item>
   </form>

import { FormBuilder, FormGroup, Validators } from '@angular/forms';

createForm() {
    this.instituicao = this.formBuilder.group({
      key: [this.instituicao_array.key, Validators.required],
      ong: [this.instituicao_array.ong,Validators.required, Validators.pattern('[a-zA-Z ]*')]
    })
  }

Would this be considered an abuse of the State Machine Pattern?

I want some type of object that represents a workflow state, where the workflow sets certain values but not in a certain order. I advance the state by using enum flags, like

[Flags]
public enum MyState
{
    None = 0,
    FooSet = 1,
    BarSet = 2
}

public class MyStateMachine
{
    public MyState State { get; private set; }

    public bool Completed
    {
        get
        {
            return State == Enum.GetValues(typeof(MyState))
                .Cast<MyState>()
                .Aggregate(MyState.None, (prev, cur) => prev | cur);
        }
    }

    public string Foo
    {
        get
        {
            return foo; 
        }
        set
        {
            foo = value;
            State |= MyState.FooSet;
        }
    }

    private string foo;

    public string Bar
    {
        get
        {
            return bar; 
        }
        set
        {
            bar = value;
            State |= MyState.BarSet;
        }       
    }

    private string bar;

    public MyStateMachine()
    {
        State = MyState.None;
        foo = null;
        bar = null;
    }

}

Is this an anti-pattern? An abuse of the State Machine Pattern? An abuse of flags? If so, what is the correct pattern I'm looking for?

Regex, How capture repeating pattern with a condition

I have many Strings

1) "book = 12 AND x2 = 50 AND cost = 45"

2) "pen = 1 AND case = 10 AND bala = 40"

.

.

.

And I need to get 'book' , 'x2', 'cost' And 'pen' , 'case', 'bala'

I use this but not work.

(?:(.*?)(?==))+

How to track web user filling patterns on my web form?

I am looking for some libraries or articles or ideas regarding how I can track some customer behavioral patterns when he/she fills my web form. Later I want to apply machine learning to identify fraud or customers in stress. Those patterns can be: speed of typing, number of corrections, entering completely different values, going to the previous step several times and changing his choice, etc.. Actually, the most difficult part is to identify the pattern and to define the type of those patterns (more of those stated above)

I tried googling but couldn't find anything appropriate at all. I dont know where to start

Is it bad form to override the "dot" operator in Python?

Usually, a period in Python denotes class membership:

class A:
    a = 1

>>> A.a
1

Sometimes the language doesn't seem quite flexible enough to completely express an idea from domains outside of computer science though. Consider the following example which (fairly brittly for brevity) uses the same operator to seem like something completely different.

class Vector:
    def __init__(self, data):
        self.data = list(data)

    def dot(self, x):
        return sum([a*b for a, b in zip(self.data, x.data)])

    def __getattr__(self, x):
        if x == 'Vector':
            return lambda p: self.dot(Vector(p))
        return self.dot(globals()[x])

Here we've taken over __getattr__() so that in many scenarios where Python would attempt to find an attribute from our vector it instead computes the mathematical dot product.

>>> v = Vector([1, 2])
>>> v.Vector([3, 4])
11

>>> v.v
5

If such behavior is kept restricted in scope to the domain of interest, is there anything wrong with such a design pattern?

vendredi 24 août 2018

What design patten it is that the class variable has the class itself

A class variable that contains the class itself, for example, the main property of the class DispatchQueue

Question 1

What kind of design pattern it is? Is this so called singleton?

Question 2

How does the object initialized when referring this property?

project design, am I understanding this correctly

I'm a software developer but always worked on "small" projects/solutions. Now I'm trying to create an application from scratch on my own, just to stay in touch with new developments and learn new stuff. I'm trying to use everything I've never used before.
So basically that means I'm developing a c# application, using EF core 2.1 and SQL Server.
I've read a lot of articles online and I learned A LOT already. But I'm still confused because everyday I find a new article using a different approach. I would like the opinion of some other developers on what I've got so far.

First of all I'm used to WinForms so for now I'll use that as my UI. Just because I can get fast results with it. Afterwards I'll try using ASP.NET Core. I also want to be able to use an other UI and still be able to use the rest of my solution.
I have several projects in my solution:
1. Data: EF Context, DbSets, Migrations
2. Models: EF models, used in EF Context (nothing more then POCO's)
3. DTO: Objects exposed to the UI (again, classes and properties, nothing more)
4. Mapper: "DTO to Model" and "Model to DTO"
5. Services: static classes and static methods/functions using all the above, containing the logic. for example GetCustomer uses the EF context class to read the database, gets the model, maps it to a DTO and returns it.
6. UI: binds to the DTO objects and uses the services for every user "action".

That's it, in a nutshell. But am I on the right track?
I've read a lot about IoC but I'm not there yet, but as far as I understand that has "nothing" to do with the above.
I do have 1 specific question: In WinForms there is validation using the IDataErrorInfo interface and for binding I need the INotifyPropertyChanged logic. Where does this belong? I would say in my DTOs but some say a DTO "can't have" any logic.

I'm sorry for the long "question" but I'll appreciate any input to make sure I understand all of this correctly.

How to serialize objects so their nested entities are represented by a id?

Let's say there are objects A, B and C. They're all Doctrine ORM entities.

Object A is the aggregate root - it's a composite of B and C objects. Serializing object A returns it's own data and also properties of B and C. This is something I want to change in the most graceful way possible.

Object A should serialize in a way that retains it's properties but represents B and C with one of their properties - in this case their id. JSON example:

{
  "objA": {
    "property": true,
    "objB": 10,
    "objC": "a1c81b5a-6ecd-4c40-a541-f779b907418c",
  }
}

I was wondering what is a good way that could be used system-wide to achieve that.

This is how I want to represent nested entities in almost every situation in my application - someone suggested me to implement Presentation Models or ViewModels for every case, but isn't there a way to configure this in Doctrine or Symfony's serializer?

Best design for reusable component to use by multiple projects or modules

I’m thinking about how is the best way to design a reusable component for many project I have a base component that I can put it into other modules or projects. But each module or project has some different requirement, it need to add new field on template sometimes in middle sometimes before or after existing field in base view. So when module A add new field I need to hide it from module B and versus. So I take some effort, but right now I just have one idea like that to reuse existing component for 2 modules because it just small different Does anyone has any idea to solve this problem? Thank you enter image description here

Pattern module issue when using Pyinstaller to build an executable

I'm building an executable using PyInstaller (3.3.1), which relies on the pattern.en module (3.6). I'm able to get the executable, but I have the following error messages (depending if I import them as import pattern or from pattern import singularize, lemma, etc.) when I run it:

ImportError: No module named pattern.en

ImportError: cannot import name 'singularize'

module pattern.en has no attribute singularize

I tried the following option (ImportError with PyInstaller (using module pattern.de)):

--hidden-import=pattern.text

but I still get the same error message. I copied all the files (and folders) from ~\Pattern-3.6-py3.6.egg\pattern to the pattern folder created by Pyinstaller, then the program/executable works as expected.

The problem is that I'm using the option of the pyinstaller command --onedir --debug right now, but I'd like to create only one file at the end (i.e., --onefile --windowed). If I do so, I will no longer be able to copy the content of the pattern module.

I tried to add all the paths I could as options (for example, -p C:\Users\Anthony\Anaconda3\lib\site-packages\pattern-3.6-py3.6.egg) as well as all the hidden imports (e.g., --hidden-import=pattern), but it still doesn't work (except by copying the pattern content).

Any suggestions are more than welcome!

Design Pattern not working with OnClickListener

I am trying to develop a abstract OnClickListener caller for all my dialog boxes.

public abstract class  A {
  public void handleError() {
    if (dialogs != null && activity != null) {
       final String mNoxMessages[] = God.getMnoxMessage((Context) activity, response);
       ((Activity) activity).runOnUiThread(new Thread
           (new Runnable() {
              public void run() {
                  dialogs.showDialogForMessage("title", "description", 
                  "ok", "cancel",
                  new View.OnClickListener() {
                     @Override
                        public void onClick(View view) {
                           performDialogOkAction(response);
                           dialogs.clearAll();
                       }
                  }, 
                  new View.OnClickListener() {
                     @Override
                         public void onClick(View view) {
                             performDialogCancelAction(response);
                             dialogs.clearAll();
                        }
                  }
               }));
     );}
   }
   public abstract void performDialogOkAction(Object errorCode);
   public abstract void performDialogCancelAction(Object errorCode);

}


public void showDialogForMessage(String title, String description, 
                     String okButtonText, String cancelButtonText,
                     View.OnClickListener okOnClick,
                     View.OnClickListener cancelOnClick) {

    ok = informationDialog.findViewById(R.id.information_ok);
    cancel = informationDialog.findViewById(R.id.information_cancel);

    ok.setText(okButtonText);
    cancel.setText(cancelButtonText);

    ok.setOnClickListener(okOnClick);
    cancel.setOnClickListener(cancelOnClick);
}


public class B extends A {
 @Override
    public void performDialogOkAction(Object errorCode) {
       //breakpoint location here never reaches
 }
}

When I click the button, the control never goes to the performDialogOkAction method at all.

What am I missing here ?

design pattern when you want to keep original data untouched and add some custom data

I have a challenge at hand to keep original data untouched let's say it's an array of users with properties. Sometimes I want to modify or add custom values for some of those properties for example change age of a user but i don't want to spoil original data and let the opportunity to remove customization altogether or by one. Is there any design pattern which I could try to use for this?

How big should a flyweight object be?

I was reading a book on design patterns and the flyweight design pattern was used to store chars in a text editor. There was written that with large number of objects it saves space, but I don't see how. I mean, the pointer is 4 bytes and a char is 1 byte so how would it save any space?

Calling method one after another spring boot

I have a service which performs a certain set of operations and these operations has to be performed in a sequence like below:

class ABCService{
        @Autowired
        ContextCreator contextCreator;
        @Autowired
        ClassA classAObject;
        @Autowired
        ClassB classBObject;
        @Autowired
        ClassC classCObject;
        @Autowired
        ClassD classDObject;
        @Autowired
        ClassE classEObject;

        public void serviceMathod(Command command){
             //Command has the input data which would be need for by the operations to perform the operations
             //Using the Command object we create the context which would available to all the classes which has the operations. Basically the context object is autowired to all the classes which has the operations
             contextCreator.createContext(command);    
             classAObject.operation1();
             classBObject.operation2();
             classCObject.operation3();
             classDObject.operation4();
             classEObject.operation5();
        }
}

And the above service method is the starting point. Is there a way to clean the above code?

Piece of code which calls operations of different classes 1 by one looks weird to me. Is there any way I could use the frameworks or any design pattern to improve the code?

The application is a standalone server side application using spring boot and spring data JPA.

When should I write interface and abstract class [duplicate]

This question already has an answer here:

When we write a programme using java, we can start writing an interface, abstract class, and next to a concrete class. But without writing interface and abstract class, we can just write the concrete class with all implementations. When should I write an interface, an abstract class with a concrete class?. Because I always write interface and abstract class just as a practice and follow the oop concept. Please explain to me.

real time observer on database table

I'm using Apache Spark under Java project, and i'm triying to build a reel time Observer on Mysql table to start some analytics on this table, now my questions are :

  • It's possible to put an Observation on database Table ?

  • If it's possible, is this a good practice?

.net Regex match Pattern for T-sql columns

I want to find a pattern to match tsql columns like this "select c1,c2,c3,(select c4,(select c5 from t2) c7 from t1) a1, from t3 " is that possiable to match the whole strings between first "select" and last "from" Is there some body can help me?

Rest API, save nested models in one request

As I know in rest we need to save each model in separate request. What if I have 3-4 levels of nested models and would like to save it all in one request, whats the best practice? (Rails, PHP, Node.js)

java builder pattern and changing field

Im having difficulties to figure out how to change some field in a object created by builder pattern: for example this is the class

public class Pizza {
  private int size;
  private boolean cheese;
  private boolean pepperoni;
  private boolean bacon;

  public static class Builder {
    //required
    private final int size;

    //optional
    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;

    public Builder(int size) {
      this.size = size;
    }

    public Builder cheese(boolean value) {
      cheese = value;
      return this;
    }

    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;
    }

    public Builder bacon(boolean value) {
      bacon = value;
      return this;
    }

    public Pizza build() {
      return new Pizza(this);
    }
  }

  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }
}

and Pizza obect is created like this:

Pizza pizza = new Pizza.Builder(12)
                       .cheese(true)
                       .pepperoni(true)
                       .bacon(true)
                       .build();

now what I'm trying to find out is how to change in this object for example cheese field to false? I don't have getters and setters, I know I can use reflection but it makes code harder to read and understand. So is builder pattern useful to not final objects ?

jeudi 23 août 2018

What is the best way to set this class's member variable with a value from a .properties file?

I have several entity classes (using Spring) that also have "helper" classes associated with them that offer additional functionality. A very simplified example:

public class Contact {

    private Integer contactId;
    private String name;
    private int age;

    // Provide access to helper class
    @Transient
    public ContactHelper getContactHelper() {
        return new ContactHelper(this);
    }

    // Getters/Setters omitted
}

public class ContactHelper {

    private static String contactUrlPattern = "http://localhost/GetContact.action?contactId=[id]";

    private Contact contact;
    public ContactHelper(Contact contact) {
        this.contact = contact;
    }

    public String getContactLink() {
        return  contactUrlPattern.replace("[ID]", this.contact.getContactId());
    }

    public void setContactUrlPattern(String str) {
        contactUrlPattern = str;
    }
}

This setup provides a very convenient pattern especially when displaying values. For example, I can now write:

<a href="${contact.contactHelper.contactLink}">${contact.name}</a>

The issue now is I would like to set the contactUrlPattern with a different value from a "production" properties file (change 'localhost' to 'example.com'). Normally I would inject a value using Spring, but since this pattern create a new ContactHelper each time, it is not a part of the Spring Context.

What is the best way to go about setting this variable? I could possibly set it after the ApplicationContext is initialized in a listener since the variable is static. I would have to set about 10-15 different "helpers" and variables -- or is that wreak of code smell?

Choosing the correct design pattern

I'm writing an api in the form of a .net Standard library. In this library, I need to provide the caller a class which will allow me to send and receive messages from a message queue. The underlying queuing system could be anything, such as ServiceBus, NATS or RabbitMQ and therefor should be interchangeable by the caller.

Something like this:

public class QueueWrapper: IQueue {

    private QueueClient _q;

    public QueueWrapper(QueueClient q) {
       _q = q;
    }

    public void Send() { 
        q.send();
    }

    public string Receive() { 
        return q.receive();
    }
}

Called by:

IQueue msgQueue = new QueueWrapper(new RabbitMQClient());

I think the Adapter Pattern is the correct Design Pattern to choose, but wanted to get advice - does this seem like the correct pattern in this scenario? Would you recommend others?

A similar scenario would be having an emailer class that sends mails and allowing different mail providers to be switched.

Thanks in advance!

CSS Design System - How do you handle anomalies?

I'm thinking of making a CSS design system which includes classes like

.text-red {color: red}

However, I have one question I can't solve, how do you handle anomalies (one of events). A common example could be making an element darker for say one element but the rest aren't affected in anyway.

Im super confused, I love the design system approach but anomalies are a big concern.

How to provide an own instance per variable to each thread (avoid sharing the heap in multi-threading)?

My app builds a complex model based on socket input. Assume that the input comes regularly at two different time intervals, in a hourly interval and in a daily interval. The data is treated exactly the same, only that I want to build a "hourly" model and a "daily" model at the same time, in parallel. The simplest solution would be to duplicate the code with two different socket endpoints, in order to send the hourly and daily data to the different endpoints. Obiously this is not an elegant solution. So, is there an elegant way/design pattern/architecture that supports my purposes? The requirements would be as following:

1. Use the same code base to build different models at the same time, based on the type of input
2. At the same time process/cccessing the data of the models at a central place to draw conclusions/combine the models

I thought about letting the application run in two different threads, e.g. one to build the hourly and one to build the daily model.However, I don't want to share my variables between the threads. E.g. Currently my code stores the incoming data into a list, which is then further processed. So when the input is hourly and daily data, I don't want it to be mixed (otherwise I wouldn't get two separate models), but rather be treated separately (without duplicating my code or huge refactoring like making the code work for two instead of one input type). Basically I want my code to be scalable.

How to manage multiple views in a single page with JavaScript?

I am developing a single page application and trying to grasp MVC, MV* structure with vanilla JavaScript. At the moment I have a page that includes a lot of functionality and events. There are some parts of the page that needs to be dynamically rendered separately. Those parts have to interact with each other and a single Model. Creating a single View class for this page seems like it would make it very heavy.

enter image description here

My question is how do I best handle this kind of structure so that the code would be clean, clear and easy to test? Should I create a View for each Part in a page? Should I have those page parts interacting with each other or should they interact through a single controller, presenter? Or should they be working through the single View as some sort of partials?

Please provide some code examples in JavaScript if possible. Thank you..

Inheritace common test steps from base class

    When writing test cases for end-to-end test scenarios using java, selenium, java; we can keep common steps into the base class method and specific add, edit steps in the specific class.

    public abstract class XXXXBaseTest extends SeleniumTest { 

    @Test
    public void validateCalendarUi() throws IOException {
            **ExpCalendar expCalendar = openExpCalendar();**

            String calenderAvailable = expCalendar.getHeaderViewText();
            Assert.assertEquals(calenderAvailable, "Calendar View", "Failed : Calendar is not available");
    }
    }

Then, opened calendar() method is overridden in each specific class with specific steps.

public class XXXXXViewExpirationCalendarTest extends RefDataExpirationCalendarTest {

@Override
protected ExpCalendar openExpCalendar() {
        //Here write specific methods
}

}

Is this appropriate approach for test scripting?.Can we use inheritance concept to write test cases in this way ?

Stateful Strategy with Layout Mangager

I try to understand the difference between stateless and stateful.

As an example i take the Java LayoutManager. Normally i cannot use an instance for example of the BorderLayout for more than one container. I think in a stateful strategy, the Context pass itself as an argument to Strategy operation. So that the strategy can reach all data which is needed for the strategy algorithm.

I have a Code Snippet of a stateful strategy. I think here the context is "creation of the panel" for which we have different strategies.

public class LayoutComparer extends JFrame {
   private LayoutManager layout;
   private String title;

   public static void main(String[] args) {
       JFrame f = new LayoutComparer();
       f.setDefaultCloseOperation(EXIT_ON_CLOSE);
       f.pack();
       f.setVisible(true);
   }

   static int counter = 0;

   JPanel createPanel(LayoutManager layout, String title) {
      this.layout = layout;
      this.title = title;
      JPanel p = new JPanel();
      p.setLayout(layout);
      p.add(new JButton("Click " + counter++), "West");
      p.add(new JButton("Click " + counter++), "Center");
      p.add(new JButton("Click " + counter++), "East");
      p.setBorder(BorderFactory.createTitledBorder(title));
      return p;
  }

  LayoutComparer() {
      setTitle("Layout Manager Test");
      setLayout(new GridLayout(1, 2));
      LayoutManager m;
    m = new java.awt.FlowLayout();
 // m = new java.awt.BorderLayout();

    add(createPanel(m, "Left"));
//  pack();
    add(createPanel(m, "Right"));
  }
}

How to return message-completion results from a consumer back to a producer

We are building an application with a microservice architecture.

The microservice architecture will follow a message-oriented pattern, with AWS SQS.

We would like to return completion results from the consumer service back to the producer service.

This is the algorithm we are considering:

  1. Producer creates a message with a unique id
  2. Producer subscribes to a Redis channel that is named with the message id
  3. Producer places the message onto the queue
  4. Consumer removes the message from the queue and performs an operation
  5. Consumer publishes the results of the operation to the Redis channel that is named with the message id
  6. Producer recieves the completion results and resumes execution

Is this a reasonable way to pass message-completion results from a consumer back to a producer?