dimanche 31 mars 2019

Best practice for adding a new item in client

I have a list that the client fetches from the server. The client can add more items, and it's 'auto save' so no need to press a button. My question is how to manage the new item id (can be several). Do I need to immediately go to the server to get a new key? or can I allocate some key Ids (say 0-10) and later in the auto save call the server will know to assign new keys and notify the client?

Thank you

Refactor Preconditon Pattern

The following is my implementation of the insertion of a B-Tree storing (int,double) pairs:

class BTree {
    class Node {
        ArrayList<Pair> data;
        ArrayList<Node> children;
        // ...
    }

    class Pair {
        int k;
        double v;
    }

    void insert(int k, double v) {
        Node currNode = root;
        while (!currNode.isLeaf()) {
            if (currNode.contains(k)) return; // duplicate insert
            currNode = currNode.forward(k); // go to promising child
        }
        currNode.insert(k, v);
        if (currNode.isOverflow()) {
            handleOverflow(currNode);
        }
    }

    // ...
}


Just to clarify the B-Tree properties for list-based implementation:

For any node, let:

  • a(i) := children.get(i).data.get(j).k for all j (i.e. all key in i-th child node)
  • b(i) := data.get(i).k (i.e. key of i-th data pair)

a(i) < b(i) < a(i+1) is guaranteed.

In order to implement Node.contains(int k), I have to do a binary search on data. In order to implement Node.forward(int k), I have to do the same binary search again.

Please give me some hints on how the redundant binary search could be saved.

What this be considered bad security practice/violation?

  1. Service A has a key to talk to Service B
  2. Service B has an HTTPS API endpoint for starting a job and the consumer of the endpoint supplies through the API the connection string of the message queue of where to send the job metadata when it's completed.

This way A is fully decoupled from B. But is it safe?

How do interfaces break dependancies of classes?

I am reading Clean Architecture - Bob Martin. He talks about breaking dependencies with an interface. For example. Class B uses class A. Thus, class B is dependant on class A(B--->A). We can add an interface and have B dependant on the interface and also have A dependant on the interface(A--->I<----B).

What I am not understanding is that if class A has private member variables that are used in the functions that B needs. Wouldn't I have to rewrite the same code in B that A has? Also, wouldn't this just be duplicate code?

Is there a way to bridge differences between given code and implementation?

In a snake game, the game model doesen't support the implementation that I would like to use.

I'm taking part in a friendly competition of who can write the best AI for a snake game. The game model is a given, we cannot change anything in it. I would like to implement an A* pathfinding AI. The problem is that the coordinates in the games are written in a way that they don't support this solution. The nodes that i would like to use look like the example below.

public final class Coordinate {

    private final int x;
    private final int y;
    }

public class Node {

    private int aStarValueG;
    private int aStarValueF;
    private int aStarValueH;
    private int coordinateX;
    private int coordinateY;
    private boolean isBlocked;
    private Node parent;
    }

I am looking for a way to brigde the differences between the 2 classes. I would like my AI to communicate with the coordinates through the nodes, and vice-verse. I'm familiar with design patterns, and I feel like they are the solution to this problem, but I don't know how. I'm also open to any other suggestions. Thanks.

OO vs POF vs SOLID

i looked over here enter link description here and found that the recommendation not to use anymore in POF but to use OO or SOLOD instead, what are the resons to use these or the other pattern and what is recommended to use in terms of automation java?

How to check that a static variable inside a class is null

I am new to programming and I was watching about Singleton design pattern.

I was trying to make a small implementation of the pattern by creating a Singleton class which have a static variable of type Singleton and a function that if the variable that i created is not instantiated to instantiate it otherwise to return that variable.


class Singleton
{
private:
    Singleton() { std::cout << "I am Singleton \n"; }
    static Singleton instance ;
public:
    static Singleton getInstance()
    {
        if (&instance == (Singleton*)nullptr)
        { 
        instance = *new Singleton;
        }

            return instance;
    }

};
int main()
{

    Singleton::getInstance();
    system ("pause");
} 

When i run it I get a error saying

error LNK2001: unresolved external symbol "private: static class Singleton Singleton::instance" (?instance@Singleton@@0V1@A)

How to handle singleton design patern in ElasticSearch Nest 6.x?

My question is really weird for me because I have to use singleton pattern with Elasticsearch for high performance but I am really open for your advise. My question is how to use singleton with elasticsearch Nest library. I created a proxy library for that. But Whenever I call singleton instance, New index creating in previous index. For example:

var log = new Log("indx1-" + DateTime.Now.ToString("yyyy.MM"), "ind1");

created in elasticsearch : indx1-2019-03

var log = new Log("indx2-" + DateTime.Now.ToString("yyyy.MM"), "ind2");

I can not see my new index : indx2-2019-03

var log = new Log("indx3-" + DateTime.Now.ToString("yyyy.MM"), "ind3");

I can not see my new index : indx3-2019-03

I think my code is correct but I need a help for corect usage for elasticsearch. I desired that when I call "CURL" I have to see that: indx1-2019-03 indx2-2019-03 indx3-2019-03

I tried to solve this problem by calling constructor again when different indexname sending from clients compared to previos indexname:

 if( _instance.indexName != indexName)
    {
        _instance = new ESClient(url, indexName, instanceName);
    }

My Singleton elasticsearch client code :

    public interface ILog
{
    ILog Put(dynamic app);
}

public class Log : ILog
{
    private string url, indexName, instanceName;
    public Log(string indexName, string instanceName)
    {
        this.url = LogSettings.Url;
        this.indexName = indexName;
        this.instanceName = instanceName;
    }
    public ILog Put(dynamic app)
    {
        ESClient.GetInstance(url, indexName, instanceName).Run(app);
        return this;
    }
}

    public class ESClient
{
    private static ESClient _instance = null;

    private static Object _mutex = new Object();
    dynamic pool, settings, lowlevelClient;
    private string indexName = string.Empty, instanceName = string.Empty;
    private ESClient(string url, string indexName, string instanceName)
    {
        pool = new SingleNodeConnectionPool(new Uri(url));
        settings = new ConnectionConfiguration(pool);
        lowlevelClient = new ElasticLowLevelClient(settings);
        this.indexName = indexName;
        this.instanceName = instanceName;
    }

    public static ESClient GetInstance(string url, string indexName, string instanceName)
    {
        if (_instance == null)
        {
            lock (_mutex)
            {
                if (_instance == null)
                {
                    _instance = new ESClient(url, indexName, instanceName);
                }
            }
        }
        if( _instance.indexName != indexName)
        {
            _instance = new ESClient(url, indexName, instanceName);
        }
        return _instance;
    }
    public void Run(dynamic app)
    {

        try
        {
            var serializeddata = PostData.Serializable(app);
            var indexResponse = lowlevelClient.Index<StringResponse>(indexName, instanceName, Guid.NewGuid().ToString(), serializeddata);
            var responseStream = indexResponse.Body; 
            Console.WriteLine(responseStream.ToString());
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Trace.Write(ex.InnerException == null ? ex.Message : ex.InnerException.ToString());
        }


    }
}

Is this an interface, i am trying to do or have speculated of an interface?

i have preferred this answer for understanding and it's intuitive and have come up with some speculation which i need to be assure of.

What is the definition of "interface" in object oriented programming

it says In object oriented programming, an interface generally defines the set of methods (or messages) that an instance of a class that has that interface could respond to

consider this example A class car

class Car{
    function start(){
       print('travelling by car');
}

A class travel

 class Travel{

 protected travel;
 public function travelling('type'){
      if(type==car){
       $this->travel=new car;
         }
       $this->travel->start()
    }

 }

An index

  $travel_obj=new Travel;
  $travel_obj->travelling('car');

(please ignore all other concept standarisation and dependency injection)

Can i say that i made interface between travelling class and car class and the interface is made by passing the some string though it is not making sense of an interface rule like have some standarisation but it is interface between travel class and car class.

Can i say that is if this was an interface of standarisation the only way to make interface is passing as argument like here we passing like a string. is there any other way which i should know.

thank you in advance good peoples.

samedi 30 mars 2019

Constructor runs once in multi-Instantiates of a class in "builder pattern" in react app

I have a class in my react app which uses 'Builder Pattern' and I've imported it in some nested components in my page. for example in parent component and child component, too.

But it seems it calls the class's constructor once! and in second instantiate it has existing data which I've added in previews in previews instantiate. (Not a new and clean instantiate!)

// [Builder pattern] 
class Requester {
    constructor() {
        this.definedHeaders = {}
        console.log('construct', this)

    }

    contentType(contenttype) {
        this.definedHeaders['Content-Type'] = contenttype
        return this;
    }

    async get(url) {
        // ...
    }

