mercredi 28 février 2018

Is a ContentResolver an example of the Adapter pattern for a ContentProvider?

As the title asks, is the ContentResolver an example of the Adapter pattern for the ContentProvider?

What's the best way to write adapters around inherited classes in java?

I have some Logic:

public interface Logic {
  Object doSomething(LogicData data);
}

The LogicData is supposed to hold data fields that different implementations of the Logic could use, given that not all Logics would need all data to be there:

public class FirstLogic implements Logic {
  Object doSomething(LogicData data) {
    // Uses data.x;
  }
}

public class SecondLogic implements Logic {
  Object doSomething(LogicData data) {
    // Uses data.y;
  }
}

I'm now trying to write a LogicData interface which I could later extend by writing adapters, and it goes like this:

public interface LogicData {
  X getX();
  Y getY();
}

Here comes the tricky part. I'm trying to write adapters that would extend this LogicData. The adapters are to take in a hierarchy that look like this:

public abstract class CommonData {
 X x;
}
public class SpecificData extends CommonData {
 Y y;
}
public class OtherData extends CommonData {
 ...
}

Thus, I've written a generic adapter that looks like this:

public abstract class CommonLogicDataAdapter<Data extends CommonData> implements LogicData {
  ActivityData data;

  @Override
  X getX() { return data.getX(); }
} 

Now I need a concrete adapter. This one can handle the SpecificData:

public abstract class SpecificLogicDataAdapter<Data extends SpecificData> extends  CommonLogicDataAdapter {
  ActivityData data;

  @Override
  Y getY() { return data.getY(); }
} 

All's good in the world, right? Nope. Now I'm stuck as to the best way I can write an adapter for OtherData. The problem with OtherData is that it can getX() but can't getY(), but that's fine. As I said, not all Logics need all Data. I still want to be able to use OtherData with FirstLogic, even though it can't be used with SecondLogic.

Here are my options:

  1. Throw an UnsupportedOperationException/return null in OtherData's getY(). This would mean relying on the developer to not make that mistake, but I'd rather get a compiler error instead. It would also mean though that using my adapters would require try-catch blocks/null checks, which I really don't want to do.
  2. Separate LogicData into LogicDataX and LogicDataY, but now I can't write decorators that would chain my Logic if I wanted to.
  3. Make LogicData getX only and extend it with another implementation LogicDataY which would getY, but that would entail changing SecondLogic to take a LogicDataY as a parameter and now I also can't chain my logic.

What's the best way to write adapters around inherited classes in java?

How to avoid a Singleton with multiple VCs depending on UserModel

this question is not so technical rather theoretical. And yeah, avoiding singletons can be found all over the internet but let me explain my situation.

I am developing an app where a user can log in and a tab bar with multiple ViewControllers is presented to him. The problem is that almost all of the ViewControllers need an access to the UserModel (class) that is logged in. I don't want every ViewController to load the user from a storage, so the first solution I came up with was a Singleton. But you know, singletons shouldn't be used to avoid passing variables around or just as a global variable. Searching the web I found that dependency injection might be the solution however it would mean that the TabBarVC would be initialized with UserModel to be able to initialize all its ViewControlllers with UserModel and it would be a lot of passing variables around.

This situation sounds like a typical example of avoiding singletons but unfortunately, I wasn't able to found an ideal solution on the internet.

Any ideas how to solve this problem? What might be the best / optimal solution for having so many ViewControllers depend on the UserModel? How to avoid using a singleton in this case?

Thank you for any ideas!

UICollectionView and MVVM

I'm trying to understand how I can use MVVM to develop a reusable UICollectionViewController.

Suppose you create a view model for each type of UICollectionViewCell

struct CollectionTestCellViewModel {
    let name: String
    let surname: String

    var identifier: String {
        return CollectionTestCell.identifier
    }

    var size: CGSize?
}

And the cell:

class CollectionTestCell: UICollectionViewCell {
    @IBOutlet weak var surnameLabel: UILabel!
    @IBOutlet weak var nameLabel: UILabel!

    func configure(with viewModel: CollectionTestCellViewModel) {
        surnameLabel.text = viewModel.surname
        nameLabel.text = viewModel.name
    }
}

In the view controller I have something like that:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let viewModel = sections[indexPath.section][indexPath.row]
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: viewModel.identifier, for: indexPath)
    configure(view: cell, with: viewModel)
    return cell
}

So far no problem. But consider now this method of UICollectionViewDelegateFlowLayout:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let viewModel = sections[indexPath.section][indexPath.row]
    return viewModel.size ?? UICollectionViewFlowLayoutAutomaticSize
}

The point is I have layout information (the size of the cell) in the view model. This allows me to put in my view controller the layout delegate methods, but I don't know if this violate the MVVM pattern.

The final question is: what should I put inside the view model (of a cell for example)? It is "allowed" to put layout data inside the view model?

Thanks

Java - Command Pattern with additional argument parsing

Recently I have really focused on design patterns and implementing them to solve different problems. Today I am working on the Command Pattern.

I have ended up creating an interface:

public interface Command {
    public void execute();
}

I have several concrete implementators:

public class PullCommand implements Command {

    public void execute() {
        // logic
    }
}

and:

public class PushCommand implements Command {

    public void execute() {
        // logic
    }
}

There are several other commands aswell.

Now.. the thing is there's a BlockingQueue<Command> which runs on a different thread using .take() to retrieve queued commands and execute them as they come in (I'd call this Executor class below) by another class which produces them by parsing the user input and using .queue(). So far so good...

The hard part about me is parsing the command (CLI application). I have put all of them in a HashMap:

private HashMap<String, Command> commands = new HashMap<String, Command>();
commands.put("pull", new PullCommand());
commands.put("push", new PushCommand());
//etc..