    async post(url, data = {}, isFormData = false) {
         // ...
    }
}

export default new Requester();

Interface to have Type and Version information

Does this sounds wrong in design? I am trying to see the most flexible way to handle a template that could get changed over time. For example, with the first version of the application template can have 10 fields. Next version of template can have 15 fields. Issue would not be so much of addition of fields but removal/change of a meaning of field name. The template would be stored as JSON representation. So storing in database with different variations is not a problem. The problem is how best to represent this in OO design principles. Also, in a classical Spring MVC with JSP views what would the best way to handle different variations of stored templates over time?

I was thinking If I store version and Type in database with record(JSON).

To do that in my base interface(Marker like interface) I have 2 methods String getVersion() and getType() would that be wrong considering design principles? If I do this I can query depending the type for any child class when retrieving those objects from database. Imagine the object is stored as flat structure(JSON) in database. For example - > findXTypes() as method. In the method implementation I can find by Type='.tostring()' in the query.

It gets complicated when viewing them .I could do this in controller by @RequestMapping(value = "/myTemplate", method = RequestMethod.GET) public String showRecord(@RequestParam ...) { .... return "myTemplate"+Type + TemplateVersion ; }

Then I would have to introduce a new JSP(View) per version. Not great I know, but otherwise I would have to handle the version in IF statements in the same view, which would be more difficult.

Any good ideas?

reduction of parameter list causing duplicate code

I'm working on an ATM machine project and I frequently need to pass bill amounts as parameters to functions. There are many functions that look similar to

depositCash(int fives, int tens, int twenties, int fifties){...}

I know that it's bad practice to have a function with too many parameters such as 4. So I tried to bundle these parameters in a new class billBundle and pass that as a parameter instead. But then I ran into a new problem of repeatedly having to write duplicate code like the following:

Billbundle billBundle = new BillBundle();
billBundle.setFives(fives);
billBundle.setTens(tens);
billBundle.setTwenties(twenties);
billBundle.setFifties(fifties);
depositCash(billBundle);

And if i just passed all the bills to bill bundle then that would be doing exactly what I was trying to avoid in the first place. How should I handle this? Thanks.

Applying SOLID - SRP to WatchKit - specifically row classes

I am trying to understand how to apply SRP to the WatchKit platform; Specifically row classes.

I say WatchKit because Watchkit has independent table view rows aka cells and I want to use those row classes for as much work on the UI as possible and take UI business out of the main VCs.

I want my view controllers to be responsible only for making network calls and the models to do all the network transformations etc.

Most developers declare only IBOutlets in the row classes. But what other business can be done in those row classes?

Please give examples. Thanks

Is it ok for an Observer to hold references to the Observable?

I'm working on a group project for School and we're making an application in JavaFX. We have some trouble understanding the Observer Pattern and wanted some confirmation whether or not a simple example is correct.

This is a minimal example of a TreeView in JavaFX that observes a list of objects.

The TreeView fxml

<fx:root type="javafx.scene.control.TreeView" xmlns="http://javafx.com/javafx/8.0.162-ea" xmlns:fx="http://javafx.com/fxml/1">/>

The TreeView controller class

public class RoundViewController extends TreeView<Round> {
    private ObservableList<Round> rounds; //reference to the model

    RoundViewController(ObservableList<Round> rounds) {
        super(new TreeItem<Round>());
        setShowRoot(false);

        this.rounds = rounds;

        rounds.addListener((ListChangeListener<Round>)(c -> {
            while (c.next()) {
                if (c.wasAdded()) {
                    addRounds(c.getAddedSubList());
                }
                if (c.wasRemoved()) {
                    removeRounds(c.getRemoved());
                }
            }
        }));
    }

    private void addRounds(List<? extends Round> rounds) {
        rounds.forEach(round -> {
            TreeItem<Round> treeItem = new TreeItem<>(round);
            getRoot().getChildren().add(treeItem);
        });
    }

    private void removeRounds(List<? extends Round> rounds) {
        List<TreeItem<Round>> treeItemsToRemove = getRoot().getChildren().stream()
                .filter(treeItem -> rounds.contains(treeItem.getValue()))
                .collect(Collectors.toList());
        getRoot().getChildren().removeAll(treeItemsToRemove);
    }

}

The Main class

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        ObservableList<Round> rounds = FXCollections.observableArrayList();
        RoundViewController roundView = new RoundViewController(rounds);

        primaryStage.setScene(new Scene(roundView));
        primaryStage.show();

        rounds.add(new Round("Music round"));
        rounds.add(new Round("Guess the facts"));
        rounds.add(new Round("Let's round it up"));
    }


    public static void main(String[] args) {
        launch(args);
    }

vendredi 29 mars 2019

ActivityIndicator (spinner) getting error Unexpectedly found nil while unwrapping an Optional value

In my shared class i write spinner code, it's working fine but, some times it's getting error.

Error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

My code in shared class:

import UIKit

class SharedClass: NSObject {

static let sharedInstance = SharedClass()

var transparentView:UIView!
var spinner = UIActivityIndicatorView()


//Show activity indicator
func activityIndicator(view:UIView) {

    DispatchQueue.main.async {
        let window = UIApplication.shared.keyWindow! //Error : Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
        self.transparentView = UIView()
        self.transparentView.frame = CGRect(x: 0, y: 0, width: window.frame.width, height: window.frame.height)
        self.transparentView.backgroundColor = UIColor.black.withAlphaComponent(0.4)
        window.addSubview(self.transparentView)

        if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
            self.spinner = UIActivityIndicatorView(style: .whiteLarge)
            self.spinner.frame = CGRect(x: 0, y: 0, width: 60, height: 60)
        } else {
            self.spinner = UIActivityIndicatorView(style: .white)
            self.spinner.frame = CGRect(x: 0, y: 0, width: 40, height: 40)
        }
        self.spinner.center = view.center
        self.transparentView.addSubview(self.spinner)
        self.spinner.startAnimating()

        DispatchQueue.main.asyncAfter(deadline: .now() + 600.0) {//Stop spinner after 10 Sec's
            self.stopActivityIndicator()
            //self.transparentView.removeFromSuperview()
        }
    }
}

//Stop activity indicator
func stopActivityIndicator() {
    DispatchQueue.main.async {
        self.spinner.stopAnimating()
        self.spinner.removeFromSuperview()
        self.transparentView.removeFromSuperview()
    }
}

 private override init() {

}

}

I'm calling like this

SharedClass.sharedInstance.activityIndicator(view: self.view)//Play spinner

SharedClass.sharedInstance.stopActivityIndicator() //Stop spinner

This is my login Btn code

@IBAction func onClickLoginBtn(_ sender: UIButton) {

    let networkReachability = Reachability.forInternetConnection()
    let networkStatus:Int = (networkReachability?.currentReachabilityStatus())!.rawValue
    print(networkStatus)
    if networkStatus == NotReachable.rawValue {
        let msg = SharedClass.sharedInstance.noNetMsg
        SharedClass.sharedInstance.alertWindow(title: "", message: msg)
    } else {

        SharedClass.sharedInstance.activityIndicator(view: self.view)//Play spinner
        let parameters = "imei=\(deviceID)&devid=\(deviceID)&ver=\(ver)"
        print("Parameters : \(parameters)")
        var request = URLRequest(url: URL(string: url)!)

        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.httpMethod = "POST"

        print("URL : \(request)")

        request.httpBody = parameters.data(using: .utf8)

        let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
            SharedClass.sharedInstance.stopActivityIndicator() //Stop spinner
            print("error=\(String(describing: error))")
            SharedClass.sharedInstance.alertWindow(title: "", message: "\(String(describing: error!.localizedDescription))")
            return
            }

            SharedClass.sharedInstance.stopActivityIndicator() //Stop spinner

            if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 500 {
                SharedClass.sharedInstance.alertWindow(title: "", message: "Server Error")
            } else if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(String(describing: response))")
            }

            do {
                let response = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]
                print(response!)


                if status == "SUCCESS" {


                } else {
                    let message = res[0]["message"] as! String
                    //Call alert function
                    SharedClass.sharedInstance.alertWindow(title: "", message: message)
                }

            } catch let error as NSError {
                print(error)
                print(error.localizedDescription)
            }
        }

        task.resume()

    }

}

Here when i click login btn first time it's working fine. But when i get response Request timed out.

Error

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={NSUnderlyingError=0x7f9eab767d60 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}

Alert will be displayed. In this scenario when i click login btn second time now app crashed with error : Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value .

1) Is my code formate is correct or not(means function calling and JSON post code)

2) How to solve this error.

Request parameters in Spring Security URL pattern? How to specify up to

Request parameters in Spring Security URL pattern? This is a question about how to specify up to. How do you specify the URL pattern below?

/co/co0001.do?method=save
/co/co0002.do?method=save
/av/av0001.do?method=save
/ri/ri0001.do?method=save

Get _m_s time format from milliseconds

I could have any value in milliseconds like :

1040370

I must alert converted time format : _m_s [ie:17m20s]

Here is how I do it :

function ms(a){
var m = a / 1000 / 60,
s = Math.round(('0.' + m.toString().split('.')[1]) * 60);
m = m.toString().split('.')[0];
alert(m + 'm' + s + 's');
}

ms(1040370);

Is it satisfactory or is there a better way to accomplish the same ?

Is there a good practice to replace SELECT COUNT(*) by table with a row [Counter] for making a real time dashboard

I have a project where we track the performances of all users and display them in a dashboard. The dashboard refresh every 30 seconds.

I track the users actions in a table named Logs with the rows:

[IdUser] [IDActionType] [DateTimeAction]

Now for some clients the table now have 10 millions rows. It's good for keeping a log but not for a dashboard where you do a SELECT COUNT BETWEEN XDate AND YDate every 30 seconds. (There's multiple queries and multiples graphs, it's just simplified for the example.)

Is there lectures, texts, websites talking about optimizing a database / good practices around doing tables for a dashboard.

I'm thinking about doing one table by graph and every table would look like this:

CREATE TABLE GRAPH_USERS_ACTIONS ( [Day], [Action], [Counter] )

Where I would just increment the counter. They can do 500 actions per day so by doing that I can divide the rows after one year by 500 and I can delete rows older than one year without deleting the logs.

Is this good practice? I hate that because it is repeating the data we could get by simply doing

SELECT COUNT(*) FROM Logs where DateTime Between 00:00:00 AND 23:59:59

But that select is so long to execute on the old clients servers.

And do you know any detailed articles about this topic?

How to display a speed like a car dashboard on Android Studio?

I want to display a speed on a Android application using Android Studio like the speed on a car's dashboard. I don't have a slightest of how I should do it. For now I only have an image of the whole ( scale + pointer ), i don't know if I have to separate the two part or not or if I don't need them at all.

I've search on Internet but didn't find what I am looking for.

I want it to be able to move the pointer with the variation of speed ( which is received by Bluetooth send by an Arduino Uno).

Can’t understand controller part of MVC

What exactly are those controllers? We were asked to build an ATM in Java for school project, and part of our design is:

  1. We have accounts that stores most of informations
  2. We have users that can make operations for their own accounts and stores some minor informations. (Also we have atm class to store users and make some toplevel changes)
  3. We have userInterface to catch inputs and use controllers.

Am I right that our accounts are models, interfaces are views and users are controllers?

Thanks a lot to address my problem,!

Ngrx Actions: Corresponding Error Actions for Each Action?

When implementing actions with Ngrx, does it make sense to have a corresponding error action for each action type?

For example:

Option A: Load_Object_Type_X, Load_Object_Type_B, Load_Object_Error

Option B: Load_Object_Type_X, Load_Object_Type_B, Load_Object_Type_A_Error, Load_Object_Type_B_Error

Options A and B can use the reducer to handle the error the exact same way (action reducer can handle both error types in Option B), but I feel that Option B might introduce an awkward quantity of actions with enough actions present. Option A represents that "some error" occurred and can include a stack trace, but the error action itself doesn't explicitly state what action was being processed when that error arose.

I've done some background reading and haven't found anything definitive on what the best practice is - wondering if there's any resources on this. Thanks!

How to refactor two functions that require all of the same but one parameter?

I have two methods that take all but one of the same parameters and run the same code except one additional line for one of the methods. I'm trying to decide what the best approach is to clean up the functions so I'm not duplicating code. Here are the methods in question.

I've tried using a try/except clause, but I feel like that is clunky and overkill. I am considering adding a param to a function that notes if the intent is to create or edit a file but that feels too restrictive.

def create_file(self, file_blob, filename, commit_message, committer_info, branch):
    json_file_data = self._file_data(file_blob, commit_message, committer_info, branch)
    content_url = '{}/{}'.format(self._github_content_url, filename)
    response = self._request(content_url, method='PUT', data=json_file_data)
    self._handle_errors(response)

def edit_file(self, file_blob, filename, commit_message, committer_info, branch):
    file_blob_sha = self._latest_blob_sha_for_file(branch, filename)
    content_url = '{}/{}'.format(self._github_content_url, filename)
    json_file_data = self._file_data(file_blob, commit_message, committer_info, branch, file_blob_sha)
    response = self._request(content_url, method='PUT', data=json_file_data)
    self._handle_errors(response)

Which is the best pattern to design a multi thread GUI?

I have to build a multi thread gui where some threads performs some computations and the gui has to update accoringly to the threads result. Which is the best pattern to design my system?

Java Class/Inheritance Structuring

So I'm trying to determine/remember what type of interface/abstract I have to use to get this layout to do what I want. I have two types of objects:

Widget and ComboWidget. I want both of these to be implemented in other classes. As the name suggests, ComboWidget is a base class that will be comprised of multiple Widget objects. I also want to have some boilerplate functionality such as addWidget(), removeWidget(), listWigets(), etc that will be applied to all items that implement ComboWidget.

Widget itself will do the same as it will be implemented by specific instances of widgets (A button widget, a fillbar widget etc).

I want to be able to have a panel or table that the user can add any widget or combo widget. So for said panel I want to generically refer to the Widget or ComboWidget as just Widget class and it will allow either or, in addition to any other object that implements those. What is the best way to accomplish this?

Best way to explain this is a drawing of sorts:

Widget 
     |_ ComboWidget
                  |_ TableComboWidget
                  |_ BoomHeightComboWidget
     |_ ButtonWidget
     |_ FillBarWiget
     |_ TextWidget

I want to be able to make a function that says addWidget(Widget) and any of the above can be placed as an argument. (Except Widget and ComboWidget themselves as they will likely be the interface/abstracts)

Two classes but same object

I have 2 tables, tblA and tblB, with same fields and types. I get datas through linq to sql so I have 2 partial classes clsTblA and clsTblB.

I have a combo to choose tblA or tblB and I have to read in that table and do some query.

What I'am trying to do is evitate to duplicate code to run the same methods. So now I have (in pseudo-code):

if (combo == "A")
{
  List<clsTblA> listUserNow = ctx.clsTblA.Where(p => p.blabla).ToList();
  List<clsTblA> listUserLastYear = ctx.clsTblA.Where(q => q.blabla).ToList();
}
if (combo == "B")
{
  List<clsTblB> listUserNow = ctx.clsTblB.Where(p => p.blabla).ToList();
  List<clsTblB> listUserLastYear = ctx.clsTblB.Where(q => q.blabla).ToList();
}

But I have in mind something like this (in pseudo-code):

SupClsTable clsTblX = null;
if (combo == A)
  clsTblX = new clsTblA();
if (combo == B)
  clsTblX = new clsTblB();

List<clsTblX> listUserNow = tblX.QueryForNow();
List<clsTblX> listUserLastYear = tblX.QueryForLastYear();

Does it exist something like this? I also searched in design pattern but without results.

Thanks in advance.

I can not to forward exceptions from my proxy class

I have an interface:

public interface ThirdPartySystemCaller {
    void sendRequest(String request) throws ThirdPartySystemException;
}

And implementation:

@Slf4j
@Service
public class ThirdPartySystemCallerImpl implements ThirdPartySystemCaller {

    @Override
    public void sendRequest(String request) throws ThirdPartySystemException {

        if (request == null) throw new ThirdPartySystemException();

        log.info("send: {}", request);
    }
}

And I have a CryptoService witch can sign request:

public interface CryptoService {
    String signRequest(String request) throws CryptoException;
}

And It implementation:

@Slf4j
@Service
public class CryptoServiceImpl implements CryptoService {

    @Override
    public String signRequest(String request) throws CryptoException {
        if (request.length() > 100) throw new CryptoException(); //just for example
        return "signed " + request;
    }
}

Now, I can use these services:

String signedRequest = cryptoService.signRequest("Hello"); 
thirdPartySystemCaller.sendRequest(signedRequest); 

But I need to call both services each time. I want to create Proxy:

@Slf4j
@Service
public class ThirdPartySystemCallerSignedProxy implements ThirdPartySystemCaller {

    private final ThirdPartySystemCaller thirdPartySystemCaller;
    private final CryptoService cryptoService;

    public ThirdPartySystemCallerSignedProxy(ThirdPartySystemCaller thirdPartySystemCaller, CryptoService cryptoService) {
        this.thirdPartySystemCaller = thirdPartySystemCaller;
        this.cryptoService = cryptoService;
    }

    @Override
    public void sendRequest(String request) throws ThirdPartySystemException {
        String signedRequest = cryptoService.signRequest(request);
        thirdPartySystemCaller.sendRequest(signedRequest);
    }
}

But my ThirdPartySystemCallerSignedProxy implement ThirdPartySystemCaller interface and sendRequest method throw only ThirdPartySystemException. But if cryptoService throw CryptoException I need throw it too.

How can I do it?

I was thinking to make unchecked exceptions, But I need to be checked.

Which design pattern solve the multiple rules checking?

I want to save some files of an article which are posted to an ASP.NET MVC Core action. Then i have them as IFormFile in HttpContext. These files can be image, video, and document. Each of these file have their restrictions to save such as size or extension and each type can have own specific restriction. For example the main image of article should not large that 1500* 900. So I decide to put this design to them:

Class Diagram

And my codes:

public interface IArticleFile
{
    void CheckFileRules(IFormFile formFile);
    void SaveFile(IFormFile formFile, string path);
}

public interface IArticleImage : IArticleFile
{
    void CheckImageRules(IFormFile formFile);
}

public interface IArticleVideo : IArticleFile
{
    void CheckVideoRules(IFormFile formFile);
}

public class ArticleMainImage: IArticleImage
{
    public void CheckFileRules(IFormFile formFile) {/*CHECK STH*/}
    public void CheckImageRules(IFormFile formFile) {/*CHECK STH*/}
    public void SaveFile(IFormFile formFile, string path) { /* Save file */ }
}
public class ArticleSummaryImage : IArticleImage
{
    public void CheckFileRules(IFormFile formFile) {/*CHECK STH*/}
    public void CheckImageRules(IFormFile formFile) {/*CHECK STH*/}
    public void SaveFile(IFormFile formFile, string path) { /* Save file */ }
}

public class ArticleDto
{
    /*some properties*/
    public IFormFile MainImage { get; set; }
    public IFormFile SummaryImage { get; set; }
    public IFormFile ThumbnailImage { get; set; }
    public List<IFormFile> Videos { get; set; }
    public List<IFormFile> Documents { get; set; }

}

public class Article: IArticleService
{
    public void AddArticle(ArticleDto articleDto)
    {
        var articleMainImage = new ArticleMainImage();
        articleMainImage.CheckFileRules(articleDto.MainImage);
        articleMainImage.CheckImageRules(articleDto.MainImage);

        var articleSummaryImage = new ArticleMainImage();
        articleSummaryImage.CheckFileRules(articleDto.MainImage);
        articleSummaryImage.CheckImageRules(articleDto.MainImage);

        //Do these for Thumbnail image, videos, and documents
    }
}

But, I think I should use a design pattern here to make them easy to manipulate later and avoid from repeating some of my codes in Service layer. How can I do this in better way?

jeudi 28 mars 2019

design service class for different representation of same POJO

We are on one requirement to design service class which transform a base class instance (I) into different class O1 and O2 object and each of them can be converted into text, xml, json, yaml or zip before sending back to client.

Current flow

  1. We have 2 endpoint to get output (o1 and o2)
  2. Endpoint e1 call to get(id) and endpoint e2 call to read(id)
  3. We read from DB using DAO layer, common for both get and read functions
  4. After DBB call in method get(id) we change db object to produce o1 & similarly read(id) to o2