When user inputs a command, the syntax is such that one thing is for sure, and it is that the "action" (pull / push) comes as first argument, so I can always do commands.get(arguments[0]) and check if that is null, if it is, then the command is invalid, if it isn't, then I have successfully retrieved an object that represents that command. The tricky part is that there are other arguments that also need to be parsed and for each command the algorithm for parsing it, is different... Obviously one thing I can do is put the arguments[] as a parameter to the method execute() and end up having execute(String[] args) but that would mean I have to put the parsing of arguments inside the execute() method of the command, which I would like to avoid for several reasons:

  1. The execution of Command happens on a different thread that uses a BlockingQueue, it executes a single command, then another one etc.. The logic I would like to put inside execute() has to ONLY be the execution of the command itself, without the parsing or any for example heavy tasks which would slow the execution (I do realize parsing several args would not mess up the performance that much.. but here I am learning structural designs and ways to build good coding habits and nice solutions. This would not be perfect by any mean)

  2. It makes me feel like I am breaking some fundamental principles of the "Command" pattern. (Even if not so, I'd like to think of a better way to solve this)

It is obvious that I cannot use the constructor of the concrete commands since HashMap returns already initialized objects. Next thing that comes to mind is using another method inside the object that "processes" (process(String[] args)) the arguments and sets private variables to the result of the parsing and this process(String[] args) method is called by the Producer class before doing queue() on the command, so the parsing would end up OUT of the Executor class (thread) and Point 1. from above would not be a problem.

But there's another problem.. What happens if a user enters a lot of commands to the application, the application does .get(args[0]) on the arguments and retrieves a PullCommand, it uses the process(String[] args) and private variables are set, so the command is queued to the Executor class and it is waiting to be executed. Meanwhile.. another command is input by the user, .get(args[0]) is used again, it retrieves a PullCommand from the HashMap (but that PullCommand is the same as the one that is queued for execution) and process() would be called BEFORE the command has been executed by the Executor class and it would screw up the private variables. We would end up with 2 PullCommands records in the BlockingQueue, second one would be correct from user point of view (since he input what he wants it to do and it does just that), but first one will be the same as the second one (since it is the same object) and it would not correspond to the initial arguments.

Another thing I thought of is using a Factory class that implements the parsing for each of the commands and returns the appropriate Command object. This would mean though, that I need to change the way HashMap is used and instead of Command I have to use the Factory class instead:

HashMap<String, CommandFactory> commands = new HashMap<String, CommandFactory>();
commands.put("pull", new CommandFactory("pull"));
commands.put("pull", new CommandFactory("push"));

and based on the String passed to the Factory, its process() method would use the appropriate parsing for that command and it would return the corresponding Command object, but this would mean that this class could potentially be very big because of containing the parsing for all commands..

Overall, this seems like my only option, but I am very hesistant since from structural point of view, I don't think I am solving this problem nicely. Is this a nice way to deal with this situation? Is there anything I am missing? Is there any way I can maybe refactor part of my code to ease it?

What is the best software architecture for coordinator Python app

I am currently building Python console/daemon smart home coordinator application to be run on Raspberry Pi, and would like to understand, what is now considered the right way to structure such apps.

Global requirements:

  1. App must coordinate several devices with cloud platform
  2. It should have internal DB (mainly for case when it's offline and cloud is not reachable), SQlite suits fine.
  3. It should be easily auto-tested (using virtual devices and maybe dev cloud environment), including integration tests to be run automatically without any human help.

Input/output streams:

  1. Inbound/outbound communications through serial port (with several devices of different types), e.g. get statuses of devices, post them to the cloud, and send commands back.
  2. Inbound/outbound communications through REST API in the cloud, e.g. send device statuses, receive commands to be passed to devices.

The app is not very complex, but contains a lot of logic and communications, and it's quickly becomes very challenging to keep all the interconnections in one's head.

My main concern now is should it be monolithic app with classes/functions that implement different parts of logic, or should it be several microservices (e.g. logic service, serial port service, cloud communication service) that run concurrently and communicate, let's say, by means of local message broker like RabbitMQ/ZeroMQ? Or maybe some other third way?

The microservices approach looks like an overkill (for example, my services will never be deployed independently), but some classes right now are a mess, so I wonder where you draw the line?

P.S. If you happen to know any resource/book/reference architecture which can help - please let me know!

Thanks!

Recursive callback to a virtual metod

I'm implementing the composite design pattern and I notice that I have many traversals with code duplication.

For example:

class Composite extends BaseComposite{

    LinkedList<BaseComposite> objs;

    public BaseComposite foo(int id){
        for(BaseComposite obj : objs){
            if(obj.getId() == id){
                return obj;
            }
            BaseComposite tmp = obj.foo(id);
            if(tmp != null){
                return tmp;
            }
        }

        return null;
    }

    public BaseComposite bar(int id){
        for(BaseComposite obj : objs){
            if(obj.getId() == id){
                return obj;
            }
            BaseComposite tmp = obj.bar(id);
            if(tmp != null){
                return tmp;
            }
        }

        return null;
    }
}

class Leaf extends BaseComposite{
    public BaseComposite foo(int id){
        if(this.id == id){
            return this;
        }
        return null;
    }

    public BaseComposite bar(int id){
        return null;
    }
}

Is there a way to prevent this code duplication in the Composite class?

use a method from class after factory class

I have a question.

I want use a method from a class, using its interface ( for istantiate it) after i have used a factory class.

Example:

public class UserBusiness{

    DAO_Interface DAO = DAO_Factory.getDAO("USER");

    public User Login(User user){
        User userx = DAO.LoginDAO(user);
        return userx;
        }

}

public class DAO_Factory {

    public static DAO_Interface getDAO(String type) {
        switch(type){

        case "USER" : {

            return new DAO_User();  

        }

public class DAO_User implements DAO_Interface{

    User userx;

    public DAO_User() { }


    public User LoginDAO(User user){
       // find data from Database 

        return userx;
    }

        @Override
    public Connection getConnetion() {
        // TODO Auto-generated method stub
        return null;
    }


}


public interface DataAccessObject {

    Connection getConnetion();

}

why don't work? i want use Interface only for method to connect every DAO(concrete) with database. Because i'm using many Entity class (as like as User), and only UserDao use a EntityClass User.

thanks a lot.

Circular dependency in the domain layer

In our domain model we have an Order and a Sending entities. They both have among others a ChangeStatus method which changes the status of order and sending respectively. Currently we have many handlers which uses those methods.

But now we need to introduce the behaviour at which changing the status of an Order to some specific value provokes changing of the status of an associated Sending and vise versa. When order is going to be canceled we should also cancel the sending (if any). And when the sending is delivered we should change the order status to "Completed".

Making Order and Sending dependent on each other leads to a circular dependency and bad design in general. Also we just can't instantiate objects which require each other as a dependency (even if they are dependent on interfaces).

My first thoughts were to create OrderStatusChanger and SendingStatusChanger interfaces (both dependent on Order and Sending) and delegate those tasks to them, but with this approach we have to modify every piece of code that changes statuses of orders and sendings to use these interfaces.

Another possible solution is to use pubsub as a workaround but it introduces other problems:

  1. How to cancel (rollback) changes if an error occurs in any of subscribers and the underlying system doesn't support transactions (such as redis)?
  2. It seems to me that event-based design in the domain layer is a bad idea. What is suitable for UI layer can lead to a poor maintability and unclear code in the domain.
  3. Mixing pubsub and classic dependency injection in one layer seems terrible too.

Order and Sending have many other methods and logic on their own, so we can't simply combine them into one entity.

Maybe there is an architecture design pattern or something I've missed completely?

Any help would be greatly appreciated

Why there is a need for creating AbstractFactory when there is Factory

What do we achieve by creating AbstractFactory when we already have Factory?

I mean by using Factory also we can directly create concrete objects than why should we use AbstractFactory and get Factory and than create object.

Interface definition for encapsulating a generic data source

I am currently working on a C# Plugin based design where the Plugin API methods will have access to a Context object which will contain the relevant information required for the method to work. In the current implementation, a file path is configured as one of the Context properties as it has to be supplied to one of the primary methods as it parses the file and loads an information hierarchy which other methods in the API will use. But the flexibility that is desired in the Context interface is to be able to accommodate a wide variety of data sources rather than only a file based data source e.g. at a later point of time, the data that is coming in the form of a file now, might be replaced by a DB based data source or a network stream, or a JSON data returned by a web service invoke. The current interface is as:

    public interface IFlowContext : IPluginContext
{
    string FlowFilePath { get; set; }
    string FlowImportFilePath { get; set; }
}

I am having a bit of difficulty in figuring out a sufficiently generic data source based interface definition to handle the desired flexibility.

Does anybody has any ideas?

Approach for saving UI entities

I have a complex object that consists of several other objects. Example:

public class Car {
   public string Name;
   public int iWheelID {get;set;};
   public int AccessoriesList {get;set;};
}

public class Wheel {
   public int iWheelID {get;set;}
   public int Color {get;set;}
   public int Radius {get;set;}
}

public class Accessory {
   public int iAccessoryID {get;set;}
   public int Type {get;set;}
}

All objects are mapped to appropriate tables in database and appropriate UI objects.

Frontend contains editor for several cars (we can change wheels or accessories, color of wheel, type of accesory etc.) and all edits are saved only after "Save" clicking.

Please, give me an advise about how I should save the state of one car to database. Because of delayed saving, i can't save to database each edit that user performs. That's why when user clicks 'Save' i should send the WHOLE model to server and perform edits in database.

The simplest way - delete old state and save new state. But i don't think it's an effective approach. Is there any pattern for my case?

I am using C# MVC + EF

Is this a correct implementation of an adapter pattern?

So I have two classes: SoccerPlayer and IceHockeyPlayer
They both have their own interface with some methods: ISoccerPlayer and IIceHockeyPlayer

SoccerPlayer:

public class SoccerPlayer implements ISoccerPlayer {

    public String[] teammembers;

    @Override
    public void kickFootball(int meters) {
        // Kick the football
    }

    @Override
    public void runForward(double speed) {
        // Run forward
    }

    @Override
    public void addTeammembers(String[] memberNames) {
        // Add the members
    }
}    

IceHockeyPlayer:

public class IceHockeyPlayer implements IIceHockeyPlayer {

    public ArrayList<String> teammembers;

    @Override
    public void hitPuck(int meters) {
        // Hit the puck
    }

    @Override
    public void skateForward(double speed) {
        // Skate forward
    }

    @Override
    public void addTeammembers(ArrayList<String> memberNames) {
        // Add the members
    }

}  

Next, I created a class which contains both a SoccerPlayer and an IceHockeyPlayer that implements both Interfaces, this would be my adapter.
The methods in this class just call the correct methods of either SoccerPlayer or IceHockeyPlayer:

public class Adapter implements ISoccerPlayer, IIceHockeyPlayer {

    public SoccerPlayer soccerplayer;
    public IceHockeyPlayer icehockeyplayer;

    public Adapter(SoccerPlayer soccerplayer, IceHockeyPlayer icehockeyplayer) {
        this.soccerplayer = soccerplayer;
        this.icehockeyplayer = icehockeyplayer;
    }

    // SoccerPlayer
    @Override
    public void kickFootball(int meters) {
        this.soccerplayer.kickFootball(meters);
    }

    @Override
    public void runForward(double speed) {
        this.soccerplayer.runForward(speed);
    }

    @Override
    public void addTeammembers(String[] memberNames) {
        this.soccerplayer.addTeammembers(memberNames);
    }

    // IceHockeyPlayer
    @Override
    public void hitPuck(int meters) {
        this.icehockeyplayer.hitPuck(meters);
    }

    @Override
    public void skateForward(double speed) {
        this.icehockeyplayer.skateForward(speed);
    }

    @Override
    public void addTeammembers(ArrayList<String> memberNames) {
        this.icehockeyplayer.addTeammembers(memberNames);
    }

}  

Is this a correct implementation of an adapter pattern? If no, what would I need to change to make it one?

Typescript : force classes to implement singleton pattern

Is there any way in forcing a class to implement singleton pattern in typescript. If so how ca i achieve this ?

So this is my interface and I would like that every class that implements it to be forced in implementing singleton

export interface ICorporationWebsitesService extends ISubject{
   readonly Instance: ICorporationWebsitesService;
}

export class CorporationWebsitesService implements ICorporationWebsitesService {

    private _instance: ICorporationWebsitesService;
    public get Instance(): ICorporationWebsitesService {
        if (this._instance === null) {
            this._instance = new CorporationWebsitesService();
        }
        return this._instance;
    }


    private constructor() {
    }
}

of course, i had to add the private constructor myself, but if someone else would like to implement this interface he/she is not required or noticed that the constructor should be made private.

Thank you.

Strategy pattern with return value

I try create Payment by strategy pattern. But All articles each I read look like this:

public interface PayStrategy {
    void pay(BigDecimal paymentAmount);
}

But if I need return Single<RestResponse<PaymentResponse>>?Is this the right approach?

public interface PayStrategy {
        Single<RestResponse<PaymentResponse>> pay(BigDecimal paymentAmount);
    }

Command Pattern in client-server context

I am trying to develop a client-server application. I want to integrate a Command-Pattern but i have never seen an example. My client have to loggin to the server then it requests some kinds of data like all the students stored in the database. Can someone show me an example(i mean code) in java of a Command-Pattern used in a client-server context? Who is the client, the invoker and reciver in this context? An example of how serializzation and deserializzaation of Commands works? How should my server answer to the client's requests?

inheritance and custom logic in DTOs

As I know, aim of DTOs usage is to keep plain object for transport data. Could you provide some argument for or against usage of inheritance and custom logic in DTOs. It makes code difficult to read this is what I found as disadvantage. On other hand it may reduce some code duplication.

mardi 27 février 2018

How to handle Facade in feature by package structure

How can I structure my project if I have a facade?

The controller will call the facade to call the class in another package and the self package?

Like:

feature/
├── order/
│   ├── OrderController <== here calls Facade
│   ├── OrderService
└── facade/
│   ├── CheckoutFacade <== here calls orderService(go to facade and back to self package) and personService 
└── person/
    └── PersonService

Should I create a controller package separately of feature?

Making an existing feature code (java) more scalable to allow external teams to easily introduce code changes independently

We are working on a feature coded by another team for a web application in java. We need to override the default logic when certain case is applicable. The partner team needs a way/ design that allows any external team like us to be able to modify the feature (if approved feature cr) with some config changes or bean creation and using when applicable to make the code more scalable. Is there a way to achieve the same?

what are the use of Handler? [on hold]

Suppose we have a function named "GetAllProducts".for calling this function first we create some interface and then we invoke it. we can directly call any function also, so what are the uses of Handler?

Elegant way of encapsulating behaviour that depends on the combination of involved objects?

In want to check whether two items collide in space. For that purpose both items are represented by some simplified geometric shapes - for simplicity lets assume these shapes can only be circles, polygons and lines. The items can be represented by any of these shapes and the collision-detection needs to be able to handle any of the possible combinations. I want to find a strategy that involves minimal code duplication and allows adding further shapes in the future.

My approach is the following:

public class Item{

   private Collidable bounds;

   public boolean checkCollision(Item target){
       return bounds.checkCollision(target.getBounds());
   }
}

Where Collidable is the interface for any geometric shape and a possible shape would look like:

public class Circle implements Collidable{

   public boolean checkCollision(Collidable target){
      if(target instanceof Cirlce){
         //Algorithm for circle-circle collision
      }else if(target instanceof Line){
         //Algorithm for circle-line collision
         //...
      }else{
         return false;
      }
   }
}

This however yields a lot of code duplication (the same circle-line collision algorithm would need to be repeated in the Line class) and does not seem elegant. I looked into different design patterns in search of a solution, but only ended up with this strategy-like solution. What would be a better approach here?

Neo4j find repeating pattern starting from node

I' currently working with neo4j and try to construct a cypher query which suits my use case. I have a graph with the following structure

(NODE_A)-RELATION_A->(NODE_B)-RELATION_B->(NODE_A)-RELATION_A-> ... repeat ...

I know the first NODE_A and want each subsequent NODE_A and NODE_B which match the two Relations (RELATION_A and RELATION_B). If Í construct a cypher query it looks like this

MATCH (a:NODE_A)-[:RELATION_A]->(b:NODE_B)-[:RELATION_B]-(c:NODE_A) WHERE id(a)=1 RETURN [a,b,c] as result

But this only returns as result the pattern NODE_A-RELATION_A->NODE_B-RELATION_B->NODE_A

If I leave out the "WHERE id(a) = 1" it get the correct result, but then it returns all nodes that match the pattern.

How do I specify a start node from which the query to execute from?

iOS Design Pattern for Setting Page

Recently, I am going to create a setting page for my app. My design is using one singleton object to link up with different setting object, like language setting, notification setting, etc., Here is my code:

class AppSettings{

  static let settings = AppSettings()
  let langSetting
  let notificationSetting

  private init(){
    langSetting = new LangSetting()
    notificationSetting = new NotificationSetting()
  }
  public getSettings() -> AppSettings{
     return settings
  }
}

However, the above code violated "open for extend, close for modification" principle. And also violated "depend on abstractions not on concrete implementations". But how to modify it to fulfil those principle?

Another problem is that, if I want to change the language, I need to write some code like this:

AppSettings.getSettings().langSetting.set("en")

Is it to long for the others to use this API?

Which design pattern to use for long running operations

I would like to know which design pattern is better to use for winform or console applications that runs long operations, Obviously, that updates the UI during the process. I saw the MVP but it executes the methods sincronusly

Mediator Pattern VS Facade Pattern

I am in a middle of task to revamp a PHP System, however there are too many classes communications, so I searched for a pattern to solve such problem, and I found that Mediator pattern aims to solve a complex objects communications also Facade may help by reducing redundant code and calls, so which one should I consider?

Thank you,

Caching Strategy/Design Pattern for complex queries

We have an existing API with a very simple cache-hit/cache-miss system using Redis. It supports being searched by Key. So a query that translates to the following is easily cached based on it's primary key.

SELECT * FROM [Entities] WHERE PrimaryKeyCol = @p1

Any subsequent requests can lookup the entity in REDIS by it's primary key or fail back to the database, and then populate the cache with that result.

We're in the process of building a new API that will allow searches by a lot more params, will return multiple entries in the results, and will be under fairly high request volume (enough so that it will impact our existing DTU utilization in SQL Azure).

Queries will be searchable by several other terms, Multiple PKs in one search, various other FK lookup columns, LIKE/CONTAINS statements on text etc...

In this scenario, are there any design patterns, or cache strategies that we could consider. Redis doesn't seem to lend itself particularly well to these type of queries. I'm considering simply hashing the query params, and then cache that hash as the key, and the entire result set as the value.

But this feels like a bit of a naive approach given the key-value nature of Redis, and the fact that one entity might be contained within multiple result sets under multiple query hashes.

(For reference, the source of this data is currently SQL Azure, we're using Azure's hosted Redis service. We're also looking at alternative approaches to hitting the DB incl. denormalizing the data, ETLing the data to CosmosDB, hosting the data in Azure Search but there's other implications for doing these including Implementation time, "freshness" of data etc...)

How to architect a Java Enterprise application?

I am given a task of Revamping a Commodity Sourcing project written by previous programmers.

The problem is the old guys didn't follow any Rules of Software Architecture, OOP or simple Naming convention. E.G

1-Single POJO is defined which serves both as Session bean and entity bean, which lead to a complex structure and duplicate code everywhere.

2-There is no N-Tier Architecture followed, which leads to almost unreadable code and over 5K lines of code in one class.

3-No Design Patterns of any sorts is practiced

Currently, we AngularJS is used on Front-End, and SparkJava(Not Apache Spark) in the Back-End. Following is what is Current Architecture (sort of)

I know very Basic

Since I have to start from the ground up. Can Anyone refer to a good resource on how I can design application that follows strict architecture rules and conventions.

lundi 26 février 2018

Building architecture on top of abstraction

I am developing a .NET Core Web API project and experiencing the following issue:

I have a simple domain of one base class and three derived classes. For simplicity let me name them in the following manner - Design1, Design2, Design3 and the abstract class Design

public abstract class Design { }
public class Design1 : Design { }
public class Design2 : Design { }
public class Design3 : Design { }

I have created repositories for every class except the abstract one and now I am trying to figure out how to structure my business logic and the controllers. But first let me go a bit deeper in the structure of the application

The data from the client is sent in a data transfer object. Let me call it DesignDTO. There, I have a property named type which has the value of either Design1, Design2 or Design3

public class DesignDto{
    // some other properties
    public string type; //has value of Design1, Design2 or Design3
}

This object is sent to the Post method of the design controller and here is the tricky part. The DesignDTO should be mapped to one of the derived objects. I do this with a factory method depending on the value of the type property. Then, I do the same when I call the business logic class - the business logic classes of all derived classes share the same IDesignLogic interface.

public class Design1Logic : IDesignLogic{
    public void add(Design design){
        // some logic
    }
}

public class Design2Logic : IDesignLogic{
    public void add(Design design){
        // some logic
    }
}

So my question is if this is a proper manner of structuring the application?

I've considered creating one business logic class - DesignLogic that will be responsible for all the logic in the derived classes. Later decided it will become complicated and I will still have to do the factory when calling the repositories.

My other though was creating controllers for every derived class, then separate business logic and repository, but this way the point of the abstraction will be lost and scalability of the application will be 0.

What are your thoughts about this issue? I am glad to hear more about it.

C# design pattern when you find yourself in need of events to be executed in specific order

I'm making a game in C# where two different classes are notified via events when the player moves.

One of those classes is the RenderGrid, as soon as the player moves the RenderGrid will instantiate only the new game tiles now visible on screen. It also contains two vectors describing the bottomLeft and topRight corners of the grid that is currently being rendered

The other is the WorldManager class, which as soon as the player moves, will check if there's the need to load and create new chunks of the game world. To do so, it needs to check the corners of the RenderGrid to ensure they're still inside the boundaries of already loaded chunks.

And here is the problem, since WorldManager depends on the event being handled first on RenderGrid and then on WorldManager thus breaking the event pattern

In pseudo-code, here's RenderGrid:

public class RenderGrid {

    public Vector2 bottomLeft;
    public Vector2 topRight;

    public RenderGrid() {
        Player.onPlayerMoved += playerMoved;
    }
    ~RenderGrid() {
        Player.onPlayerMoved -= playerMoved;
    }

    private void playerMoved(Vector2 delta, Vector2 position) {
        // updates the bottomLeft and topRight corners
    }
}

And WorldGrid:

public class WorldGrid {
    public WorldGrid() {
        Player.onPlayerMoved += playerMoved;
    }

    ~WorldGrid() {
        Player.onPlayerMoved -= playerMoved;
    }

    private void playerMoved(Vector2 delta, Vector2 position) {
        // it needs the corners of the renderGrid, but since those are also updated when player moves, we can't be sure
        // wheter they've been updated here or not
    }
}

Using a separate event to notify that the RenderGrid corners have been updated and listening to it seems like sure spaghetti and I'm not sure how to proceed from here

Any structure interface

Please, give me some clues concerning this matter. Thank you in advance and sorry if my explanation seems a bit confusing.

Suppose I have some struct

struct Some
{
  DataTypeA a;
  DataTypeB b;
  ...etc.
};

and I have this interface:

class AnyStruct
{
public:
  using Variant = boost::variant<boost::blank, DataTypeA, DataTypeB, ...etc.>;
  using StringArr = std::vector<std::string>;

  virtual StringArr fieldNames() = 0;
  virtual Variant getValue(const std::string & fieldName) = 0;
};

Futher I want to implement this interface to have possibility to access Some fields using string names like this:

class SomeStruct : public AnyStruct
{
  Some m_some;

public:
  SomeStruct(const Some & some);

  /**
   * Function fieldNames returns vector {"a", "b", ...etc.}. Please, see the Some 
   * structure definition above.
   */
  virtual StringArr fieldNames();

  /**
   * 1. Function getValue with parameter "a" returns m_some.a wrapped in boost::variant
   * 2. Function getValue with parameter "b" returns m_some.b wrapped in boost::variant
   * ...etc.
   */
  virtual Variant getValue(const std::string & fieldName);
};

May be there is a some elegant solution or design pattern for this case? I will be very grateful for any advices.

Design pattern for memory allocation design for object creation

In this previous question I wondered how to decide size for objects. Now to another somewhat similar question. What if I have a solution to create objects in my own little memory play-area. What kind of object oriented design patterns do there exist to decide object size prior to construction?

The point would be two-fold:

  1. to try and make a single external allocation per construction, saving time and memory/pointer management overhead.
  2. by a single allocation we get locality in memory for each object which is nice for cache hitting purposes.

Is there some clever way to pair constructor argument list to for example static functions returning int? Maybe something factory-like?

What is actually the Domain Model in Ports and Adapters architecture?

As I was reading a lot lately regarding the Ports and Adapters architecture, I stumbled upon this piece of code as a part of an application that was build following the above mentioned architecture :

package com.example.user.management;

import lombok.*;

import javax.persistence.*;
import java.io.Serializable;

@Table(name = "user")
@AllArgsConstructor
@Data
@NoArgsConstructor
@javax.persistence.Entity
@Setter
@Getter
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class User implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    private Long id;

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;

    @Column(name = "role")
    private String role;

    public User(String username, String password, String role) {
        this.username = username;
        this.password = password;
        this.role = role;
    }

}

As the main intent of the Ports and Adapters architecture is to separate and isolate the domain layer from any technical details and implementations, and having in mind that this User entity is in fact, the domain layer, doesn't it contain dependency to the java persistence library? As I understand it, the domain layer is responsible only for implementing the use-cases. I am really confused as per what should actually be the Domain Layer in this type of architecture.

Adapter pattern without passing class object as parameter

I have a really simple question. There are examples of adapter pattern on internet and in every one of them adapter class get object of class that needs to be adapted as parameter. Something like this:

class Adapter {
    private SomeClass someClass;

    public Adapter(SomeCLass someClass){
        this.someClass = someClass;
    }

    public adaptMethod(){
        ...
    }
}

If I do something like this:

class Adapter {
    private SomeClass someClass;

    public Adapter(){
        this.someClass = new SomeClass();
    }

    public adaptMethod(){
        ...
    }
}

Would this still be an adapter pattern?

Design patterns for python flask(Portfolio)

I have my python flask web application code for implementing a portfolio website. Can anyone suggest me the sources or useful links for implementation of design patterns in flask web application as part of code refactoring. I could not find any source which gives this implementation.

Thanks. Appreciate your help.

Class implements interfaces should only implements functions defined in interface?

working on design, does this is kind of clean design if concrete class only define/implement the functions that are defined in interfaces ? or the class can implement more function ?

dimanche 25 février 2018

How to share data across multiple instances with a common parent?

I have the following code

//parent class
class Parent {
 private Object data;
 Parent (Object data){
  this.data=data;
 }
 method1(){}
 ...
 methodN(){}
}
//wrapper class
class Wrapper extends Parent {
 Wrapper(Object object){
   super(object)
  }
 class Son1{
  //do something
 }
 class SonN {
  //do something
 }
}

Parent has useful methods for their sons, the wrapper is meant to create only one instance of the Parent in order to give access to the inner classes the Parent's methods and data

All works fine, however, the wrapper became huge due to all the sons.

I'm figuring out how to move each son to its own class (In a separate file) without impact the existing code

what I did so far is to make each son to extend directly from Parent and passing the data to the parent through the constructor

class SonN extends Parent{
  SonN(Object object){
  super(object)
  }
}

it works, but I see a downside, each check that gets created will have its own instance of Parent

I'm not really worried about the extra memory used, I think it won't make any notorious difference in the software but I have some questions

  • Is there a design pattern for this cases?

  • If the number of sons will continue growing up, would it be better to remain with the original design?

  • is there a better way to share the methods to the sons keeping the memory used low?

Note

there are multiple instances of wrapper at the same time pointing to different objects what limits the usage of static variables

Page not found 404 URL config

I keep getting the following error in my terminal (while running server) when I try to look at the home page. "GET / HTTP/1.1" 404 2028

here is the code that I have for mapping URLS:

urls.py (main):

   from django.urls import path
from django.contrib import admin
from django.urls import include


urlpatterns = [
    path('admin/', admin.site.urls),
    path(r' ', include('learning_logs.urls', namespace='learning_logs')),
]

urls.py(in learning_logs folder)

    """Define URL pattersn for learning_logs."""

from django.conf.urls import url
from . import views

app_name = 'learning_logs'

urlpatterns = [
    # Home page
    url(r'^$', views.index, name='index'),
]

views.py:

   from django.shortcuts import render


def index(request):
    """The home page for learning log"""
    return render(request, 'learning_logs/index.html')
# Create your views here.

index.html:

    <!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <p>Learning Log</p>
    <p>Learning log helps you keep track of your learning, for any topic you're learning about.</p>
  </body>
</html>

this is the error I'm getting on the home page:

Using the URLconf defined in learning_log.urls, Django tried these URL patterns, in this order: admin/

Thanks for the help in advance.

Java Where should i create eventHandlers?

Lets imagine i have relative big program, where should i write the eventHandlers bodys?

Imagine the following scenario:

public class MyClass extends OtherClass{

    private int a;
    private Object x;

    public MyClass(){
        super();

        //Adding EventHandlers
        addEventFilter( MouseEvent.MOUSE_PRESSED, getOnMousePressedEventHandler());
        addEventFilter( MouseEvent.MOUSE_RELEASED, getOnMouseDraggedEventHandler());
    }

    //Event Handler Body
    EventHandler<MouseEvent> getOnMousePressedEventHandler() {
        return onMousePressedEventHandler;
    }
    EventHandler<MouseEvent> getOnMouseDraggedEventHandler() {
        return onMouseDraggedEventHandler;
    }
    private EventHandler<MouseEvent> onMousePressedEventHandler = event -> {
        //Do something
    };
    private EventHandler<MouseEvent> onMouseDraggedEventHandler = event -> {};
}

I was thinking to bring the Event Handler Body to other class or a abstract class, however there is a few variables like x that are needed on the event handlers. So is there a correct way for doing what i want? I have a few options but all of them sound terrible and create a class like private MyClassEventHandler handler and do MyClassEventHandler = new MyClassEventHandler() on the construtor looks very bad.

Exchange Data Between multiple sources

I want to build a java microservice to synchronize data between a java application and external sources such as Office365 ,Gsuite ,CSV files.Is there any pattern or strategy to build it.

The expressiveness of fold(r)?

I am working of kind of blog-post/paper regarding fold. Mostly I stick to fold : (a -> b -> b) -> b -> [a] -> b signature, however fold-left might work as well.

What I need is as many examples as possible, where fold used to implement well-known and commonly used bits like:

sum = foldr (+) 0

product = foldr (*) 1

any = foldr (||) False

all = foldr (&&) True

(++ ys) = foldr (:) ys

length = foldr (\_ n -> n + 1) 0

reverse = foldr (\x xs -> xs ++ [x]) []

map f = foldr (\x xs -> f x : xs) []

filter p = foldr (\x xs -> if p x then x : xs else xs) []

All the examples above are written and tested in Haskell, however I can accept any language, including OO-ones.

Thanks in advance.

Promise versus TypeError for input parameters

What are the cons and pros of implementing a promise function/method in the following way? -

Return a promise only if all input parameters pass validation. Otherwise, throw TypeError.


I used both of the following approaches in the past...

  • Simply throwing an error: throw new TypeError('Argument "bla-bla" is invalid...')
  • Returning a rejection: return Promise.reject(new TypeError('Argument "bla-bla" is invalid...'))

Now I am refactoring a library for that, to make it more consistent, and want to know the good/bad sides of either approaches first.

Separating write function from calculation (design)

I am currently in refactoring my code. I try to use more OOP features instead of using one large main function. Though I struggle with using the right approach to separate the calculation from writing the file. I want to use the write(...) routine as an interface, so I can swap out the ParallelWriter with, say NullWriter. Is using a template in an interface a right choice?

Since the writing is actually not very much, I don't want it to stand in the way of the calculation. So enqueue_write actually just blocks for a moment and buffers the data. In any case, both ParallelWriter and Calc have to know about struct d, right? So if for example Calc is using some OpenCL which is placed inside struct d, I have to include the same header files in both compilation units?

From a design perspective, is using a pointer to Writer is the right approach? I mean, its non-owning, and has to be flexible. Or should Calc own the writer because it has to know about the datastructure struct d?

Note: I use struct to keep the code a bit shorter. Also, I do not know a lot about programming design principles.

struct d {cl_uint x;};
template <class T> struct Writer {
  virtual ~Writer() {}
  virtual void enqueue_write(T &data) = 0;
  virtual void close() = 0;
};
struct ParallelWriter : public Writer<std::unique_ptr<struct d>> {
  void enqueue_write(std::unique_ptr<struct d> &data) override {
    std::cout << "move into internal buffer, gets written somewhen. "
                 "Calculation can continue\n";
  }
  void close() override { /* ... */ }
};
struct Calc {
  Calc(Writer<std::unique_ptr<struct d>> *writer) { m_writer = writer; }
  void run(int param) {
    std::cout << "allocate struct s, work on it w/ param, send to writer\n";
    auto data = std::make_unique<struct d>();
    data->x = static_cast<cl_uint>(2 * param);
    m_writer->enqueue_write(data);
  }
  void stop() {}
  Writer<std::unique_ptr<struct d>> *m_writer = nullptr;
};
int main() {
  auto writer = ParallelWriter{/*filename*/};
  auto calculation_object = Calc{&writer /*, options */};
  calculation_object.run(42);
  calculation_object.stop();
  writer.close();
}

Cheers, Jonas

Implementing UnitOfWork with Service and Repository layers in a MVC 5 application with Entity Framework

Could you please help me with some guidance in implementing the Unit of work pattern with the service and repository layer. The application is using the EF ORM.

Currently, I have the service and repository layers implemented, however, I need to adapt the application architecture and implement the Unit of Work layer in order to support atomic operations from multiple service classes.

I don't know how exactly the Unit of Work layer should be implemented, who will have the responsibility of instantiating it and who should commit the changes ?

In my mind, I'm thinking of instantiating an unit of work in the controller and control all the actions through its reference. The unit of work object will contain all references (interfaces) to all of the service classes. Would this be a good approach ?

Regards

Design Patterns - when to use Visitor?

On what kind of scenarios should I use the Visitor design pattern? I understand it is fairly rare one should be using it

Externally lock Cache for updates

I have 2 caches which are updated individually form various parts of my code. Every some time (e.g. 12 hours) I want to make sure they are synced. An external class is responsible for starting and executing this task. How can I make sure other classes are not working with the caches when this happens?

My thinking is using some ReadWriteLock in each cache and exposing lock/unlock methods.

Class Cache {
  private final ReadWriteLock lock = new ReentrantReadWriteLock();

  public void put(String id, Object object) {
    lock.readLock().lock();
    try {
      // put in cache
    } finally {
      lock.readLock().unlock();
    }
  }

  public Object get(String id) {
  lock.readLock().lock();
    try {
      // get from cache
    } finally {
      lock.readLock().unlock();
    }
  }

  public void lock() {
    lock.writeLock().lock();
  }

  public void unlock() {
    lock.writeLock().unlock();
  }
}

And this is the code for the sync class

Class Synchronizer {
  Cache cache1 = new Cache();
  Cache cache2 = new Cache();

  public void syncCaches() {
    cache1.lock();
    cache2.lock();

    try {
      // do sync
    } finally {
      cache1.unlock();
      cache2.unlock();
    }
  }
}

This works, but I think it's a misuse of the Read/Write lock architecture and I couldn't find libraries or something else what might work.

Any ideas are welcome!

samedi 24 février 2018

Is the decorator pattern the correct pattern to be used on this situation

I would like to ask if the decorator pattern suits my needs and is another way to make my software design much better?

Previously I have a device which is always on all the time. On the code below, that is the Device class. Now, to conserve some battery life, I need to turn it off then On again. I created a DeviceWithOnOffDecorator class. I used decorator pattern which I think helped a lot in avoiding modifications on the Device class. But having On and Off on every operation, I feel that the code doesn't conform to DRY principle.

namespace Decorator
{
    interface IDevice
    {
        byte[] GetData();
        void SendData();
    }


    class Device : IDevice
    {
        public byte[] GetData() {return new byte[] {1,2,3 }; }
        public void SendData() {Console.WriteLine("Sending Data"); }
    }


    // new requirement, the device needs to be turned on and turned off
    // after each operation to save some Battery Power
    class DeviceWithOnOffDecorator:IDevice
    {
        IDevice mIdevice;

        public DeviceWithOnOffDecorator(IDevice d)
        {
            this.mIdevice = d;
            Off();
        }

        void Off() { Console.WriteLine("Off");}
        void On() { Console.WriteLine("On"); }

        public byte[] GetData()
        {
            On();
            var b = mIdevice.GetData();
            Off();
            return b;
        }


        public void SendData()
        {
            On();
            mIdevice.SendData();
            Off();
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Device device = new Device();
            DeviceWithOnOffDecorator devicewithOnOff = new DeviceWithOnOffDecorator(device);
            IDevice iDevice = devicewithOnOff;

            var data = iDevice.GetData();
            iDevice.SendData();
        }
    }
}

On this example: I just have two operations only GetData and SendData, but on the actual software there are lots of operations involved and I need to do enclose each operations with On and Off,

void AnotherOperation1()
{
On();
// do all stuffs here
Off();
}

byte AnotherOperation2()
{
On();
byte b;
// do all stuffs here
Off();
return b;
}

I feel that enclosing each function with On and Off is repetitive and is there a way to improve this?

How to avoid loading duplicate objects into main memory?

Suppose I am using SQL and I have two tables. One is Company, the other is Employee. Naturally, the employee table has a foreign key referencing the company he or she works for.

When I am using this data set in my code, I'd like to know what company each employee works for. The best solution I've thought of it to add an instance variable to my Employee class called Company (of type Company). This variable may be lazy-loaded, or populated manually.

The problem is that many employees work for the same company, and so each employee would end up storing a completely identical copy of the Company object, unnecessarily. This could be a big issue if something about the Company needs to be updated. Also, the Company object would naturally store a list of its employees, therefore I could also run into the problem of having an infinite circular reference.

What should I be doing differently? It seems object oriented design doesn't work very well with relational data.

This is more of a design/principles sort of question, I do not have any specific code, I am just looking for a step in the right direction!

Let me know if you have any questions.

Micro-job platform - matching orders with nearest worker


I am currently planning to develop a micro-job platform to match maintenance workers (plumbers, electricians, carpenter, etc) with users in need through geolocation. Bookings can be made well in advance or last minute (minimum 1h before) at the same fare.

Now, I am struggling to find a suited matching algorithm to efficiently assign bookings to available workers. The matcher is basically a listener catching "NewBooking" events, which are fired on a regular basis until a worker is assigned to the specific booking. Workers can accept or decline the job and can choose working hours with a simple toggle button (when it's off they will not receive any request). On overall the order is assigned within a certain km range.

The first system I thought of is based on concentric zones, whose radius is incremented every time the event is fired (not indefinitely). All workers online within the area will be notified and the first to accept gets the job.

Pros:

  • more opportunities to match last minute bookings;

Cons:

  • workers may get a lot of notifications;
  • the backend processing several push & mail messages;

1st algorithm

A second solution is based on linear distance, assigning the work to the nearest available worker and, if (s)he does not accept it within a certain timeframe (like 30'), the algorithm goes to the next available person and so on.

Pros:

  • less processing power;
  • scalability with lots of workers and requests;

Cons:

  • less chances to match last minute orders;

2nd algorithm

Third alternative is to use the first approach sending orders in multiple batches according to feedback ratings; the first group to receive the notification is made out of those with 4+ stars, then 3+ avg. of votes and so on.

I was wondering if there is a best practice when it comes to this kind of matching algorithms since even taxi apps face these issues. Anyway, which approach would you suggest (If any), or do you have any proposal on possible improvements? Thank you

Konvajs and similar design pattern(s) in TypeScript

I hva been examining the source code of konvajs (https://github.com/konvajs/konva) and i am fascinated by the design pattern, eg. src/shape.js (https://github.com/konvajs/konva/blob/master/src/Shape.js):

    Konva.Shape = function(config) {
      this.__init(config);
    };

    Konva.Util.addMethods(Konva.Shape, {
    __init: function(config) {
    this.nodeType = 'Shape';
    \\ more code

Here it seems that the constructor of the class Shape passes the argument 'config' to the __init method not declared yet. Also the __init method is added to the class by the Util method addMethods. To me this seems like a flexible way of coding, that is if you want to add some new feature a utility class handles it for you.

Moreover, the default values for defining attributes is added by a factory class (eg. see the bottom part of shape.js).

So my question is:

Is it possible to implement a similar design pattern in typescript? Or is this design pattern not applicable in OOP-languages (or what ever typescript is).

Removing Spam Posts

I have hit a roadblock here. I have posts table in my database and a spam table which basically stores if the users mark the posts as spam or inappropriate content. And I know how to write an algorithm to remove but there's a problem with how I think I can do this. If I include or check inappropriate content in Laravel when user logs in then It would run multiple times with each user and I don't want that which is how I thought I could code.
Another way is to check when displaying posts. If I do that on the controller it won't solve anything as it runs with each user and is not a viable option. So how can I implement this? And what does this type of things are called for lack of technical terms I can't say exactly what this type of problem is called.

vendredi 23 février 2018

Testing how fast new is on my computer, using it to allocate an array of doubles, ten thousand times?

I am having trouble doing this, I am new to C++, this is from the Joshi design and patterns book. So I would assume that I would need to make an array ten thousand times and test how fast it took, and then use new to make a dynamic set of arrays, ten thousand and then time it again. But I am confused on how to make ten thousand arrays, or run the program ten thousand times? So far this is the code I have written:

#include <stdio.h>
#include <ctime>
#include <iostream>
using namespace std;

int main()
{

    long start = clock();
    int size;
    cout << "\nEnter size of array\n";
    cin >> size;


//    double array[size];
//    for(int i=0; i<size ; i++) {
//        array[i] = rand() % 10000000;
//    }

    double *dynamicArray = new double[size];
    for(int i=0; i<size ; i++) {
        dynamicArray[i] = rand() % 10000000;
    }


    long end = clock();

    cout << "it took " << ((float)end-start)/CLOCKS_PER_SEC << " seconds." << endl;


}

Write a program to print the following output in java [on hold]

Write a program to print the following output in java Enter 3 Output: 333 313 323 333

Enter 5, Output: 55555 55155 55255 55355 55455 55555

Groovy Regex: String Split pattern not returning same result as Matcher pattern

I'm trying to extract the data between a starting and ending markers in a string. There are multiple matches and I need to extract all the matches (into an array or list doesn't matter)

I have a limitation and cannot use Regex Matcher on my setup so as an alternative I'm looking at using string.split() with a regex.

This pattern works with Regex Matcher and extracts all the matches between the starting and ending marker.

def items = str =~ /(?s)(?<=START:M).*?(?=END:M)/

However, when I try to use the same pattern on string.split

def items = str.split(/(?s)(?<=START:M).*?(?=END:M)/)

it returns the end and start markers themselves for each match instead of what's between them.

e.g. [ "END:M START:M", "END:M START:M", "END:M START:M" ... ]

What am I missing, why isn't the Split pattern returning the same groups as Matcher pattern?

Using Template Method design pattern in JSF 2.x web application

I'm working with a JSF 2.x web application, where we need to support multiple versions of a web form. We now have 2 versions of the form -- form 1 being the original form, and Form 2 having a few new elements and rearranged elements.

My issue is this. In some of the backing beans (which are ManagedBeans), some routines need to do different things based on the Form Number. For instance:

@ManagedBean(name="projectInfoBean")
@SessionScoped
class ProjectInfoBean {
    private int hasFlagChanged() {
        if(formVersion == 1)
            return hasFlagChanged_form1();
        else
            return hasFlagChanged_form2();
   }
}

where hasFlagChanged_form1() and hasFlagChanged_form2() are two similar but different algorithms. hasFlagChanged() is called as part of a Save routine.

Now, we're already considering more changes in the form, so we'd have a new Form Version 3.

Is there a better way to do this kind of thing? Other than a giant if-statement. I was wondering about using the Template Method design pattern, or perhaps Strategy pattern, since the algorithms vary based on the Form Version Number.

What confuses me is how to use design patterns like Template Method, within a JSF ManagedBean like the above example?

What other suggestions might people have?

Thanks

Chris

Patterns to segregate Models and DbContext on ASP.NET Core microservices

I'm trying to make my services to deploy individually without depending on each other.

All services will be using the same SQL database using EF Core (same DbContext).

I'm using a separate project (MyServices.Data) that has all my models and the DbContext, but I'm really dependent on this and if there is any change on this Data project, all services needs to be redeployed.

Is there any pattern/approach to this situation so I can have my project not dependant on it?

Startegy Design Pattern

Hello I'm trying to implement Strategy Design Pattern but I'm getting a null pointer exception in the main method

This is my Interface Course

public interface Course {


    public String courseName();

}



And These are my Implementation Classes

public class JavaCourse implements Course{

    @Override
    public String courseName() {
        return "Java Course is completed and job is ready";
    }

}



public class Python implements Course{

    @Override
    public String courseName() {
        return "Python course is completed Job is ready";
    }

}



This is my Factory class

public class CourseFactory {

    public static JobSeeker getInstance(String course){
        Course cou= null;
        JobSeeker js= null;
        if(course.equals("java")){
            cou= new JavaCourse();
            js= new JobSeeker();
            js.setCourse(cou);
            System.out.println("JAAAAAVAAAVAVAVAVAVAVA");
        }else if(course.equals(".net")){
            cou= new DotNet();
            js= new JobSeeker();
            js.setCourse(cou);
        }else if(course.equals("python")){
            cou= new Python();
            js= new JobSeeker();
            js.setCourse(cou);
        }
       return null; 
    }
}



This is the Service class

public class JobSeeker {
    private Course course;

    public void setCourse(Course course){
        this.course= course;
    }

    public String getJob(String company){
        String status = null;
        status= course.courseName();
        return "Since "+status+" for the Company "+company;
    }
}



This is the Main Class

public class Test {
    public static void main(String[] args){
        //CourseFactory cf= new CourseFactory();

        JobSeeker js= new JobSeeker();
        js= CourseFactory.getInstance("java");
        System.out.println("----------");
        System.out.println(js.getJob("IBM"));
    }
}


I'm getting Null Pointer Exception when I'm calling js.getJob("IBM")
I'm expecting output like:::
Since Java Course Is completed job is ready for the company IBM

Instruct constructor method to use default value if null

I'm designing an API wrapper with a constructor something like this:

public class Client(string username, string password, int timeout = 60)

The caller looks like this:

class Program 
{
    private static int? Timeout => GetFromConfig("Timeout");

    static void Main(string[] args)
    {
        Client client = new Client(Username, Password, Timeout);
        // do things...
    }
}

I would like to use Client's default timeout (60) if Timeout is null.

I know of a few options:

1) Use conditional logic in Main

static void Main(string[] args)
{
    if (Timeout == null) 
    {
        Client client = new Client(Username, Password);
    }
    else 
    {
        Client client = new Client(Username, Password, Timeout);
    }
}

I dislike this solution because 1) it's a lot of code, and 2) the code grows exponentially as I add conditional parameters (e.g. if I added int MaxFailedRequests = 5 to Client()'s signature, my if/else block grows to 4 blocks).

2) Handle null values in Client()

public class Client(string username, string password, int? timeout) 
{
    _timeout = timeout ?? 60;
}

I dislike this solution, because the default value is no longer exposed in the constructor's signature (which acts as excellent/free documentation).

3) Handle null values in Client() with a default value

public class Client(string username, string password, int? timeout = 60) 
{
    _timeout = timeout ?? 60;
}

I dislike this solution because 1) it's not immediately obvious how null will be handled (requires more documentation), and 2) the default value is duplicated (it would stink if someone modified one but forgot to modify the other).

4) Use null operator and usedefaultparam keyword in Main

static void Main(string[] args)
{
    Client client = new Client(Username, Password, Timeout ?? usedefaultparam);
    // ...
}

I like this solution because it's easy to read and grows nicely if I add more optional parameters.

I dislike it because the usedefaultparam keyword doesn't seem to exists.

Thus my question:

Does something like option 4 exist? If not, is there a nicer, fifth pattern I am not thinking of?

Java code duplication refactoring

I use codeclimate to analyze statically my java code. The output says: Similar blocks of code found in 3 locations. Consider refactoring.

What could be the best way to refactor the following code without repeat myself and not losing the "code readability":

public String getString(String component, String key, String defaultValue) throws ConfigException {
    try {
      SingleRequestData config = clientRest.target(this.configServiceUrl).path(CONFIG_ENDPOINT).path(component)
          .path(key).path(defaultValue).request(MediaType.APPLICATION_JSON).get(new GenericType<SingleRequestData>() {
          });
      logger.log(Level.INFO, "Fetched Remote config: {0}={1} for Component: {3}",
          new Object[] { key, config.value, component });
      return config.value;
    } catch (Exception e) {
      logger.log(Level.SEVERE, "{0} : {1}", new Object[] { e.getMessage(), ERROR_MESSAGE });
      throw new ConfigException(e.getMessage() + " " + ERROR_MESSAGE, e.getCause());
    }
  }

  @Override
  public Integer getInteger(String component, String key, int defaultValue) throws ConfigException {
    try {
      String value = this.getString(component, key, String.valueOf(defaultValue));
      return Integer.parseInt(value);
    } catch (Exception e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      throw new ConfigException(e.getMessage(), e.getCause());
    }
  }

  @Override
  public Double getDouble(String component, String key, double defaultValue) throws ConfigException {
    try {
      String value = this.getString(component, key, String.valueOf(defaultValue));
      return Double.parseDouble(value);
    } catch (Exception e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      throw new ConfigException(e.getMessage(), e.getCause());
    }
  }

  @Override
  public Boolean getBoolean(String component, String key, boolean defaultValue) throws ConfigException {
    try {
      String value = this.getString(component, key, String.valueOf(defaultValue));
      return Boolean.parseBoolean(value);
    } catch (Exception e) {
      logger.log(Level.SEVERE, e.getMessage(), e);
      throw new ConfigException(e.getMessage(), e.getCause());
    }
  }

Thank you

Property file based builder pattern in java

I have a property file which has the details of Elasticsearch hostname, port number, and the scheme.

The Elasticsearch RestCleint API provides constructors to instantiate a client object with the hostname and also with hostname, port number and scheme.

There are cases when an application is deployed to AWS it has only a URL which can be used as the hostname. The same application, when deployed in the different environment, will have all 3 properties.

Therefore, I have created a class which does some if else and tried to instantiate the RestClient basing on the availability. The code looks very ugly. I want to use a Builder kind of Pattern which handles this elegantly. But, I am unable to get an idea to implement it. I would like to request a help.

This is how my current implementation looks like.

public class ElasticSearchContext {

    private RestClient restClient;

    public RestClient getContext() throws Exception {

        if (PropertyFileReader.getInstance().containsKey("elasticsearchHostName")
                && PropertyFileReader.getInstance().containsKey("elasticsearchPortNumber")
                && PropertyFileReader.getInstance().containsKey("elasticsearchScheme")) {

            restClient = RestClient
                    .builder(new HttpHost(PropertyFileReader.getInstance().getProperty("elasticsearchHostName"),
                            Integer.parseInt(PropertyFileReader.getInstance().getProperty("elasticsearchPortNumber")),
                            PropertyFileReader.getInstance().getProperty("elasticsearchScheme")))
                    .build();

        } else if (PropertyFileReader.getInstance().containsKey("elasticsearchHostName")
                && !PropertyFileReader.getInstance().containsKey("elasticsearchPortNumber")
                || PropertyFileReader.getInstance().containsKey("elasticsearchScheme")) {
            restClient = RestClient
                    .builder(new HttpHost(PropertyFileReader.getInstance().getProperty("elasticsearchHostName")))
                    .build();
        } else {
            throw new Exception("Hostname is mandatory");
        }

        return restClient;

    }

}

This is how my properties look like.

elasticsearchHostName=localhost
elasticsearchPortNumber=9200
elasticsearchScheme=http

Factory method arguments available in instance of inner class in python

When browsing Pyramid code I noticed one interesting thing in pyramid/session.py and I don't understand how it works and would be glad if you could explain or point me to the explanation.

In the mentioned pyramid/session.py there is method BaseCookieSessionFactory, which returns CookieSession object. In the CookieSession.__init__ and CookieSession._set_cookie parameter serializer is used.

I also created a simple example on repl.it, which represents the same behavior. I don't understand how can class instance can continue achieving outer function parameter when I call class_instance.get_a()

Statically allocated objects which don't die at out of scope?

What is a good way to allocate an object statically which does not die at end of scope?

For some class C with a constructor C() I have mostly used

C* lPtr = new C();

or

C& lPtr = *new C();

depending on what to return. But this is dynamically allocated which is not what I want.

I can write:

C lObj();

Which would allocate statically the memory of lObj, but then lObj will be destructed when leaving scope.. which I don't want either.

Do there exist any design patterns to build objects statically which survive falling out of scope?

C#, Announce class settings to GUI

I am working on a C# project where I have several electrical instruments such as Power supplies and Volt meters.

There are multiple choices for each instrument, for instance we have two different type of power supplies. We only connect to one of each type for every run.

In the design that I have in mind, I would like to have a common interface for each type, for instance

public interface PSU
{
    public void connect();
    public void disconnect();
    ...
}

Next in my GUI I will register all the available PSU units which will show up under a menu item and in that menu item only one of them can be selected for each type.

Next what I would like to do is for the units to announce their settings in a way that the GUI can create a sub menu out of those settings. My goal is to have it like this, so that if I add another PSU for instance, I would only need to register it.

My main questions here are the following:

  • How do I provide the settings in a way that can be turned into menus?
  • How do I connect menu event(s) to these dynamically created submenus? These events should actually update the instrument settings.
  • Is this even a valid and maintainable idea?

Thank you

jeudi 22 février 2018

Coupling and Performance/readability

I am working on refactoring some Object-Oriented code and I have the following problem:

The code design is mostly highly cohesive but classes are highly coupled together.

There are certain values (e.g. employeeID, project_id and location_id) that are used in many of the classes, so are passed as parameters quite often. The issue is that more often than not, classes use many more parameters (e.g. role, trajectory) that are derived from the first three values. As long as the class has the first three values, it can calculate the rest using helpers or similar.

The list of these secondary parameters can get quite long, but they are necessary. I could remove these arguments and just work them out in the constructor of the classes, but recalculating these values very often may impact the program.

I am concerned about the performance cost and readability. Some values (e.g. role) would be easy to query from the DB using employee_id, project_id and location_id, but others are more resource intensive (e.g. there is a class that calculates trajectories, and has to use geometry libraries, etc.).

What pattern would be desired in this situation? Is it worth reducing coupling at an increased cost? Here is are some examples of how the new classes could look:

Example 1:

class EmployeeMonitor:

    def __init__(self, employee_id, project_id, location_id, role, settings_list, gps_car_trajectory):
        pass

Example 2:

class EmployeeMonitor:

    def __init__(self, employee_id, project_id, location_id):
        role = calcRole()                      # low cost
        settings_list = calcSettings()         # low-ish cost
        gps_car_trajectory = calcTrajectory()  # medium cost (~200ms)

Understand that this is an example as I am not allowed to release any code. Any suggestion would be appreciated! Thanks in advance.

Service Injection in PDO

I'm designing the architecture for a new project and after analyze the requirements for the project. I realize that most of them are domain specific, also the domain is quite complex (multiple abstractions and inheritance families), also the validation rules are domain specific and it is expected to change quite a bit, the domain entities may vary their logic each year and retrocompatibility must be keep.

So i'm thinking that on this context using the PDO pattern (persistence domain object), can be quite useful for us, because we can use a full object oriented design and benefit from the use of polymophism and inheritance, using a skeleton process that mostly dont it is expected to change and the part that mute each year and it is domain specific can be placed on each PDO.

Thinking on that i have the following doubt, ¿It is correct to inject some service inside a PDO?. I am thinking about some common logic that could be isolated in a service and injected inside the PDO's that require it. Or a PDO should be always clean from injections of any kind and this common behaviour should be placed elsewhere.

I'm assuming that this common behaviour it's not specific to a family of objects, neither to all the "leaf" object on the inheritance tree.

Tanks for your answers.

Java regex with ^ symbol: find from position

I'm trying to find ^a{3} pattern in string, but not from beginning. From position 2

For example:

Pattern pattern = Pattern.compile("^a{3}");
Matcher m = pattern.matcher("xxaaa");
System.out.println(m.find(2));

It seems ^ means start of the string (not start of string from position 2)

But how to find pattern from position 2 and be sure that a{3} starts in this position

Correct/best way to use a third-party lib in React?

I'm working on a React project and the structure of components is:

Index /\ / \ ModContainer MapContainer | /\ [Modules] / \ Map Toolbar

Map contains an OpenLayers map object and I want Modules to interact with it. Should I pass the map object to the Modules as a prop? Or Create states and functions inside the Index component (common parent) and pass the functions to Modules as props??

Thanks in advance

Android design broken in different phones

I developed an android application I create 3 design screen, but after testing different devices with same screen resolution screen layout and elements arranging irregularly

Inheriting an implementation class for a method reusability

There is an implementation class - Class P, which has around 10 concrete methods in it. My interest lies with one of the methods of this class.

Problem is my class is not encouraged to directly call Class P method. Also for my class to access Class P method i will need to add a condition in the desired Class P method.

My question is which is more subtle-

  • inherit Class P into a new impl class and use this (given the no of methods in this class P i am not sure if this is right, as i will have overhead of unwanted extra methods).

  • or adjust my operation in the Class P method by adding few lines in Class P method.

mercredi 21 février 2018

Structuring reusable code

I have a class that does something similar to:

class B{
    void x(){
        statement-block1;
        statement-block2;
        statement-block3;
        statement-block4;
    }

    void y(){
        statement-block5;
        statement-block6;
        statement-block7;
        statement-block8;
    }
}

I need to add a new class that does this:

class C{
    void x(){
        statement-block1;
        statement-block200;
        statement-block3;
        statement-block4;
    }

    void y(){
        statement-block5;
        statement-block6;
        statement-block700;
        statement-block8;
    }
}

I was considering combining the reusable logic this way:

class A{
    void x(){
        statement-block1;
        statement-block2;
        u();
        statement-block4;
    }

    void y(){
        statement-block5;
        statement-block6;
        v();
        statement-block8;
    }

    virtual void u(){
        default-message;
    }

    virtual void v(){
        default-message;
    }
}

class B : A{
    void u(){
        statement-block3;
    }

    void v(){
        statement-block7;
    }
}

class C : A{
    void u(){
        statement-block200;
    }

    void v(){
        statement-block700;
    }
}

Is there a better way to implement this, a different/better way of injecting sub-class-specific code, or is there a design pattern I can use? In the future, I might have to add more classes similar to B and C.

Thanks!

Is this a valid usage of the Factory pattern? multiple dependancies

I want to create a set of dependancies instead of injecting them everywhere. Would the factory pattern support this idea? Or is there another pattern for dealing with it?

For example:

class PassportCheckFactory {
    protected $clientInstance;
    protected $responseInstance;

    public function buildDependancies() : bool
    {
        $this->clientInstance       = new PassportCheckSoapClient;
        $this->responseInstance    = new PassportCheckResponse;

        return true;
    }

    public function getResponseInstance()
    {
        return $this->responseInstance;
    }

    public function getClientInstance()
    {
        return $this->clientInstance;
    }
}

This creates and holds the classes we would use, so we wouldn't need to inject them.

For example, we can do this

$request = new WhateverRequestClass;
$factory = (new PassportCheckFactory)->buildDependancies();
$service = new PassportCheckService($request, $factory);
$response = $service->execute();

instead of:

$request = new WhateverRequestClass;
$service = new PassportCheckService($request, new PassportCheckSoapClient, new PassportCheckResponse);
$response = $service->execute();   

Cross reference workaround in C#

I have two classes and they have fields of each other types. Now I want to inherit from these classes in parallel and some magic so that derived classes could have the same fields but in relative types to each other after inheritance.

class Leader {
   public Follower slave;
}

class Follower {
   public Leader master;
}

class Teacher : Leader {}
class Student : Follower {}

class Officer : Leader {}
class Soldier : Follower {}

Teacher.slave.GetType(); // Returns Student
Officer.slave.GetType(); // Returns Soldier

Student.master.GetType(); // Returns Teacher
Soldier.master.GetType(); // Returns Officer

Is there a pattern or any solution to get this implemented in C#?

Is there anything wrong with using an imported config object in javascript/react

I have these settings passed to my component and they are used in various places around the app. Instead of carrying them with me all over the place I initialise a config object with them and then just import it when I need it.

Is there anything wrong with it?

Isn't this how dependency injection works?

Javascript resolves to the same object if the import is in the same place, right?

Example

// ./cmsSettings.js
const cmsSettings = {};
cmsSettings.initialise = (props) => {
  cmsSettings.settings = { ...props };
};

export default cmsSettings;

// ./App.jsx
import cmsSettings from './cmsSettings';
...

class App extends Component {
  constructor(props) {
    super(props);
    cmsSettings.initialise(props);
  }

  render() {
    return (
      <MyComponent />
    );
  }
}

export default App;

The props contain the object with the properties passed by the site (locales, languages, some ids, etc). I need them in various places for when I am getting language translations, making requests to APIs using specific ids and such.

So I have a config file that I initialise when the component is loaded and then import in a file that I need it. It will return the same object because javascript.

i.e.

// ./apiService
import cmsSettings from '../cmsSettings';
...

const get = () => {
  const url = `${BaseUrl}?id=${cmsSettings.settings.context.ee}&lang=${cmsSettings.settings.context.locale}`;

  return Request.get(url).then(response => response.body.data);
};

export default {
  get,
};

My other concern is that I have this initialise function which also has the benefit that allows me to "mock" the object in my unit tests.

Any opinions, advice, for, against?

Seperation of UI Laye from the domain layer

In the book Applying UML and Design Patterns, it is written that in a layered system, we delegate requests from the UI layer to the domain layer. An example of this is: If someone enters something in window and requests an operation on this newly input then this request should be delegated to domain/logical layer.

This is ok but suppose i want to show the result back in a window after adding two numbers for example, in this case , my domain/logical layer must know about the UI layer interface and then my representation is not independent of the view.

How do i solve this problem?

enter image description here

Is it possible to avoid birectional association between UI and Domain Layer? The problem is that the requests from users are caught in GUI and then these must do some calculations and update GUI.

Proper pattern or methodology to traverse data and dynamically construct objects?

I'm looking for potentially some design pattern advice regarding object traversal to dynamically construct objects based on the data being presented.

Below, I am manually constructing this object. Initially, the root node is a BinaryLogicOpType but could be a different object based on the rootNodeType.

My question is.. I need to dynamically construct these objects of differing types based on the string data in my lists. What is the best route in doing so?

I'm willing to refine this questions if it's confusing.

String rootNodeType = fN.type;

BinaryLogicOpType _blop = new BinaryLogicOpType();
JAXBElement<BinaryLogicOpType> root = constructRootElement(_blop, factory, rootNodeType);

/** LETS CREATE THE FIRST CHILD ELEMENT */
BinaryComparisonOpType attrName1GTEFive = new BinaryComparisonOpType();
_blop.getOps().add(factory.createPropertyIsEqualTo(attrName1GTEFive));

JAXBElement<String> attr1Property = factory.createValueReference(fN.nodes.get(0).getProperty());
LiteralType attr1ValueLiteral = new LiteralType();
attr1ValueLiteral.getContent().add(fN.nodes.get(0).getValue());

JAXBElement<LiteralType> attr1Value = factory.createLiteral(attr1ValueLiteral);

attrName1GTEFive.getExpression().add(attr1Property);
attrName1GTEFive.getExpression().add(attr1Value);

html pattern attribute does not appear in red in NotePad++

I just want to understand why it doesn't, since all of the other attributes in my code are "red". (although the "pattern" attribute does work when launched)

enter image description here

Password:
<input type="password" name="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" title="Enter a password that is minimum 8 characters, 1 lowercase characher and 1 uppercase character."><br />

How to know if an object was moved

It might be a stupid question but I feel like I am missing some design pattern.

During the destruction of a class I would like to do different operations if it was moved or not. I thought about implementing a simple boolean that is ticked when the class is moved.

Like this:

class A {
    A(const A && a) {
        a.was_moved = true;
    }

~A() {
    do some stuff

    if (!was_moved) {
        clean some more stuff
    }

bool was_moved = false;
};

Is there a "better" way doing this? some cpp feature I could ask if the class was moved or some known design pattern.

JQuery-like single / multi container class in Java

I'm looking to implement some sort of jQuery-like object in which, acting as container, can contain one or more objects.

In Jquery you can e.g do: $('.bla').addClass('ble');. It is unknown whether this is applied on one or more objects, yet the method is only one.

I was also very surprised to see that in java-8 you can do CompletableFuture.allOf(CompletableFuture<?>... cfs).join().

No matter how many objects you pass, you will get a single CompletableFuture<Void> and you can call any instance method that will act on all internal objects.

Still, its implementation is definitely too complex for my case.

My base interface looks like this

public interface Response< T extends DataTransferObject< ? > > {

    // instance methods

    public boolean isSuccess();
    public String getMessage();

    public default boolean isUndefined() {
        return this.equals(ActionResponse.UNDEF);
    }

    @SuppressWarnings("unchecked")
    public default Response< T > mergeWith(final Response< ? super T > response) {
        return Response.allOf(this, response);
    }

    public default boolean isMultiResponse() {
        return this instanceof ActionResponse.ActionMultiResponse;
    }
    /* -------------------------------------------------------------------------------------------------------------- */

    // factory methods

    @SuppressWarnings("unchecked")
    public static < U extends DataTransferObject< ? > > Response< U > allOf(final Response< ? super U >... responses) {

        Objects.requireNonNull(responses);

        if (responses.length == 0) return ( Response< U > ) ActionResponse.UNDEF;

        return new ActionResponse.ActionMultiResponse< U >(responses);
    }

    public static < U extends DataTransferObject< ? > > Response< U > from(final boolean success, final String message) {
        return new ActionResponse<>(success, message);
    }
}

The package-protected class looks like this (incomplete):

/* Package-protected implementation for the Response< T > type */
class ActionResponse< T extends DataTransferObject< ? > > implements Response< T > {

    static final Response< ? extends DataTransferObject< ? > > UNDEF = new ActionResponse<>();

    private final boolean success;
    private final String message;

    private ActionResponse() {
        this.success = false;
        this.message = null;
    }

    ActionResponse(final boolean success, final String message) {
        this.success = success;
        this.message = message;
    }

    // getters

    static final class ActionMultiResponse< T extends DataTransferObject< ? > > extends ActionResponse< T > {

        private final String[] messages;

        ActionMultiResponse(final boolean success, final String message) {
            super(success, message);
            this.messages = null;
        }

        ActionMultiResponse(final Response< ? super T >... responses) {

            /* must check if any of the following is already a MultiActionResponse */
            // TODO

            this.messages = new String[responses.length];

            for (int i = 0; i < responses.length; i++) {
                this.messages[i] = responses[i].getMessage();
            }
        }

        @Override
        public String getMessage() {

            if (this.messages == null) return super.getMessage();

            return Arrays.toString(this.messages); // dummy string merger
        }
    }
}

It's important that classes outside of this package can access only the interface as I want the implementation details to be hidden. Nobody should care on whether a given instance is a single or a multi.

The only way you can build a Response< T > would be via the factory methods provided or the instance method Response::mergeWith. E.g:

Response< SpotDTO > response = Response.from(true, "message");


If was wondering if this is indeed a pattern and if such pattern has a name? If so, what guidelines should I follow?

What is a better way to implement this concept?

For instance, I do not like that the ActionResponse holds a String type for message whereas ActionMultiResponse has String[].

Still I do not want to have only one object with a String array and place if needed only one object inside.

MVP in Matlab, why using View Interfaces?

I'm trying to create a simple Matlab GUI which displays some data from an external sensor on potentially different views. The goal is to implement some kind of MVP (Model View Presenter) pattern. However, some questions occured. First a short description of my classes:

classdef (Abstract)IView < handle        
    properties (Abstract)
        % define required properties, to be implemented by subclass
        ConnectedSensorSerialnumbers
        SensorsAreConnected 
        ...
    end

    events 
        % define some required events
        ConnectButtonPressed
        ...
    end

    methods (Abstract)
    end
end

A concrete View could look like

classdef ViewAppDesigner < IView % implement the interface
    properties (private)
        ViewInstance matlab.apps.AppBase
    end

    properties
        ConnectedSensorSerialnumbers
        SensorsAreConnected 
    end

    events 
        ConnectButtonPressed
    end

    methods
        % ctor
        function obj = ViewAppDesigner ()
            % create View made by Appdesigner, a GUI tool
            obj.ViewInstance = CreateAppDesignerGui();
        end

        % bind the events to some GUI elements, notify if something changed etc.
        ...
    end
end

A presenter could look like

classdef Presenter < handle       
    properties
        Model IModel = DefaultModel();
        View IView = DefaultView();
    end

    methods
        function obj = Presenter(view, model)
            % input error checks etc.
            ...
            % make model and view known to Presenter
            obj.Model = model;
            obj.View = view;

            obj.registerViewCallbacks();
        end

        function registerViewCallbacks(obj)
            addlistener(obj.View, 'ConnectButtonPressed', @obj.onConnectButtonPressed);
            ...
        end

        function onConnectButtonPressed(obj, src, evt)
            obj.Model.connectSensor
            if obj.Model.IsConnected
                obj.View.ConnectedSensorSerialnumbers = obj.Model.GetListOfConnectedSensors.SerialNumber;
                obj.View.SensorsAreConnected = true;
            else
                % trigger some error message
            end                
        end
    end
end

For clarity I did not write down the Model + Interface.

However, these are my questions:

  1. In this implementation the View is decoupled by an Interface. In the classical MVP pattern each View belongs to exactly one Presenter. So the Presenter could use the View's internals. Why do we need an Interface then?

  2. The above approach feels not right, if we used an appropiate Interface one Presenter could handle multiple Views, because it is decoupled. For example one could create a second View showing the data on a console. The Interface remains the same, even the Presenter remains the same, but the View has to include some logic. For example SensorsAreConnected could be a green lamp in the GUI implementation or a plain text message in a console View. But that would require the concrete View knows how to display that information. Is that design okay or has the View to be as dump as possible? That would lead to #1 and we don't need an Interface anymore.

In the end, is some logic in the View allowed and can we use multiple Views in one Presenter?

Thank you very much!