New Requirement

  1. Endpoint which can transform o2 into yaml then zip it and return back to client.
  2. Endpoint to produce list of o1 and o2.
  3. Endpoint to produce list o2 dump into yaml then zip it and return back to client.
    class Base {
      ...
    }

    class O1 {
      ...
    }

    class O2 {
      ...
    }

    class Service {
      Dao d;

      O1 getO1(id) {
        return Converter.toO1(read(id));
      }

      Base read(id) {
        return d.byId(id);
      }

      O2 getO2(id) {
        return Converter.toO2(read(id));
      }

      List<o1> listO1(){
        List<O1> list = new ArrayList<>();
        Consumer produce = b -> { O1 o1 = Converter.toO1(b); list.add(o1);}
      }

      List<o2> listO2(){
        List<O2> list = new ArrayList<>();
        Consumer produce = b -> { O2 o2 = Converter.toO2(b); list.add(o2);}
      }

      private void read(Consumer produce) {
        d.all().forEach(produce);
      }
    }

Need suggestions on designing pattern and principle to apply for Service class to address this requirement.

Guidance on how to make micro-services communicate effectively

We are embarking on a new project development , where we will have multiple micro-services communicating each other to provide information in cloud native system. Our application will be decomposed into multiple services like Text Cleaner , Entities Extractor, Entities Resolver , Output Converter. As you can see in diagram we have some forking where input to one service in required by other service and so forth.

I wanted to check if some one can guide me here to best patterns:

1- Should we have one Wrapper class which has model classes for all projects as one all of details is needed in final output convertors or how should the data flow so data is sorted out in last micro-service. We want to keep systems loosely coupled and are thinking about how orchestrate this flow without having a middle layer which composes all this data?

2- How to orchestrate this flow? Service Mesh / Api Gateway?

Service Dataflow patterns

How to convert multiple different .csv files with different headers?

Could you help me to figure out the best solution for my task?

I'm reading multiple .csv files and persist the data in a certain table into db.

The table is pretty straightforward and has such columns as first_name, last_name, birth_date

The data in ingress .csv files are also almost similar to each other but first_name header could be represented as first_name, firstName, First Name, etc. Also, the birth_date can be provided in various formats: it can be as yyyy-MM-dd HH:mm:ss:SSS ZZZZZ as dd-MM-yyyy.

My Brute Force approach is to create a mapper for each possible set of headers that would be invoked based on the headers and maps the .csv file to the List of entities. However, it doesn't seem good because it's not extendable at all to create a new mapper per each possible format.

One more requirement that I have is that information should be configurable via external configuration files. It makes me struggle.

Could you advise a good solution to my problem?

c# - Can I refactor functions that have similar inputs but call different services into one generic function?

I am looking for a way to combine x amount of very similar CRUD functions into one without having to use x amount of if else statements to check the type of a generic.

I have Web API controllers that I want to make calls from like this:

Service.Get<FooModel>(number, type, part, version); 

This is to prevent having to have an extremely similar function for 40+ API endpoints. The issue is when I receive this in my service, I have to check the type of the generic given and compare with those 40+ object types in the one function. All of the models currently inherit from a base inherited model.

Current generic function

(Create, Update, Delete functions are similar):

public T Get<T>(string documentNr, string type, string part, string version) where T : InheritedModel, new()
{
    try
    {
        T model = new T();

        if (typeof(T) == typeof(InheritedModel))
        {
           using (var repo = new InheritedModelConsumer(ref _helper))
           {
                model = (T)repo.Get(documentNr, type, part, version);
           }
        }
        else if (typeof(T) == typeof(FooModel))
        {
            using (var repo = new FooModelConsumer(ref _helper))
            {
                model = (T)(object)repo.Get(documentNr, type, part, version);
            }
        }
        else if (typeof(T) == typeof(ComponentModel))
        {
            using (var repo = new ComponentModelConsumer(ref _helper))
            {
                model = (T)(object)repo.Get(documentNr, type, part, version);
            }
        }
        else if (typeof(T) == typeof(BarModel))
        {
            using (var repo = new BarModelConsumer(ref _helper))
            {
               model = (T)(object)repo.Get(documentNr, type, part, version);
            }
        }
        ... and so on
        ... and so on
        ...
        else
            throw new Exception("Type T structure not defined");

        return model;
    }
    catch (Exception)
    {

        throw;
    }
    finally
    {
        _helper.Dispose();
    }
}

This does work, but if it is possible I am looking for something where I can say at run time, "oh I have this object of Type T, and well since I know the functions all have the same inputs I'm going to instantiate this consumer of Type TConsumer, call consumer.Get(inputs), and then return an object of T to whatever API controller called me."

what design patterns can be used

I am new to design pattern. i have a list for task to be completed in java.right now its all in 1 java file as we had time constraints while developing. now i want to refactor it. consider str is input to task1 , task2 and for task 3 i have to input str as well as output from task2, etc. later point of time we want to create kind od pipeline for these task, in the sense, for pipeline1 i might need task1, task4... and pipeline 2 - task2, task3,etc. how do i achieve this? or is there any tool to do this? how ETL tools fall into this problem?

Please help.

Replace A Pattern In String Using Java

I need to replace test word up to next comma in a string.
For example the string is "abc test xy, tmy test 1, vks , csb";
The output after replacement should be "abc , tmy, vks,csb".
Removed test followed by any character or number up to comma.

I tried the following code but did not work.

import java.sql.Timestamp;
import java.time.Instant;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class TESTREPLACE {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //String str = " DEFAULT REPLACEME NOT NULL,";
        String str = "abc test   xy, tcs test  1, vks , csb ";

        String regex = " default.+\\,";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        System.out.println(matcher.replaceAll("\\,"));
    }
}

Which design pattern is suitable illustrated problem below?

I am developing a project in spring boot. There are common required steps will be used by all classes in development phase. For example to make connectivity through jdbc from java program to database the first step is load the jdbc driver, second step is create connection object and so on. The problem is design pattern of my project should restrict the new developer of my project to write new classes in such a way that no requires steps would skip in such condition which design pattern should i use??

Is there a better way to implement dependencies?

Below is my use case:

Employee Management is a separate C# class library project. And there is a setting for Employee Management at application level. It means there is a global Boolean variable isEmployeeManagement

If the variable is true, then all the code related with Management used across whole application should get executed for e.g.

IEmployeeManagement.AddUser();
IEmployeeManagement.DeleteUser();

But if the setting is false then; the below lines should not through any exception. One of the approaches I thought of is like checking the condition.

If (isEmployeeManagement)
  IEmployeeManagement.AddUser();

But I want to achieve this using Interfaces without putting any code in the condition. So if the setting is false, the above code should not through any error.

Appreciate if you could help me with the implementation.

Different represent of object

We have a requirement to represent a base POJO class into different representations.

We are thinking to go with decorator design pattern

Base class Person

class Person {
  String fName;
  String lName;
}


Should be represented into another format for example wherein class P we want to represent fName and lName of Person as a name in class P. There could many more representations. Here I am giving one of them.

class P {
  String name;
}

Need opinion what is best-suited design for such requirement, should we go with model converters?

P Converter.convertToPFromPerson(){
  ...
}

What are some best practices for designing mobile friendly websites?

I have a large amount of experience with general programming languages such as Java, Python and C. I self-study frequently and I am familiar with Design-patterns from the Gang of Four. I have recently been making mobile friendly websites, however overviewing my solutions I can surely suggest that my frontend development skills are not very good, despite a solution being found. I would suggest that I do not implement best practices and I would like to find a palce where I can improve my ability to create mobile response websites. I read a lot of the bootstrap4 framework and it helps for things like navbars, however certain things are not possible.

For example, a recent mobile responsive component of my website can be described in this link https://imgur.com/a/6SgaOVY

The general problem I solved was creating a full-width square with an image, text and an arrow.

For the desktop. The button has a width of 30% and the img is on the left. For mobile, the button has width of 100%, the img is on top, below is the text and finally is the button etc...

To solve such problem I used react and completed is roughly this way

let result;

if (desktop){
     result = /* 40 lines of html to create the solution for desktop */ 
} elif (mobile) {
     result = /* Same 40 lines of html, button width change, html reordering 
     to move the image on top */
} else {
     result = ...
}

{result}

As you can tell I am essentially tripling the code for each case sent back to the user. So far my only understanding of mobile responsive websites is to add a lot of series css conditionals using @media queries.

I have industry level experience with general programming languages but so far most of my frontend development is self-taught.

I would like to find any source of information that teaches best practices for creating efficient, readable, well-written css/html/js that is using to create mobile friendly websites.

Feel free to comment on my previous code example for recommendations

mercredi 27 mars 2019

Decorator design and factory design patterns

I am trying to figure out how to use the users input and output certain information depending on the user input. Can someone provide a simple example of using the decorator pattern for a simple pizza shop for example?

So I know how to go about the decorator pattern, it’s just the user input portion that has me stuck. So let’s say the user wants to make a pizza, they will first choose the size of pizza, and then add ASB many toppings as they want. Then when they have finished, they will see their total price for what they added as well as what they added (like a reciept). This is in Java.

A query on software design/architecture

In book 'Patterns of Enterprise Application Architecture', following is stated:

When thinking of a system in terms of layers, you imagine the principal subsystems in the software arranged in some form of layer cake, where each layer rests on a lower layer. In this scheme the higher layer uses various services defined by the lower layer, but the lower layer is unaware of the higher layer.

On other hand, in book 'Agile Principles, Patterns, and Practices', following is stated on Dependency-Inversion Principle:

High-level modules should not depend on low-level modules. Both should depend on abstractions.

This sort of confuses me. Am I mixing two different things here?

How to ensure functions are run in specific order Python

Im relatively new to python design patterns but I want to ensure my code is as understandable and flexible as possible. Here is an example:

data=query_data(sql)

transformed_data=transform_data(data, arg1, arg2)

train, test, validate = train_test_validate(transformed_data, frac_test, frac_validate)

model = fit_model(train,test, loss, learning_rate)

predictions, f1 = model.predict(validate)

Each function must run in this order. In this particular example the order should be very obvious. But in more complex modules there can be branching paths and it can be unclear without extensive documentation which order the functions should be run in.

It is simple enough to just wrap the module in another function that applies the functions in order but that seems to make a needlessly complex function with many arguments that violates single responsibility.

I've also tried to wrap each function in a class that returns the next class in the sequence which has the appropriate branching methods. This has the advantage that the order of the code is implied in the design of module and methods are only callable at appropriate times. This leads to many many classes, most with just one method where there are no branches. Ive been warned that this is a bad design pattern.

Is there a best way to ensure that code runs in a specific order and that that order is obvious from the design of the code?

Thank you so much for your help!

Java: Best match search on on object with required and optional fields

Assume I have a key/value that has the following structure.

@Value.Immutable
public interface Key {
  EnumFoo required_enum_one;
  EnumBar required_enum_two;
  Optional<boolean> optional_boolean_one;
  Optional<EnumBaz> optional_enum_two; 
} 

@Value.Immutable
public interface Value {
  Message message; 
} 

Assume that I have a key/value mapping, where I have a message value for all the combinations of the required fields, and some combinations of optional fields. For example:

{foo1, bar1, true, baz1 } => msg1
{foo1, bar1, true, <any value except baz1> } => msg2
{foo1, bar2, <any value>, <any value> } => msg3
{foo2, bar2, <any value>, <any value> } => msg4
If I do a look up of {foo1, bar2, false, baz1}, it should resolve to msg3

What would be the best way to implement this? I was thinking of adding a custom @equals to the key where it skips optional matching when it isnt present in mapping collection. As for the mapping collection, I was thinking of a list of key/value tuples which is ordered based on the presence of the optional fields(similar to above code block), so that the key which matches all required fields and most optional fields is selected and the corresponding value is returned?

Is there a better approach? As a bonus, I find myself repeating this pattern for different types. Is there a way to have a reusable solution?

Best way to have a module with a module scoped variable

I am writing a client to talk to a server API in JavaScript. I have an OOP background but am trying to embrace modern EcmaScript.

So I started with this:

customerApi.js:

const baseUrl = "http://myapi";
export const getCustomers = () => { /* get customer code */ }
export const addCustomer = cust => {}
export const deleteCustomer = id => {}

All the functions use baseUrl.

Now I want to refactor so that the code that uses customerApi.js sets/passes in the baseUrl, and the only ways I have come up with are -

make it a class:

export default class customerApi {
  constructor(baseUrl) {
   this._baseUrl  baseUrl;
  }
}

Pass it into every method:

export const getCustomers = (baseUrl) => { /* get customer code */ }
export const addCustomer = (baseUrl,cust) => {}
export const deleteCustomer = (baseUrl,id) => {}

Wrap in a function:

const moduleFn = baseUrl => (
  return {
    getCustomers: () => { /* get customer code */ }
    addCustomer: (cust) => {}
    deleteCustomer: (id) => {}
  }
)
export default moduleFn;

What would be the preferred pattern to implement this?

What is the correct way of structuring private methods that are going to be called inside a classmethod?

What is the correct way of structuring private methods that are going to be called inside a classmethod? There is such a thing as a private classmethod?

class Foo:
    def _bar(self):
        # do something

    @classmethod
    def bar(cls):
        cls._bar()


>> Foo.bar()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in bar
TypeError: unbound method _bar() must be called with Foo instance as first argument (got nothing instead)



Code templates/wire-frames for working with hardware devices

I write GUI desktop applications to work with different hardware devices (I write on C++). Usually an application have several different devices and shall send commands and receive answers from it. Every transaction take some time to write data to a port and wait for an answer. User has to set device parameters from GUI elements, and watch actual parameters. Devices may be dependent or independent from each other, and have some business logic of interactions between them, business logic associated with external data calculations, etc. The main thing - working with multiple devices.

My question is about global understanding.

Every time I try to come up with new classes structure, but I am not happy with the results.
Also I am sure that there are well-known thoughtful solutions for this class of projects, but have no idea how to find them. I do not want to invent my decisions for well-known common problems.
What famous articles and code wire-frames could I watch?

Adapter Design Pattern: Expose private adaptee instance of the Adapter class Except for the Client code?

Is there any way I could have private adaptee instance inside the Adapter class exposed when I need it except for the client code?

To elaborate, there are certain cases where I would want to expose the adaptee instance from the Adaptor for the public, but I do Not want to do it with the client code. Therefore would it be appropriate to write a method within the Adapter class like this one:

public Adaptee ExposeAdaptee(){
    return _adapteeInstance;
}

enter image description here

Create object of one type from object of another type with database lookups

I have an application that gets a car entity from a third party database. I call the entity ThirdPartyCar. My application needs to create a Car entity by using data from a ThirdPartyCar. However, the Car entity must also derive some of its data from my application's database. For example, a status of a ThirdPartyCar might be _BOUGHT and through a database lookup my application must transform to Sold.

I currently have a Car constructor that has a ThirdPartyCar argument. But the Car constructor cannot populate the lookup data since it is an entity and entities should not have a reference to a repositories. So, I also have a service to populate the remaining data:

public class ThirdPartyCar {
    @Id
    private Long id;
    private String vin;
    private String status;
    // more props + default constructor
}

public class Car {
    @Id
    private Long id;
    private String vin;
    private CarStatus status;
    // more props (some different than ThirdPartyCar) + default constructor

    public Car(ThirdPartyCar thirdPartyCar) {
       this.vin = thirdPartyCar.getVin();
       // more props set based on thirdPartyCar
       // but props leveraging database not set here
    }

 public class CarStatus {
    @Id
    private Long id;
    private String status;
 }

 public class CarBuilderService {
     private final CarStatusMappingRepository repo;

     public Car buildFrom(ThirdPartyCar thirdPartyCar) {
        Car car = new Car(thirdPartyCar);
        CarStatus status = repo.findByThirdPartyCarStatus(thirdPartyCar.getStatus());
        car.setStatus(status);
        // set other props (including nested props) that depend on repos

     }
  }

The logical place to create a Car based on a ThirdPartyCar seems to be the constructor. But I have a disjointed approach b/c of the need of a repo. What pattern can I apply such that all data is created in the constructor but still not have the entity be aware of repositories?

What are the effects after making non-chainable setter chainable?

I have the following class.

<?php

namespace CompanyName\DataBundle\Entity\Intern;
class Order 
{
    public function __construct($invoiceAddress){
        $this->invoiceAddress = $invoiceAddress;
    }
    //non-chainable setter
    public function setInvoiceAddress(Address $invoiceAddress)
    {
        $this->invoiceAddress = $invoiceAddress;       
    }
}

Now I want to make the setter (setInvoiceAddress) chainable. So I made the following changes to the function.

//chainable setter
public function setInvoiceAddress(Address $invoiceAddress)
{
    $this->invoiceAddress = $invoiceAddress;
    return $this;       
}

QUESTION: I want to know if the changes are correct and will work when chaining methods.

I have taken example from here.

Node.js resource based ACL

I am implementing a simple Access Control system in Node, and I am wondering what can be the best approach for what I am doing.

I am using Node ACL and it is not clear to me how to block on a per-resource basis.

Let's take the following example: USER ->* PROJECT ->* ENTRY. Users can have multiple projects which contains many entries. Users can be ADMIN or USER.

I created an endpoint /entry/{ID} where user can access an entry detail. The endpoint is accessible to everyone, ADMINs can see all entries, but for User I need to do something similar:

app.get('/entry/{id}', (req, res) => {
    if (user.admin) {
        // Return eveything
    }
    else {
       if (entry.project == user.project) {
           // return it
       }
       else {
           // Unathorized
       }
    }
})


Is there a better approach/pattern to implement this checks on ownership on a resource?

Recommended strategy for a collection with large amount of inserts and multiple readers using different indexes

I need some help with a strategy for a collection that is used in our app. The collection receives a large amount of inserts which we'd like to process as rapidly as possible, yet we also have a UI that allow users to read from this collection using a number of different properties. We're looking for a strategy that permits the fastest insert rates into the collection, yet uses indexes appropriately for the reads.

At the moment it's mostly working, however we are getting to the point where we need to increase both read and write rates so need to decide what to do next. Some initial testing shows we can get better insert rates without the indexes yet clearly our UI falls to its knees. Ideally we'd replicate the collection that 'receives' the documents to another server which has the indexes on it and that is the collection the UI would read from. A short amount of latency is permissible here while the date is copied over. However when we've looked into this in the past using the default replication it seemed very hard to have different indexes on the secondary compared to a primary.

Are there any tools (builtin or otherwise) we can use to perform this? It's not really a traditional "BI" service as the data arrives in exactly the format we want it so there's no need to any aggregations etc and we don't want a "nightly" process as we'd like it to be as near-live as possible (a few seconds, maybe a minute's delay would be OK).

Thanks.

Pyramid Pattern in Java with Star followed by a underscore

I want to print below pattern

*
*_*
*_*_*
*_*_*_*
*_*_*_*_*

but the issue here is I am unable to eliminate last _ symbol below is the output that I am getting

*
*_*_
*_*_*_
*_*_*_*_
*_*_*_*_*_

int row =5;
String star="*";
String undrscr="_";
String s;
for(int i=1;i<=row;i++)
{//System.out.print(undrscr);
    for(int j=1;j<=i;j++)
    {           
        if(i==1)
        {
        System.out.print(star);
        }
        if(i>1)
        {
            System.out.print(star+""+undrscr);
        if(j==i)
        {
            System.out.print("");
        }
        }
    }

    System.out.println();
}

Is it correct to encapsulate KafkaTemplate/handling methods in your own wrapper(and how)?

I try to introduce apache Kafka to our project and change projects architecture to producer-consumer. I experiment on a new test project. For example, I have one producer and two consumers. It is different spring-boot applications(microservices).

In producer service, I need to configure Kafka, create KafkaTemplate. In each consumer, I need to configure Kafka and create handlers(methods with @KafkaListener annotation).

For example, tomorrow we will want to change Kafka to something another, we will change KafkaTemplate and methods with @KafkaListener annotation to an implementation of a new library. This is not a good approach. So I consider that we need to create our wrapper. Something like this:

public interface EventBus {
    void sendMessage(String topicName, String message);
}

And encapsulate KafkaTemplate in the implementation of this interface(KafkaEventBus implements EventBus)

I start to implement it but I faced the fact that I do not understand how to do it. I create a Gradle module with 'event-bus' name. This module is not spring - just java module. I create EventBus interface and implement it:

public class KafkaEventBus implements EventBus {

    private final KafkaProducer<String, String> kafkaProducer;

    public KafkaEventBus() {
        this.kafkaProducer = new KafkaProducer<>(producerConfig());
    }

    @Override
    public void sendMessage(String topicName, String message) {
        kafkaProducer.send(new ProducerRecord<>(topicName,message));
    }

    private Map<String, Object> producerConfig() {
        Map<String, Object> configProps = new HashMap<>();
        configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        return configProps;
    }
}

And stuck. I have questions:

1) Do I need to create a different module(event-bus)? Do I think right?

2) How can implement message handling in this module? If sending something is clear(encapsulate KafkaTemplate and delegate message to it) then with handling ничего не понятно nothing is clear.

Maybe, Are there some examples of this, best practices?

Android: repository pattern what is the best solution to create an object?

This question is about the OOP(class/interface) design.

I am developing an android library, not an app. The app will use this library. This library is developed by Repository pattern.

One repository and 2 data sources (local, remote).

Because the local data source uses "SharedPreference", it needs Context.

Below is my repository interface and implements.

interface MyRepository {

    fun create(String data)

    fun get(key: String): String
}

class MyRepositoryImpl(
        private val localDataSource: LocalDataSource,
        private val remoteDataSource: RemoteDataSource
): MyRepository {

    fun create(String data) {
        localDataSource.create(data);
        remoteDataSource.create(data);
    }

    fun get(key: String): String {
        // temp code
        return localDataSource.get(key)
    }

    companion object {

        private var instance: MyRepository? = null

        fun getInstance(context: Context): MyRepository {
            if (instance == null) {
                val localDataSource: LocalDataSource = LocalDataSourceImpl.getInstance(context)
                val remoteDataSource: RemoteDataSource = RemoteDataSourceImpl.getInstance()
                instance = MyRepositoryImpl(localDataSource, remoteDataSource)
            }

            return instance!!
        }

    }
}

The MyRepositoryImpl is implemented by the Singleton pattern. Because it should be used anywhere in the app. So the app developers should be able to get the instance of MyRepository like:

val myRepository = MyRepositoryImpl.getInstance(context)
val data = myRepository.get("key")

But It looks weird... "getInstance(context)". I think this is not a good approach. Is there any more smart design, please?

mardi 26 mars 2019

Are TDD and DDD architectural patterns or design patterns?

There are design patterns and there are architectural patterns.

I have understood that design patterns aim at solving code complexity, like the Singleton pattern, Repository pattern is a design pattern.

Then on the other side, you have architectural patterns which is aimed at organizing and structuring code. - MVVM, MVC are examples.

However, where does TDD and DDD falls?

Patterns: Translate plain data object object and wire formats

I was inclined to just use the mapper pattern which I use in various places in the app's code for the following task. But I thought it might actually not be the best fit in this particular case:

The task:

  • I need to implement data objects according to a given specification. The specification defines multiple versions for each object type, thus I have for example a class CarV1 and CarV2 representing each version of the specification.

  • I need to translate these models between C++ classes and wire formats (Json, Protocol Buffers), and vice versa.

  • Construction of the objects is rather simple.

As I said, I'd normally use a mapper pattern, define a mapper interface and concrete mappers to map between each format. There are two things though why I ask for your opinion in this case:

  • I'd use the mapper pattern only to map between two, and only two, types of formats, e.g. a database object and a C++ class. I already have a third format in this case, and it's possible that I have to add more formats to translate between in the near future.

  • The versioning adds some complexity on top of the mapping, and I think there needs to be another indirection in between.

I've read about the Translator Pattern [1], but never used it. I think it fits to some degree, but not completely.

I also considered an Abstract Factory. This would allow to create similar objects (in my case versioned objects). But it is not a good fit for mapping between object representations.

What pattern should I use, and why?

looking for specific Design Pattern in C++ that solve this problem

I am looking for specific Design Pattern in C++ that solve this problem.

I want to design a Storyboard. Our version of the Storyboard contains arbitrary many notes (imagine it like putting sticky notes on a board). Every note has a title, a text and a set of tags. E.g. - title: "Test Traceplayer" - text: "Implement a unit test for the class Traceplayer of the spark core framework." - tags: {"unit test", "traceplayer", "testing", "spark core"}

Our Storyboard should enable us to search for notes by title, text and tags. E.g.: searchByTitle( "Test Traceplayer" ) searchByTag({"testing", "unit test"}) searchByText("Implement a unit test for the class Traceplayer of the spark core framework.") For the sake of simplicity we don't want to do any similiarity or prefix matching when searching for a title, tag or text. Only an exact match should give results.

I have number of solution that solve this problem O(1) search complexity But can any one suggest any "Design Pattern" that solve this problem.

Solve that issue with three STL map and get constant time search complexity

Looking for a specific Design Pattern that solves this problem.

I have solved this problem using 3 STL Map and solution get O(1) search complexity

#include <iostream>
#include <vector>
#include <map>

#define INPUT 8 

class Note {
public:
    string Tital;
    string Text;
    vector<string> vec;
    Note(){
        Tital = "\0";
        Text = "\0";
    }
};

class storyBoard{
public:
    void AddNote(string Tital,string Text,vector<string> vec );
    void RemoveByTital(string &tital);
    void PrintStoredData();
    Note* searchByTitle(string titleSearch);

    Note* searchByText(string text_);
    vector<Note*> searchByTag(string titleSearch);

    void printSlip(Note *tm);
    storyBoard(){}
private:

    std::map<string,Note *> TitalMap;
    std::map<string,Note *> TextMap;
    std::map<string,std::vector<Note *> > TagsMap;
};


Note* storyBoard::searchByTitle(string titleSearch){
    auto it_v = TitalMap.find(titleSearch);
    if (it_v != TitalMap.end()){
        cout<< "Tital search result is below:-"<<endl;
        return it_v->second;
    } else {
        cout <<"data "<<titleSearch << "  Not found"<<endl;
        return NULL;
    }
}

Note* storyBoard::searchByText(string titleSearch){
    auto it_v = TextMap.find(titleSearch);
    if (it_v != TextMap.end()){
        cout<< "Text search result is below:-"<<endl;
        return it_v->second;
    } else {
        cout <<"data "<<titleSearch << "  Not found"<<endl;
        return NULL;
    }
}

vector<Note*> storyBoard::searchByTag(string tagSearch){
    auto it_v = TagsMap.find(tagSearch);
    if (it_v != TagsMap.end()){
        cout<< "Tag search result is below:-"<<endl;
        return it_v->second;
    } else {
        cout <<"data "<<tagSearch << "  Not found"<<endl;
        vector<Note*> del;
        return del;
    }
}


void storyBoard::AddNote(string Tital, string Text, vector<string> v){
   Note *note = new Note;
   note->Tital = Tital;
   note->Text = Text;
   note->vec = v;

   TitalMap[note->Tital] = note;
   TextMap[note->Text] = note;

   for (auto it = note->vec.begin(); it != note->vec.end(); ++it){
       //check that is tags already 
       auto it_v = TagsMap.find(*it);
       if (it_v != TagsMap.end()){
           it_v->second. push_back(note);
       } else {
           vector<Note *> &v = TagsMap[*it];
           v.push_back(note);
       }
    }   
}

void storyBoard::printSlip(Note *tm){
    cout << "Tital=" << tm->Tital <<endl 
        << "Text=" <<  tm->Text <<endl
        << "Tags = ";
    for (auto it = tm->vec.begin(); it != tm->vec.end(); ++it){
        cout<< *it<<"\t";
    }    
    cout<<endl<<endl;
}

void storyBoard::PrintStoredData(){
    for(auto tm : TitalMap){
        printSlip(tm.second);
    }
    cout<<endl; 
}

void feed_data_for_testing(storyBoard &Sb);
void TestCase(storyBoard &Sb);

int main() {
    storyBoard Sb;
    feed_data_for_testing(Sb);

    Sb.PrintStoredData(); /*Print all contain data */
    cout<<"************* From Here start searching ************"<<endl;
    TestCase(Sb);
    return 0;
}

void TestCase(storyBoard &Sb){    
    Note* obj = Sb.searchByTitle("Tital-3");
    if(obj != NULL){
        Sb.printSlip(obj);
    }

    obj = Sb.searchByText("Text-4");
    if(obj != NULL){
        Sb.printSlip(obj);
    }

    vector<Note *> vec = Sb.searchByTag("tag-3");
    if(vec.size() !=0){
        for (auto it = vec.begin(); it != vec.end(); ++it){
            //cout<<(*it)->Tital << "\t";
            Sb.printSlip(*it);
        } 
    }   
}

void feed_data_for_testing(storyBoard &Sb){
    vector<string> tags ;
    int count =INPUT;
    for(int i =1;i<=count;i++){
        string tital = "Tital-" + std::to_string(i);
        string text = "Text-" + std::to_string(i);
        tags.clear();
        for(int j =1;j<=i;j++){
            string tag_ = "tag-" +  std::to_string(j);
            tags.push_back(tag_);
        }
        Sb.AddNote(tital,text,tags);
    }
}

I am looking for a design pattern that solves this issue.

When I should use repository pattern in laravel?

I'm reading about the Laravel Best practices to reduce the code duplication as much as I can, then I read about the repository pattern and I'm following this technique but when I was exploring the https://github.com/akaunting/akaunting open source software for accounting, I saw there is nothing related to respository pattern. I really got confused, so when should I use the repository pattern? if it is helpful when why the good projects not use that pattern? or if there is something better than repository pattern?

Which of these two ways of storing multiple static managers are best for performance?

Are these two setups equal in terms of memory-usage and performance?

I'm currently using singeltons to access different managers in my system. But I've noticed that the singelton Get() functions take a fair chunk of the performence because they are called quite often. (I thought the compiler would optimize that, but apparently not)

So I started looking for ways to change this.

One way was just to put them in a big shared-state class. But I'm still working and modifying these managers. So I want to forward declare them, to avoid recompiling (a full recompile takes about 15 minutes).

But then I though, doesn't 'new' put them in another memory position. Not the same as static declared non-pointer variables.

Question 1: How does these two solutions compare to each other, in terms of performance?

Question 2: And are they faster than a simple singleton-pattern?

////////////////////////////////////////////////////////////
// Way 1: Shared State
////////////////////////////////////////////////////////////
// .h

class SharedState
{
    // Just put all managers here
    static ObjectManager1 manager1;
    static ObjectManager2 manager2;
    static ObjectManager3 manager3;
    static ObjectManager4 manager4;

    // Class things
}

or


////////////////////////////////////////////////////////////
// Way 2, Shared State (With pointers)
////////////////////////////////////////////////////////////
// .h 

class SharedState
{
    // Just put all managers here
    static ObjectManager1* manager1;
    static ObjectManager2* manager2;
    static ObjectManager3* manager3;
    static ObjectManager4* manager4;
}

// .cpp
void Init()
{
    manager1 = new ObjectManager1();
    manager2 = new ObjectManager2();
    // Blah blah
}

MVC pattern > good practice

I'm a little bit confuse with the MVC pattern. If I understand what is Model, View, Controller schema. I don't know what is the correct practice about processing model's request result.

-Model should only handle getter and setter, then it's the controller process datas.

Or

-Model could also own some method to preprocess datas to send it to controller ?

What are chainable and not-chainable setters in PHP/Symfony? [on hold]

While I can say the following is the non-chainable setters.

public function setCategory($category): Product    
{    
    $this->category = $category;    
    return $this;   
}


/**    
* @param $sku    
* @return Product    
*/

public function setSku($sku): Product    
{    
    $this->sku = $sku;    
    return $this;    
}

I am not sure how chainable setters would work. Can I have a simple example for both?

On the creation of a scripts that calls several other with diferent inputs

I'm downloading a lot of data from websites that I need to upload to a DB after. I have several scripts, each with Its own input, i.e. date, value, columns, etc. What I now want to do is to create a script that calls the other 3 on schedule.I was thinking about using a main script to call an to parse configs files, but I also looked at libraries like multiprocessing and subprocessing, but don't know which one to use, as the former looks more rigid and dificult to scalate. My script is going to be running in a server downloading data every half hour or so, so input from the user on each function is out of the question. How can I aproach this issue?

Thanks in advance

How to find every piece of code in my project that addressing/accessing file system?

I need to find every place in the code (in Java project) where it somehow treats file system (e.g. creates file, reads file, gets the list of directory files etc.)

What is the most common pattern to do this type of search? How not to miss something?


Also, I'm interested in existence of pattern for accessing file systems. Do I need to do such access over the one specific utility (provider, manager, controller...) class?

This question may seem too broad, apologies in advance.

lundi 25 mars 2019

Redis vs HTTP for communications between services

We have a monolithic Rails API that was also serving our Websockets. Recently, we outgrew ActionCable and we decided to move our Websockets to Elixir's Phoenix.

In this model clients still interact with the Rails application for HTTP requests, but Phoenix handles all the Websocket traffic. Rails communicates to Phoenix what data to send and on what channel then Phoenix acts essentially as a passthrough for what Rails sends it.

I had initially set this up using Redis PubSub for communication from Rails to Phoenix. It works well at its current scale, but I'm starting to think that it may have been an inferior choice. Here is my list of pros and cons:

Redis

Pros:

  • Ordered messages (not important in our case)
  • Acts as a proper queuing mechanism
  • Wicked fast and dead simple publishing from Rails

Cons:

  • No competitive consumers - I would have to manually implement balancing if I had multiple Phoenix consumers (a real possibility)
  • Concurrency is more difficult to implement well (which really acts against Elixir's strengths)

HTTP

Pros:

  • Concurrency comes for free
  • Load balancing comes for free - a request will only be fulfilled by a single Phoenix consumer
  • Slightly more simple to implement

Cons:

  • Unordered messages (not important for us)
  • Much slower to send a message from Rails
  • Would have to manually implement retry and timeouts on the HTTP requests from Rails
  • If a message is lost (due to server restarts or similar), it's gone for good

Even after weighing it out, I still find it hard to claim one as being the clear choice. Are there patterns for Redis or HTTP communication between services that alleviate some of my problems? If not, which of these two would be preferred, considering the cons?

Is there another simple alternative that I'm overlooking? I don't want to involve something like Rabbit MQ if it can be avoided.

Isn't CQRS + MediatR a glorified service locator pattern?

I have started working with CQRS a while ago using ASP.NET Core and the awesome MediatR library. I love MediatR and the idea to decouple the Request/Notification objects from the actual implementations (Request/Notification handlers).

For messaging, the INotification part is perfect, because as the sender I do not care about who will receive my notification and what they will do with it.

For IRequests however, I am making an assumption that there exists a single IRequestHandler that will process my request and return the data I want. And by injecting IMediatR instead of the handler itself, I am hiding this dependency, which feels much like the Service Locator (Anti-)Pattern.

Here is a pseudo-code example to illustrate. Assume PerformComplexCalculationCommand, PerformComplexCalculationCommandHandler and CalculationResult exists.

public class ComplexController : Controller {
    private readonly IMediator _mediator;
    public ComplexController(IMediator mediator){
        _mediator = mediator;
    }

    public async Task<IActionResult> SomeAction(PerformComplexCalculationCommand command){
        // Here I have an implicit dependency on an IRequestHandler<PerformComplexCalculationCommand> which I'm hiding
        var result = await _mediator.Send<CalculationResult>(command); // generic argument made explicit for illustration
        return Ok(result);
    }
}

This is code that I learnt to write from many Clean Architecture lectures from professionals. Now let me change this up a little to illustrate my point.

public async Task<IActionResult> SomeAction(PerformComplexCalculationCommand command){
    IRequestHandler<CalculationResult> handler = _mediator.GetHandler<PerformComplexCalculationCommand, CalculationResult>();
    var result = await handler.Handle(command);
    return Ok(result);
}

This is the same logical operation, right? In fact this is exactly what MediatR does in its Send implementation.

Simplified code, I stripped out the irrelevant parts, it is from Mediator.cs:35-40

var handler = Activator.CreateInstance(typeof(RequestHandlerWrapperImpl<,>).MakeGenericType(requestType, typeof(TResponse)));
return handler.Handle(request, cancellationToken, _serviceFactory);

where RequestHandlerWrapperImpl will call a service locator to look up and create the actual IRequestHandler. Now you can just call IMediator IServiceContainer and you arrived at the Service Locator pattern.

So how is this not a violation of the Explicit Dependencies principle? Looking at my controller code, there is not a sign that it relies on PerformComplexCalculationCommandHandler for it to work correctly. How do I know that an IRequestHandler is safe to remove, or change. Or is my logic flawed? Don't take me wrong, I love to work with MediatR, I am just worried about reintroducing the maintenance headaches I learnt to avoid by using explicit dependency injection instead of locating or creating dependencies myself.

What pattern can you advice to solve a task?

I have an assignment and I would like to figure out which pattern is better to utilize.

The task is pretty straightforward:

Develop an application that consumes various text files which differ from customer to customer, parses them one-by-one and persists into the database in a unified form. The application is going to be used by numerous customers.

For example, one .csv file can contain the following payload:

day,time,year,name,surname
01,12:00,2019,Andrey,Arshavin
... 

Another file can look like:

day,time,year,fullName,country
01,12:00,2011,Cristiano Ronaldo,Portugal
...

And the database table has the following columns:

date(Timestamp),firstName(String),secondName(String)

The goal of the project is to provide a solution with a clear design.

The first idea that I have is to create different DTOs for different customers and one Entity class. On each .csv read, make a List<DTO> by using a factory method and after convert it to the List<Entity> and persist.

But how can I make it more extendable and maintainable? I think the spaghetti code is not a good idea for each new customer I will have to add

"if that customer then return such new object"

Design patterns to implement SOLID principles

Recently I was asked in an interview on what design patterns are suitable for implementing the Solid principles. As I have understood, OCP can be implemented with strategy pattern. Other than that I couldn’t relate any other pattern to other principles. Would be really appreciated if someone can help me point out on what patterns can be used to implement SRP, LSP and ISP in C#.

Why should we use interface in MVP pattern for Android?

I'm making an Android app using Kotlin for the first time using MVP pattern. My questions is, why do I need interfaces for View and Presenter as Kotlin provides higher order functions? Can't we just communicate using those higher order functions? Is the use of pattern without interfaces bad?

I have looked and read lots of article and tutorials but non answered my question. Is what I am doing in the code below a wrong practice? Can someone explain it to me?

In my Activity

override fun init() {

    btn_login.setOnClickListener {
        LoginPresenter.userLogin(et_emailAddress.text.toString(),et_password.text.toString()){
            if (it){
                //do something
            }else{
                //do something
            }
        }
    }
}

My Presenter

object LoginPresenter {

fun userLogin(emailId: String, password: String, completion: (Boolean) -> Unit) {
    //do something
    completion(true)
 }
}

dimanche 24 mars 2019

Design patterns/ Structure to flow when creating chatbots through java without other frameworks like SLACK,MICROSOFT BOT FRAMEWORK

I want to know what should be my approach if I want to create a domain specific chatbot. More specifically what is the best approach to create the brain of chatbot i.e. the part which decides which method to call to retrieve information.

I know a message should parsed to get the interrogative pronouns which will decide the INTENT and other keywords should be compared with my domain specific words collection, which will be my ENTITIES. Now with these INTENT and ENTITIES I am deciding which method to call based on a long if-else ladder. I am worried that with increase in capabilities this if-else ladder will grow huge and is definitely not the approach, the smart people in the world are following.

Though the implementation of methods is not important, in my case the methods are fetching data from linux server and oracle database. I am using JAVA.

How should I move forward now, any algorithm or design pattern being followed in the Industry? Any link,article,book or guidance is appreciated. Thanks!!!

Can someone explain Javascript classic module pattern and why IIFE is important?

I came across this code, which I don't understand what is going on, and then I removed the IIFE parenthesis and the console.log didn't work anymore, can someone explain what is going on, It is called the classic module pattern.

var foo = (function(){
  var publicAPI = {
    bar: function(){
      publicAPI.baz()
    },
    baz: function(){
      console.log('baz')
    }
  }
  return publicAPI
})()

foo.baz()
foo.bar()

removing the IIFE parenthesis the console.log doesn't work anymore.


var foo = function(){
  var publicAPI = {
    bar: function(){
      publicAPI.baz()
    },
    baz: function(){
      console.log('baz')
    }
  }
  return publicAPI
})


Thank you a lot in advance.

How to design a laser range sensor that can measure 70 meters

I need to design a 360 degree laser measurement sensor that can measure up to 70meters.I have a 500mW and 905nm laser diode.I will send the beam coming from the laser diode to a distance of 70 meters and I will collect the reflected beam with the help of a lens.Could you help me how to design it?

samedi 23 mars 2019

Trying to build a simple Pipe and Filter

I am trying to implement the Pipe and Filter pattern integrating TPL Dataflow within it. I am having issues where not all my results are churned out. For example, i put 99999 items into the pipeline and only 85238 came out.

EmployeeModel.cs

public class EmployeeModel
{

    public String FirstName { get; set; }

    public String LastName { get; set; }

    public String FullName { get; set; }

    public override String ToString()
    {
        return $"FirstName: {FirstName}\nLastName: {LastName}\nFullName: {FullName}\n";
    }
}

IFilter.cs

public interface IFilter<T>
{
    T Execute(T input);
}

AbstractParallelFilter.cs

public abstract class AbstractParallelFilter<T> : IFilter<T>
{
    public AbstractParallelFilter()
    {
        TransformBlock = new TransformBlock<T, T>(new Func<T, T>(Execute), new ExecutionDataflowBlockOptions()
        {
             BoundedCapacity = DataflowBlockOptions.Unbounded,
             MaxDegreeOfParallelism = Environment.ProcessorCount

        });
    }


    public abstract T Execute(T input);

    internal TransformBlock<T, T> TransformBlock { get; private set; }
}

IParallelPipeline.cs

public interface IParallelPipeline<T>
{

    IParallelPipeline<T> Register(AbstractParallelFilter<T> filter);

    IParallelPipeline<T> CompleteRegisteration();

    IParallelPipeline<T> Process(T input);

    Task CompleteProcessing();


    ConcurrentBag<T> Results { get; set; }
}

AbstractParallelPipeline.cs

public abstract class AbstractParallelPipeline<T>: IParallelPipeline<T>
{

    public AbstractParallelPipeline()
    {
        filters = new List<AbstractParallelFilter<T>>();

        Results = new ConcurrentBag<T>();
    }

    public IParallelPipeline<T> Register(AbstractParallelFilter<T> filter)
    {
        filters.Add(filter);
        return this;
    }

    public abstract IParallelPipeline<T> Process(T input);

    public Task CompleteProcessing()
    {
        if (filters.Count == 0)
            throw new Exception("No filters have been registered");

        filters.First().TransformBlock.Complete();

        return filters.Last().TransformBlock.Completion;
    }

    public IParallelPipeline<T> CompleteRegisteration()
    {
        if (filters.Count < 2)
        {
            return this;
        }
        else
        {
            for (int i = filters.Count - 2; i >= 0; i--)
            {
                filters[i].TransformBlock.LinkTo(filters[i + 1].TransformBlock, new DataflowLinkOptions() { PropagateCompletion = true });
            }

            ActionBlock<T> dumpBlock = new ActionBlock<T>(x => Results.Add(x));
            filters.Last().TransformBlock.LinkTo(dumpBlock, new DataflowLinkOptions() { PropagateCompletion = true });
        }

        return this;
    }

    public IList<AbstractParallelFilter<T>> filters;

    public ConcurrentBag<T> Results { get; set; }
}

ParallelPipeline.cs

public class ParallelPipeline<T> : AbstractParallelPipeline<T>
{
    public override IParallelPipeline<T> Process(T input)
    {
        filters.First().TransformBlock.Post(input);
        return this;
    }
}

Program.cs

class Program
{
    static void Main(string[] args)
    {
        List<EmployeeModel> employeeModels = new List<EmployeeModel>();
        int count = 99999;

        for (int i = 0; i < count; i++)
        {
            EmployeeModel employee = new EmployeeModel()
            {
                FirstName = NameGenerator.GenerateFirstName(Gender.Female),
                LastName = NameGenerator.GenerateLastName()
            };
            employeeModels.Add(employee);
        }

        IParallelPipeline<EmployeeModel> parallelPipeline = new ParallelPipeline<EmployeeModel>()
            .Register(new ParallelFirstNameToUpperFilter())
            .Register(new ParallelLastNameToUpperFilter())
            .Register(new ParallelFullNameConcatFilter())
            .CompleteRegisteration();

        for (int i = 0; i < count; i++)
        {
            parallelPipeline.Process(employeeModels[i]);
        }
        parallelPipeline
            .CompleteProcessing()
            .Wait();


        Console.WriteLine(parallelPipeline.Results.Count);

        Console.Read();
    }
}

A design pattern for two different "strategies", that do not implement the same interface

I've built some program with ReactJS and SocketIO, that serves as a fully customizable tool for communicating with a socketIO server.

You can register events to listen to, send messages of any type, pass configuration object to the connection, etc.

Now i've decided to add support for native websockets. The problem is, that native web sockets are simpler, and do not implement the same functionality that SocketIO does.

For instance, i have this method in my React container(where all my main logic is concentrated, no Redux):

registerEventToSocket = (instanceId, socket, eventName) => {
      socket.off(eventName);

      socket.on(eventName, (...args) => {           
        const lastArg = args[args.length - 1];
        const isFunction = this.isFunction(lastArg);

        if (isFunction) {
          lastArg();//If a callback was supplied from the server, it is invoked.
          var index = args.indexOf(lastArg);
          if (index > -1) {
            args.splice(index, 1);
          }

        }

        this.addMessageToState(instanceId, eventName, args, false)
      })
    }

This method is called when the user "adds an event" to listen to. In the case of native websockets, there is only one event to listen to, which is "onmessage" event, so this whole functionality is irrelevant.

The app does few more things that would be useless with native sockets, like an option to "listen to all incoming events".

I'm trying to think of some good design pattern, which i could use to create some polymorphism here, to deal both with the SocketIO case, and the native one.

I'm familair with "strategy pattern", which i used a lot, but in my case both "strategies" would implement two different interfaces, which would violate SOLID principles.

Any suggestions?

Looking for a better way to implement MapView with multiple BottomViewController (or PullUpController)

I am not very experienced in handling iOS applications so might be a stupid question.

I want to display a Map along with different bottom views. When first time the view is loaded, it displays Map along with first bottom view. When user performs an action, it displays the second bottom view but with the same Map View i.e keep the same Map view but display bottom view based on user action. I am looking for a better way to display bottom view based on user action and if user click on back button, it should return to last-displayed bottom view.

  • I tried to apply NavigationController on the bottom view controller (which is a child controller to Map View Controller) but it displays the child view in the entire windows instead of displaying in the bottom.

  • I also thought of registering bottom views to an event and show/hide bottom view based on what kind of event occurred. But here I also want to keep track of last event so when user clicks on back button it should display the last view. As this is very initial state so don't know if it's a good idea or not.

When splitting 1 service into multiple services, do the configurations for the service need split and each part stored in the services?

Let's say you have a "monolith" with a set of configurations

{
    id: 1273,
    fooConfig: { .. },
    barConfig: { .. },
    bazConfig: { ...}
}

and you want to split it into Foo, Bar and Baz services which run jobs when asked to by a central workflow engine.

Do you need to store each of the configurations in the services, like

// Foo service config (stored in Foo service)
{
   id: 1273,
   .
   .  // fooConfig stuff
   .
} 

// Bar service config (stored in Bar service)
{
   id: 1273,
   .
   .  // barConfig stuff
   .
} 

// Baz service config (stored in Baz service)
{
   id: 1273,
   .
   .  // bazConfig stuff
   .
} 

or can you store the configuration in some other service (say Configuration Manager service) and input the respective parts of it into the 3 job services when they are invoked?

What is the best/recommended way to gather user input selections in MVC app design?

I'm creating an app that requires users to setup the game with certain preferences/parameters to the game (number of points to play to, number of players, etc.) and am wondering what is a generally recommended way to gather these inputs. The things I'm struggling with is that I'm trying to adhere to MVC design to separate my View (buttons) from my Model (variable values), but that means that whenever the user touches a button to change one preference, I need to update 2 things: both the View and the Model. Seems kind of inefficient. In my case, would it be better to reload the display and re-save the relevant variable for that preference every time the button is clicked, or would it be better to do nothing with my model when each button is clicked until the user finally clicks to "create the game", in which I scan through all the buttons and gather what their current states are?

Can model use observer to get input?

Observer by definition is just an observer/update mechanism and if user interacts with model, it leads to MVC pattern but can a model ask observer to get input?

From implementation point of view, it works well and the model waits for input from the user but would this be a bit of violation of observer pattern (which is generally one way)?

Alternatively, I will have to handle the case when the observer needs input in a view and make the method in model not ask for user input.