vendredi 31 janvier 2020

Springboot external api call request and response capture in database

From my backend application(springboot, java8) i will make multiple external api call's. I have a requirement to log all the requests and response data's (including headers, request and response body) into database(MongoDB).

Below is my sample code, this how i am trying to capture request and responses on each external api calls. On exception i will store status as 'FAILED'.

In my project multiple modules will be added on new 3rd party api integration, so in each module for every different external api calls i have to capture all the requests and reponses like this. I am not satisfied with below approach. Kindly suggest best approach to solve this.

Sample Service layer method

public ResponseDTOFromExternalApi externalApiCallServiceMethod(String clientId, RequestDTO requestDTO) {

        ExternalApiCallRequestObj externalApiCallRequestObj = prepareExternalApiRequestObjFromRequestDTO(requestDTO);
        ApiCall apiCall = ApiCall.builder()
                .clientId(clientId)
                .status("SUBMITTED")
                .requestPayload(externalApiCallRequestObj)
                .build();

        apiCall = apiCallRepository.save(apiCall);

        ExternalApiCallReponseObj externalApiCallReponseObj = externalApiCallService.callExternalApi1(externalApiCallRequestObj);

        apiCall = apiCallRepository.findById(apiCall.getId());

        apiCall.setResponsePayload(externalApiCallReponseObj);
        apiCall.setStatus("COMPLETED");

        apiCallRepository.save(apiCall);

        return toDTO(externalApiCallReponseObj);
}

Sample Domain for api calls

@Document("api_calls")
@Builder
@Data
public class ApiCall {

    @Id
    private String id;

    private String clientId;

    private String status;

    private Object requestPayload;

    private Object responsePayload;

}

Solution to the Second Example of the Anti-If Campaign

1. My Attempt

The first example of bad code in the Anti-If Campaign's website seems pretty trivial and standard to me. The solution, as plenty of books, other StackOverflow questions and websites have pointed out, is polymorphism.

However, the second, server example doesn't seem so straightforward to me — which is an indication that I'm not that good a programmer, I guess. I would like for someone to please confirm if my solution attempts are right; or, if not, give a better one. (My points are numbered so the answer can refer to them more easily, this is not a hierarchical ordering.)

  1. Even though there is only one if-null condition highlighted, there are plenty of such cases throughout that example. My guess at the best way of solving this type of issue is to use the Null Object Pattern.
  2. Probably the biggest issue with that piece of code isn't even the if's themselves, but the huge amount of nesting, of which we can encounter up to 5 levels.
  3. The if (getArea() == 1) conditional doesn't seem that bad to me if it is only in this piece of the codebase. But it surely doesn't reveal that much meaning and intention to the reader. What does the 1 mean? Is it a suffiency clause? Then maybe it would have been better to replace it by something like if (validArea()). It is also not attached to any object, so I can't easily easily establish relationships.
    1. I think this if clause could also benefit from either a Factory or a Template Method, depending on what the relationship of the objects is — it isn't very clear to me what would be the correct choice from only that piece of code, but maybe someone more experienced could have a better grasp of the solution.

2. The Referenced Code

For reference, this is the piece of code (Java) in the website (there is some weirdness with the indentation and commenting on the else line I think):

public ArrayList eseguiAnalisi() {
  ArrayList listaSegnalazioni = new ArrayList();

  List domande = null;
  List risposte = null;
  Domanda domanda = null;

  DAOReques req = new DAOReques();
  DAOArea ar = new DAOArea();
  ar.setIdQuestionario(getIdQuestionario());

  boolean quizDomandaNonForzata = false; // warning 7

  try {
    //set Aree e
    if (getArea() == 1) { // Highlight #1
      List aree = ar.getAree();
      Area area = null;

      for (int i = 0; i < aree.size(); i++) {
        area = (Area) aree.get(i);
        domande = req.getDomande(getIdQuestionario(),area.getIdArea());
        if (domande != null) {
          for (int j = 0; j < domande.size(); j++) {
            domanda = (Domanda) domande.get(j);
            risposte = req.getRisposteDomanda(getIdQuestionario(),domanda.getIdDomanda());
            if (risposte != null)
            domanda.setRisposte(risposte);
          }
        }
      }

      area.setDomandeArea(domande);

      if (aree != null) // Highlight #2
      setAreeDomande(aree);
    } //else { // I think there was an indentation mistake in the website...
      // set ListaDomande
      domande = req.getDomande(getIdQuestionario());


      for (int i = 0; i < domande.size(); i++) {
        domanda = (Domanda) domande.get(i);
        risposte = req.getRisposteDomanda(getIdQuestionario(),domanda.getIdDomanda());
        if (risposte != null)
        domanda.setRisposte(risposte);
      }
      if (domande!=null)
      setDomande(domande);
  //}
  } catch (DAOException de) {
    de.printStackTrace();
  }

is there any way to invoke different classes (which have different types of input and output) from a common class

I have a unique issue. I am building a spring boot app from where i need to invoke different types of rest api urls based on a parameter from client. Each of these api could have different input and output but there invocation would be based on a single parameter which i will receive as a parameter. I am thinking of creating separate operation classes for these separate apis under a common interface. And i will create a factory using factory design pattern and will create object of one of these operation classes from this factory class using input parameter value as decision making value. But as input and out could be different for different apis , i should have a mapper class which can map input and output from these api and can represent a common input and out.

But if i create a single mapper class for all of these operation classes, each time we introduce a new rest api to call from our app, we are going to have a new operation class so we need to modify this mapper class as well. this is where i am stuck. I am not able to find solution for this. Is there any design pattern which i can use here or can spring boot come to rescue?

Aprender design patterns e engenharia de software

Boa tarde, galera.

Tenho programado forma mais séria há dois anos e a maior parte desse tempo me dediquei a programação Android com Java, desenvolvendo alguns projetos e coisas do tipo. Além disso, curso ciência da computação. Ao longo desse período, consegui aprender bastante coisa e resolver alguns problemas, porém sinto muito amadorismo nos meus códigos. Queria saber quando é uma boa começar a estudar engenharia de software e design patterns para melhorar a qualidade do que eu desenvolvo e como começar a estudar esses assuntos, pois só verei esses conteúdos daqui um ano e quero mexer com isso, já que tenho muito tempo livre por estar de férias.

Design pattern to store context of "sessions" in asynchronous application

Context

I have a running NodeJS application which can be interacted with a CLI.

The communication is done with Websocket: - The CLI emit an Event to run a task in the running NodeJS application - The NodeJS application emit Events to log messages to the CLI

The NodeJS application is huge and completely written in POO with Typescript.

Problem

Imagine I have a class like this:

export class Order {

  public id;
  public customer;
  public total;

  public send() {
    ...
  }

  public static get (orderId: number) {
    return new Order(api.get(orderId));
  }
}

And the socket server like this:

// This event is emitted by the CLI
socket.on('sendOrder', orderId => {
  socket.emit('title', 'Sending order...') // This tell to the CLI to log a title
  const order = Order.get(orderId)         // Retreive the Order
  order.send()                             // Send the Order
  socket.emit('exit', 'Succesfully sent')  // This tell to the CLI to exit with a message
})

I would like to get the current context (in my case, the Socket) from anywhere in my application, example:

export class Order {
  public send() {
    socket.emit('message', 'Sending 34%...')
  }
}

Where am I currently

If I store the context (in my case, the socket) in a "global" variable and run two CLI commands at a time. The second one will override this "global" variable.

So I bring everywhere the Socket with me, example:

export class Order {

  public id;
  public customer;
  public total;

  constructor(private socket: Socket, data) { ... }

  public send() {
    this.socket.emit('message', 'Sending 34%...')
  }

  public static get (socket, orderId: number) {
    return new Order(socket, api.get(orderId));
  }
}
// This event is emitted by the CLI
socket.on('sendOrder', orderId => {
  socket.emit('title', 'Sending order...') // This tell to the CLI to log a title
  const order = Order.get(socket, orderId)         // Retreive the Order
  order.send()                             // Send the Order
  socket.emit('exit', 'Succesfully sent')  // This tell to the CLI to exit with a message
})

Conclusion

Bringing the context everywhere is a pain when the application start to growth.. As a PHP Developer I never had this kind of problem and I couldn't find anything related to my problem on the Web.

Is there any design pattern for my case ?

This question will surely get closed for opinion-based. Fingers crossed.

Is there buffered lock pattern?

In Go there is a concept of buffered channel. That is a channel that will not be locked untill you fill its buffer.

Is there any general pattern for general buffered locking? It will lock some resource for limited amount of clients.

Security of account recovery codes

Description

Many web platforms use recovery codes for account restoration (for example: mega.nz).

However, big tech companies (like Google or Apple) do not use recovery codes. User don't get any key, code or password during account creation.

Security value of recovery codes

Is it because of any security vulnerabilities? Or security codes are obsolete, and there is some better approach?

What are advantages and disadvantages of account recovery codes?

I can't understand the syntax of this code

I am watching a course about design-patterns and it uses sample codes like below, but I can't understand the language of the code exactly. For example in the following code I can't understand how public static ExampleSingleton getInstances() works? I mean why does it use the name of the class before the name of the function?

enter image description here

Or in the next code, why in publick Kinfe orderKinfe(String knifeType) it uses Kinfe word before the name of the method?

enter image description here

I have confused about this syntax and can't understand it right. So please help me!

How to filter the specific entries within a with a specific pattern over certain value?

I have a data file containing the following information: I am interested to retrieve only the entries where the pattern

len:XXXX is greater than 200

TY_DN106_c0_g2::TY_DN106_c0_g2_i1::g.1::m.1 type:internal len:123 gc:universal TY_DN106_c0_g2_i1:1-366(+) TY_DN106_c0_g2::TY_DN106_c0_g2_i1::g.2::m.2 type:internal len:213 gc:universal TY_DN106_c0_g2_i1:366-1(-) TY_DN108_c0_g1::TY_DN108_c0_g1_i1::g.3::m.3 type:5partial len:513 gc:universal TY_DN108_c0_g1_i1:3-341(+)

How could I do it in Python or other scripting language??

Flask - Cannot use instance celery into app/__init__.py?

I have already visited several questions in the community, but I believe this is my fault because I was unable to identify an adequate way, in the use of the factory architecture pattern indicate in documentation Flask.

We have an application, based on Flask + Gunicorn + Nginx, that always worked without major challenges. However, we need to build a solution that requires asynchronous tasks. Soon the indication was unanimous, to use Celery for this, but even following the style used here.

I can't make the project compile because it informs that there are import errors and the official documentation of the framework does not bring much clarity on how to use it, in the structure factory, just how to do it in single instance.

How can I solve this?

My traceback:

  File "/home/user/Workspace/test/project_async/celery_runner.py", line 3, in <module>
    from app import create_app
  File "/home/user/Workspace/test/project_async/app/__init__.py", line 9, in <module>
    from .api import configure as config_api
  File "/home/user/Workspace/test/project_async/app/api.py", line 3, in <module>
    from .resources.chosen import Change
  File "/home/user/Workspace/test/project_async/app/resources/chosen.py", line 5, in <module>
    from app.jobs.tasks import exec_change as tk_change
  File "/home/user/Workspace/test/project_async/app/jobs/tasks.py", line 1, in <module>
    from app import celery
ImportError: cannot import name 'celery' from 'app' (/home/user/Workspace/test/project_async/app/__init__.py)

My structure:

.
├── app
│   ├── api.py
│   ├── jobs
│   │   ├── celeryconfig.py
│   │   ├── __init__.py
│   │   └── tasks.py
│   ├── jwt.py
│   ├── models
│   │   ├── core.py
│   │   ├── __init__.py
│   │   ├── inventory.py
│   │   └── other.py
│   ├── resources
│   │   ├── chosen.py
│   │   └── __init__.py
│   ├── schemas.py
│   ├── services
│   │   ├── chosen.py
│   │   ├── base.py
│   │   ├── chosen_other.py
│   │   └── inventory.py
│   ├── static
│   │   ├── swagger.json
│   │   └── swagger.yaml
│   ├── swagger.py
│   └── utils.py
├── celery_runner.py
├── config.py
├── main.py
├── test.log
└── tests
    ├── __init__.py
    └── test_inventory.py

Code:

path - app/__init__.py

from flask import Flask
from flask_cors import CORS
from flask_migrate import Migrate

from config import configure as config_project

from .api import configure as config_api
from .jwt import configure as config_jwt
from .models.core import configure as config_db
from .models.inventory import configure as config_db_mongo
from .swagger import configure as config_docs
from celery import Celery

celery = Celery(__name__)

def create_app(config_name):

    app = Flask(__name__)

    '''Added Configurations'''
    config_project(app)
    config_jwt(app)
    config_api(app)
    config_docs(app)
    config_db(app)
    config_db_mongo(app)
    '''Added Thirds'''
    CORS(app)
    Migrate(app, app.db)
    '''Background Tasks'''
    celery.conf.update(app.config)
    celery.config_from_object('app.jobs.celeryconfig')

    return app

path - project_async/celery_worker.py

from dotenv import find_dotenv, load_dotenv

from app import create_app

load_dotenv(find_dotenv())

app = create_app(getenv('FLASK_ENV') or 'default')
app.app_context().push()

path - app/jobs/celeryconfig.py

broker_url = 'redis://localhost:6379/1'
result_backend = 'redis://localhost:6379/0'

# import
imports = 'app.jobs.tasks'

# Timezone
timezone = 'America/Bogota'
enable_utc = True

path - app/jobs/tasks.py

from app import celery
from app.services.chosen_other import ChangeOpportunity


@celery.task(name='tasks.change')
def exec_change(data, change, client):
    change = ChangeOpportunity(data, change, client)
    change.execute_change()

return string when using the builder Pattern and Method chaining in C#

i want to use Builder Pattern and use that by Method chaining .

this is my class :

 public class SQLGenerator : ISQLGenerator
{
    private readonly SQLGeneratorModel generatorModel;
    public SQLGenerator()
    {
        generatorModel = new SQLGeneratorModel();
    }

    public ISQLGenerator From(string TableName)
    {
        generatorModel.TabelName = string.Format("FROM {0}", TableName);
        return this;
    }

    public ISQLGenerator Select(List<string> SelectItems)
    {
        StringBuilder select = new StringBuilder();
        var lastItem = SelectItems.Last();
        foreach (var item in SelectItems)
        {
            if (!item.Equals(lastItem))
            {
                select.Append(item).Append(" , ");
            }
            else
            {
                select.Append(item);
            }
        }
        generatorModel.Select =string.Format("SELECT {0}", select.ToString());
        return this;
    }

and class that by ths way :

        SQLGenerator generator = new SQLGenerator();
        List<string> select = new List<string>();
        select.Add("id");
        select.Add("Name");
        var str = generator.Select(select).From("AppUsers");
        Console.WriteLine(str);

now i except return to me string like this SELECT ID , NAME FROM APPUSER but it show me this result in the console :

SqlPagingGenerator.Pattern.SQLGenerator

how can i show the string result ????

Real Time video Processing Design issue

I am a newbie in the field and don't know if i am doing this right. So I need help with architectural and design issue, just to make sure if I am moving in right direction.

I am trying to process a real time video capturing from the client's camera. The captured video stream is converted into frames and send to the server for processing. After processing, server is sending it back to client's screen.

My backend code is written in Python and I am using SocketIo to send the frames from frontend to backend. You can have a look at this design to get a better idea about what's happening - https://docs.google.com/drawings/d/1_65mikOZaaL1oLHFEzTzaoKptgj98OX1_EALqCIwYqI/edit?usp=sharing .

  1. My server(app.py) will be running in backend and client will be accessing index.html
  2. SocketIo connection will get establish and video stream captured using webcam will be send to server frames by frames.
  3. These frames will be then processed at the backend and emit back to the client.
  4. Processed frames coming form the server can be shown in img tag.

So, my problem with this architecture is the lag. There is a noticeable delay even after limiting fps. From client to server then processing and back to client, each frame is take on an average 150 ms and is not giving a real time response. I have tried my image processing code separately with no socket programming on local and it is more near to real time (it is taking 80 ms for one frame).

But I fail to understand here that how can I minimize lagging with this design or improvise it? Is there any better way to do this task to get more real time results?

Thanks in advance!

jeudi 30 janvier 2020

Need to invoke same controller method for different api's

I have 2 APIs

1. localhost:8080/myservice/foo/1/0/updatesStatus
2. localhost:8080/myservice/bar/1/0/updatesStatus

I am not allowed to have different controllers for each API. So both the APIs are pointing to the same controller method where I have if-else check, but the code looks very bad in that, is there any better way to handle this.

@PostMapping(value = UPDATE_STATUS_API_PATH)
public Response updateStatus(@PathVariable("group") String group , @RequestBody UpdateStatusRequest updateStatusRequest, HttpServletRequest request) {
        try {
            if(APIUrl.FOO_GROUP.equals(group)){
               //code spefic to foo
            }
            else{
              //code spefic to bar
            }
            //common code
}

The same conditional checks also have to be performed on the service layer as well. Is there any way I can avoid this conditional checks without having separate controller methods.

How to do Design Patterns for files and persistency on applications?

I have an application that used Ionic Storage to store flags and other simple objects used in the system.

Over time the application grew and the objects became bigger and demand more and more.

I would like some Design Patterns suggestions for handling files in Ionic.

In version 3, there was a defined "halt" in AppComponent, where I started all the critical services and storage, now on v4, I had to create a SplashComponent that "holds" until all services are started. I'm switching to files so things started to enter in the uncanny valley.

The diagram below explains it better:

Before (Ionic 2)

AppComponent.ts platform.ready() -> Start Services and prepare Storage -> After all set-up assign a page to rootpage and voilà app good to go

NOW (Ionic 4)

AppComponent.ts platform.ready() -> routing leads to a SplashPageComponent(Page) Basically all methods wich prepare stored are here. As they're all asynchronous I made an "access lock". A big if() checking a boolean for every method

if(method_1_lock && method_2_lock && method_3_lock...)

The core of my application is a gamified questions app, with progress save, as well as a system of achievements.

I didn't put my code itself, because I'm not exactly needing the coding, but the idea of how to do things.

Should I put user settings on file? on memory? Should I use a splash screen, should I start it all on Home? This kind of things.

Every single tutorial on internet are about actually DOING things, but quite few are about thinking on how and how well do a few things...

Any help?

Design help- Design pattern for handling a generic interface for different types of messages

I have to bring up an interface for a node which can receive messages with same header but different message types. The message type comes at a fixed position in the header always. These message types can further be divided into two classifications - Atype(a set of 6 messages) and Btype(a set of 8 messages). The design needs to provide support to add a new message type (eg Ctype) to the interface easily. I have been thinking of writing an interface class which has a std::map with message_type being Atype or Btype and the message_handler_type is a function call to the corresponding message handlers(based on two singleton classes for AtypeMessage and BtypeMessage) - AtypeMessage::get_instance()->AtypeMessageHandler() or BtypeMessage::get_instance()->BtypeMessageHandler() and pass the message along to the corresponding message handler based on the message_type. This node will receive huge amount of traffic. Will this be a good enough design for future extension? Is there any other good design options that I am missing out?

Where should UICollectionView/UITableView delegate/datasource functions go in Clean Swift [Uncle Bob's Clean Architecture]

I recently switched my app over from MVC to Clean Swift and i'm having trouble deciding in which classes to put certain things. For example, should the delegate/datasource functions for a UICollectionView/UITableView go in the Interactor, or Presenter? Or maybe certain functions, like didSelectItemAt should go in the Interactor because they deal with input, and others, like cellForItemAt, should go in the Presenter because they deal with views.

What are your decision making processes when deciding where to put certain functionality in Clean Swift?`

Currently I have the following in my ViewController

{
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool)
    func scrollViewDidScroll(_ scrollView: UIScrollView)

}

the following in my Interactor

{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
}

and the following in my Presenter

{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets 
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 
}

How to mock classes of external framework with delegates in iOS?

I am working in an iOS application called ConnectApp and I am using a framework called Connector. Now, Connector framework completes actual connection task with BLE devices and let my caller app (i.e. ConnectApp) know the connection request results through ConnectionDelegate. Let's see example code,

ConnectApp - host app

class ConnectionService: ConnectionDelegate {

    func connect(){
        var connector = Connector()
        connector.setDelegate(self)
        connector.connect()
    }

    func onConnected(result: ConnectionResult) {
        //connection result
    }
}

Connector Framework

public class ConnectionResult {
    // many complicated custom variables
}

public protocol ConnectionDelegate {
      func onConnected(result: ConnectionResult)
}

public class Connector {

   var delegate: ConnectionDelegate?

   func setDelegate(delegate: ConnectionDelegate) {
       self.delegate = delegate
   }

   func connect() {
        //…..
        // result = prepared from framework
        delegate?.onConnected(result)
   }
}

Problem

Sometimes developers have no BLE device and we need to mock the Connector layer of framework. In case of simple classes (i.e. with simpler methods) we could have used inheritance and mock the Connector with a MockConnector which might override the lower tasks and return status from MockConnector class. But when I need to deal with a ConnectionDelegate which returns complicated object. How can I resolve this issue?

Note that framework does not provide interfaces of the classes rather we need to find way around for concrete objects like, Connector, ConnectionDelegate etc.

A service that implements Observer and Controller observable

I have a @service that implements Observer and on the other hand, the controller is Observable. Is this approach is correct? is there any disadvantage or logically is incorrect?

How can i use a single namespace for multiple imported modules?

Is it possible to have a single namespace for multiple imported modules ?, i wanna do something like this:

import {moduleA, moduleB, moduleC} as ModuleManager from 'AllMyModules.js';

So i can avoid conflicts such as module and class function having the same name, for example :

moduleA = () => {
}

doSomething = () => {
   ModuleManager.moduleA();
   moduleA();
}  

Of course that is not all, giving the modules a namespace also improves readability and helps me know where a function or module is coming from and for what purpose.

Please note that i already know about:

import * as ModuleManager from 'AllMyModules.js'  

And this is not what i'm looking for !, i don't want ModuleManager to include everything.

C++: Design suggestions for class

Lets say i have an object CAR

class CAR
{
public:
    string doorColor
    string seatColor
    string engineCC
    string engineTransmission 
    string engineTorque
    string enginePower
    string steering
    string break
    void initCarSpec();

    ..
}

At some part i have a business logic based on engine , where the logic is based only on engine properties and does not care about rest of the properties. The current design is this way loading up the car object and iterating through it :

std::map <std::string , std::shared_ptr <CAR>> carsPortfolio 
carsPortfolio["Ford"] = carspec1
carsPortfolio["Tesla"] = carspec2
carsPortfolio["BMW"] = carspec3

for(auto itr = carsPortfolio.begin(); itr != carsPortfolio.end(); ++itr)
{
    if (itr->engineCC > x) {do something}
    if (itr->enginePower > y) {do something}
}

I m thinking it would be better not to load the entire object , instead create a struct only for engine spec and iterate through it.

struct Engine
{
    string engineCC
    string engineTransmission 
    string engineTorque
    string enginePower
};

class CAR
{
public:
    string doorColor
    string seatColor
    struct Engine engineSpec;
    string steering
    string break
    void initCarSpec();

    ..
}

std::map <std::string ,std::shared_ptr <struct Engine>> engineSpecs;
engineSpecs["Ford"] = engineSpec1;
engineSpecs["Tesla"] = engineSpec2;
engineSpecs["BMW"] = engineSpec3;
for(auto itr = engineSpecs.begin(); itr != engineSpecs.end(); ++itr)
{
    if (itr->engineCC > x) {do something}
    if (itr->enginePower > y) {do something}
}

Please suggest.. I m also looking for suggestions for a good material to read , i did a lot of reads on the web which got me more confused than before.

mercredi 29 janvier 2020

How to use AttributeConverter and @ElementCollection in a wrapped List using Hibernate?

I need to implement an API that provides custom data types to use in software development. The idea is that such types can give additional features to the default ones from Java language.

For example:

class ViewStringList {

  // String value
  private List<String> values = new ArrayList();

  // Define if the value must be show/hide on view
  private boolean visible;

  public List<String> getValues() {
    return values;
  }

  public void hide() {
    this.visible = false;
  }

  public void show() {
    this.visible = true;
  }

}

This custom type can be viewed as an extension from the Java List<String> type because it provides the hide and show feature. Using this type as Java property is fine because it facilitates development. However, if I want to persist each value from the ViewStringList list of values in a relational table using @ElementCollection and AttributeConverter I don't know how to do this. For example:

@Entity
class Panel {

  @ElementCollection
  private ViewStringList cars = new ViewStringList();

  @ElementCollection
  private ViewStringList trucks = new ViewStringList();

  // Getters/setters
}

class FormTemplate {

  public Panel getUserPanel() {
    Panel panel = new Panel();
    panel.getCars().show();
    panel.getTrucks().hide();
    return panel;    
  }

}

@Converter(autoApply = true)
class ViewStringConverter implemets AttributeConverter<ViewStringList, String> {

  @Override
  public String convertToDatabaseColumn(ViewStringList viewString) {
    return ?;
  }

  @Override
  public ViewStringList convertToEntityAttribute(String string) {
    return ?;
  }

}

Is that possible? There is some other strategy to achieve this persistence?

Designing Validator for validating the data

I am trying to design validator which will validate the rules configured in config file and if any of the rules satisfied, we need to block that data.

public class AllMatchDemo {

    public static void main(String[] args) {

        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("String","Ask");
        dataMap.put("Date1", new Date());
        dataMap.put("Long", new Long(100));
        dataMap.put("Integer", new Integer(10));

        String message = new String();
        List<Validator> validators = Arrays.asList(new RegexValidator(),new DateIsBeforeTodayValidator ());

        boolean result = validators.stream().anyMatch(validator -> validator.validate(dataMap,message));
        System.out.println("Result :"+result);
        if(result)
        {
            block;
        }

    }
}
public interface Validator {
    boolean validate(Map<String,String> dataMap,String message);
}

Following are implementors :

public class DateIsBeforeTodayValidator implements Validator {

    String dateFieldToBeCompared;

    @Override
    public boolean validate(Map<String,String> dataMap, String message) {

    }

    public void setDateFieldToBeCompared(String dateFieldToBeCompared) {
        this.dateFieldToBeCompared = dateFieldToBeCompared;
    }
}
public class RegexValidator implements Validator {

 @Override
    public boolean validate(IPublishable publishable) {
                      //validation Logic here based on match                    
              }

}

Initially I started with RegexValidator without any Validator and later on requirement kept on increasing and I have to compare dates too so I created Validator interface and provided above 2 implementations. In future many other implementations would be needed like date1 compare to date2 , date less than, number greater than etc.

Is there any other better way to handle design so that it can be scalable in future ?

How to resolve type safety objections to global setting/event registry?

I'm working on a client’s Java application with multiple projects and plugins. They have a very brittle design because sharing any information across these division involves some god classes instantiating and registering classes that implement specific interfaces. The interfaces proliferate unchecked and often contain contract methods that no client requires.

In an effort to decouple everything, I have proposed a couple of clearinghouse objects that handle “settings” and “events”. Any class can request a setting, specifying the type of setting from an enumeration and the type of value expected. Any class can register a setting source that implements an interface defining how to get that setting (e.g. whether the network is available by checking some variable in some class), but more often I can completely separate some variable from the original class and it floats for eternity as an anonymous SettingSource that just accepts and publishes some setting value.

//code from caller requesting the setting value
long netID = Setting.GetLongSetting(Setting.Type.NetworkID);

//one of those self-defined settings
Setting.RegisterLongSource(Setting.Type.NetworkID, new LongSource() {
  private long myID=-1;

  @Override
  public long getValue() {
    return myID;
  }

  @Override
  public void setValue(long l) {
    myID = l;
  }

  @Override
  public Setting.Type getType() {
    return Setting.Type.NetworkID;
  }
} 

The events are registered in a similar way with an EventArg object borrowed heavily from C#.

//code from an event generator
Events.Event(Event.Type.MessageReceived, new ObjectEventArg(messageInstance));

//An anonymous event listener that expects a message object and passes it to a method for processing
Events.RegisterListener(Event.Type.MessageReceived, new Event.Listener() {
  @Override
  public void HandleEvent(Event.Type type, EventArg e) {
    if(type!=Event.Type.MessageReceived)
    {
       try
       {
         Message m = (Message) ((ObjectEventArgs)e).value;
         if(m!=null)
         {
           this.handleMessage(m);
         }
         else
         {
           //error 3
         }
       }
       catch
       {
         //error 2
       }
    }
    else
    {
      //error 1
    }
  }
} 

There are some problems with these designs and my clients are asking me to consider something that has more compile-time safety. For example there are three opportunities for errors in the events. It should be impossible for an event listener to get an event type for which it didn't register (error 1), but I should at least check. There is no guarantee that the EventArg type will be the right kind or that the object passed in the ObjectEventArg will match expectations (error 2). There is no guarantee that the passed reference isn't null (error 1). All of this leaves so very much up to the good behavior of the code that cannot be guaranteed at compile time. For that matter, someone could try to create settings for time that accept a string instead of a long and who to say which is right?

What could I do to improve this design, avoid some of the unknowns, and provide that compile-time guarantee?

mardi 28 janvier 2020

Why does Spring's RestTemplate has setters when Spring also provides RestTemplateBuilder class to build RestTemplate

The following are the methods:

  1. public void setMessageConverters(List> messageConverters)
  2. public void setErrorHandler(ResponseErrorHandler errorHandler)
  3. public void setDefaultUriVariables(Map uriVars)
  4. public void setUriTemplateHandler(UriTemplateHandler handler)

I was expecting that RestTemplate would be immutable.

Does it mean that we are not meant to reuse a singleton bean of RestTemplate?

Thanks in advance

how to update the using unit of some values in many pages

I have three pages A,B,C, and each of them has a Label to show a different distance value and the distance values can be presented as Km or Mile. The app provides a settings page for the user to change the distance unit globally. My question is how to update the UI globally when the distance unit setting is changed?

My current solution is to let every page that has distance values subscribe to the unit changed event and update its UI element separately when the event is invoked, but the app will end up having many redundant codes in this way.

Is there any elegant solution to this issue?

PHP spl_autload_register alternative way

I am making a pattern for my own project, We knew that this spl_autoload_register turn into all files until it finished. It just returns the class as I know. Let's get into my wish/ Problem.

app
 |__ controllers
 |      |__ ctrl-default.php
 |      |__ ctrl-other.php
 |
 |
 index.php

In my controllers have classes with the almost same name.

// ctrl-default.php
class  ctrl_default{
  //silence is golden...
}

// ctrl-other.php
class  ctrl_other{
  //silence is golden...
}

I can not find the class name for the '-' and '_' But I don't want to change my file name or class name. Is there any possible way to get all the class on my index.php page, without changing the controllers' name? Is there any alternative way of spl_autoload_register()?

Is there a name for this 'pattern'?

I recently encountered a situation where it was useful to create a lazy-loading version of a class by wrapping its factory.

I'd like to do some research to find out if there are any issues I hadn't thought of before I rely too heavily on it, but I don't know what to look for.

edit: In my case it involves creation of cookies and session files, which I don't want to do until a user's credentials are verified.

interface FooInterface
{
    public function bar();
}

class Foo implements FooInterface
{
    public function bar()
    {
        ...
    }
}

interface FooFactoryInterface
{
    public function getFoo():FooInterface;
}

class FooFactory
{
    public function getFoo():FooInterface
    {
        return new Foo(...);
    }
}

class LazyFoo implements FooInterface
{
    protected
        $foo=null,
        $factory;
    public function __construct(FooFactoryInterface $factory)
    {
        $this->factory=$factory;
    }
    public function bar()
    {
        if($this->foo===null) $this->foo=$this->factory->getFoo();
        return $this->foo->bar();
    }
}

Decorator design pattern & dependency between components

I have a use case to draw some machine in a CAO software that the user can configure (for example setting the length, if an option has to appear graphically or not, etc.). This is done through the software (Autocad) using dynamic properties, layers or block to show/hide, so with different type of behaviours. The number of possible options vary from one equipment to another, and we often had new parameters to our products.

I started to use the decorator pattern to manage the different parameter of the equipment. My main concern now is that some parameter values are interdependant (I need for example the current value of the current decorator multiplied by the value of another one... that may be wrapped into the first decorator, or that may wrap it).

Do you have any clue if : - What I want to achieve is feasible in the boundaries of the decorator pattern ? - I am totally wrong and should use a different kind of design pattern for my use case ?

Here is some simplified material of my implementation :

My component interface

public interface Component
{
    void Draw();

    void Store();
}

I have a "machine" class that represent the basic information of the machine that is fixed :

public class Machine : Component
{
    public int MachineID { get; set; }

    public void Draw()
    {
        //Do some stuff
    }

    public void Store()
    {
        //Do some stuff
    }
}

An abstract class that represents the parameters:

public abstract class Parameter : Component
{
    internal string ParameterName;
    internal string Value;
    internal Component BaseComponent;

    public Parameter(string _parameterName, string _value, Component _component)
    {
        ParameterName = _parameterName;
        Value = _value;
        BaseComponent = _component;
    }

    public abstract void Draw();

    public void Store()
    {
        //Do store data in the drawing (same procedure for any parameter)
    }
}

And a concrete parameter class :

public class ConcreteParameter : Parameter
{
    internal string SomeAdditionalMember;

    public ConcreteParameter(string _parameterName, string _value, Component _component) : base(_parameterName, _value, _component) { }

    public override void Draw()
    {
        this.BaseComponent.Draw();
        //Draw in a specific way in addition to parent drawing
    }
}

Thanks in advance for any advise on the topic !

Pyside2, How to avoid .parent().parent().parent().parent()

So I have a simple pyside2 app where I want a button to update a counter widget.

The button has been subclassed and has a function that calls the increment function of the counter widget.

Currently call looks like this

self.parent().parent().parent().parent().counter_widget.increment()

This is pretty ugly. How should I make this call between widgets that are are so distant in the class hierarchy.

How should I design Java Classes?

I need to solve a java design problem. I am implementing a generic ConfigurationRetriever which would return the Configurations that user needs.

I have multiple *Configuration objects which need to be auto refreshed based on the user provided time interval. Client should be able to provide the list of Configurations it needs. The retriever should provide ways for the user to retrieve the configurations which are auto updated. How should I design this? Which design pattern is more suitable for this problem?

Here are sample classes.


    class AConfiguration {}

    class BConfiguration {}

    class CConfiguration {}


    class ConfigurationRetriever {


        AConfiguration getAConfiguration() {}

        BConfiguration getBConfiguration() {}

        CConfiguration getCConfiguration() {}

    }

I want to add additional fields in the ConfigurationRetriever class.

long timePeriod; // This indicates hhow frequently configurations should be auto updated.

List<String> configNames; // This indicates which configs should be retrieved. e.g { "AConfiguration", "CConfiguration" }

Based on the timePeriod there will be a ScheduledExecutorService which will keep on updating the configs provided in the configNames list.

How should I go about designing these classes? Which design pattern would be suitable here?

Observer Design Pattern, Concrete Subject Can Expose getData()? [closed]

First-time Target switch on, In My Application, I want to show some data on List, I am Observing for DataUpdate on App, but my Service will push data for every 30sec if My app is up at 15sec, I don't have data to show(instead of showing not data found), can we design observer design pattern in such a way that it can expose getdata()(which contain lease recent data).

so While the app is up I will call getdata() then registerObserver().

Is this is a correct approach?

Chain of Responsibility Pattern - Returning a value/result

I'm trying to implement a Chain of Responsibility solution but I have some doubts about the result/returning value.

I would return a result to the caller to understand the result of the validation done during the Chain.

For example:

public class DataObjectToValidate {}

public class DataObjErrorValidation {}


public class DataObjectValidationResult {

    public Boolean isValidationOK;
    public DataObjErrorValidation;
}

public interface ValidationChain {

    void setNextChain(ValidationChain nextChain);

    void validate(DataObjectToValidate objToValidate);
}


public class Validation1 implements ValidationChain {

    private DispenseChain chain;

    @Override
    public void setNextChain(ValidationChain nextChain) {
        this.chain = nextChain;
    }

    @Override
    public void validate(DataObjectToValidate objToValidate) {

        //Execute the first step validation using objToValidate parameter

        //If the first step validaiton fails, I would return a DataObjectValidationResult obj
        //with the isValidationOK parameter set to false and the DataObjErrorValidation contains
        //the info regarding the failure
        //else I will call the next step
    }
}


public class Validation2 implements ValidationChain {

    private DispenseChain chain;

    @Override
    public void setNextChain(ValidationChain nextChain) {
        this.chain = nextChain;
    }

    @Override
    public void validate(DataObjectToValidate objToValidate) {

        //Execute the second validation step using objToValidate parameter
        //If the second step validaiton fails, I would return a DataObjectValidationResult obj
        //with the isValidationOK parameter set to false and the DataObjErrorValidation contains
        //the info regarding the failure
        //else I will call the next step
    }
}


public class Validator {

    private ValidationChain c1;

    public executeValidation() {

        ValidationChain c1 = new Validation1();
        ValidationChain c2 = new Validation2();

        DataObjectValidationResult objErrorValidation = c1.setNextChain(c2);
    }
}

Using this approach, the caller will receive a DataObjectValidationResult object from the Chain and understand if the validation was successful and which error happened.

What do you think about this approach? Does it make sense or am I violating some rules?

Thanks

Python 3 exception convertion and re-raise

I have the following problem: my application is a bridge between dbus and json-rpc. I have a dbus library that in case of Dbus exception is raising a

DBusException("my err msg") exception.

My json-rpc library is catching all the Exception and convert it to a nice generic server error message

{"jsonrpc": "2.0", "error": {"code": -32000, "message": "Server error"}, "id": 2}

The problem is that i want to handle better those exceptions and I can distinguish between them only using the error message: for example I need to convert the

DBusException("Invalid Parameters")

to

{"jsonrpc": "2.0", "error": {"code": -32001, "message": "Server error", data="Invalid Parameters" }, "id": 2}

that can be done raising in my library an ApiError(msg, code, data) exception.

So summarizing: - I need to catch a DBusException - based on the err_msg I need to switch between different exception types and re-raise a modified ApiError exception

How is the better approach to that? this needs to be done in at least 10 functions that have the same exceptions.

1) using a decorator?

def my_exception_catcher(fun, *args, **kwargv):
    try:
        fun(args, *argv)
    except DBusException as e
        err_msg = str(e)
        if err_msg == "Invalid Arguments":
            raise ApiError("Server Error", code=1, data=err_msg)
        else if err_msg == "Connect Error":
            raise ApiError("Server Error", code=2, data=err_msg)
        else:
            raise

@my_exception_catcher
my_fun(*args):
    do_something

2) using a function to determine the exception type?

def find_my_dbus_error(err_msg):
    if err_msg == "Invalid Arguments":
        return ApiError("Server Error", code=1, data=err_msg)
    else if err_msg == "Connect Error":
        return ApiError("Server Error", code=2, data=err_msg)
    else:
        return Exception(err_msg)

try:
    my_fun(params)
except DBusException as e
    raise find_my_dbus_error(err_msg)

3) something else?

Thanks Nick

Are there any design patters that can only be used for dynamically typed languages and not for statically typed languages?

Since statically typed programming languages do type checking (verifying and enforcing the constraints of types) at compile-time, one has to ensure type consistency at compilation stage itself.

However, for a language like Python, we can leverage different behaviours for different data types at runtime by making use of functions like isinstance()

What I want to know about is has anyone been able to come up with a design patter (even for a specific use case) that is not possible to be implemented in a statically typed programming language?

lundi 27 janvier 2020

php class locator or class routing

I am looking simple way to use class locator for php.

I have developed application that is working for different clients, clients requirements are very similar but with some small differences and exceptions. So code is near the same for all clients, but with some differences to implement that exceptions for each client.

I want to use same base code for all clients, I want to keep it simple but still allow customization for each client. It needs to be easy to maintain and I want to reduce cyclomatic complexity.

Sample, say I have a class A like this:

namespace src;

class A
{
   public function f1()
   {
       // do something  
   }

   public function f2()
   {
       // do something  
   }

   public function F()
   {
       return $this->f1() + $this->f2();
   }
}

Class A implements default behavior or most common used path. For some clients it works.

Other clients need special behavior in one or more of their methods, so my first approach was to use some if inside each method like this

class A
{
   public function f1()
   {
       if (CLIENT === 'peter') {
           // do something for client peter  
       } elseif (CLIENT === 'mary') {
           // do something for client mary  
       } else {
           // default client
       }
   }
}

It works, but I do not like because I have a lot of clients, and become difficult to read, test and maintain, and code for each method becomes very long.

Second approach I tried to extend main class for each client, something like

namespace src\peter;

class A extends \src\A
{
    public function f1()
    {
        // do something for client peter
    }
}

and when I need to use it:

if (CLIENT === 'peter') {
    $className = src\peter\A::class;
} elseif (CLIENT === 'mary') {
    $className = src\mary\A::class;
} else {
   $className = src\A::class;
}

$object = new $className();
$object->f();

It works, it is better, because separates methods implementation for each client on separated class and it looks cleaner, but I still have two problems:

1 - From IDE like phpstorm I cannot navigate code clicking on method or class name, that is because class name now is variable.

2 - I still have that "if" on code.

I am looking for cleaner solution, some way to define current client as CONST in a configuration file and on code I just want to write

$a = new A();

and A, could be src\peter\A; or src\mary\A; depending how I configured it, and if class A is not defined for configured client then default class src\A; should be used.

is possible use some kind of class locator like this?

thanks!

Singleton pattern execute ordering issue

I'm trying to learn singleton design pattern.the code is as follow:

public class Model {

    private static final Model INSTANCE = new Model();

    public static void main(String[] args) {
        Model.getInstance();
    }

    private Model(){
        System.out.println("constructor");
    }

    public static Model getInstance(){

        System.out.println("I hope to be printed first!");
        return INSTANCE;
   }
}

I expect the code to print I hope to be printed first! first, and then go through class constructor. but the code output is reverse :

constructor
I hope to be printed first!

I cant understand why the class is instantiated first?

What are the advantage or disadvantages difference import styles such as module import and * as import

I was wondering and kinda confused as to which style of import should i use, till this moment i came across these imports and i'm not sure which on is faster, or if its worth refactoring my codes to use one of these instead of another one
Type1 :, (very simple, no problem here):

//This is simple and straight forward
import Component from 'Component';

Type2 (This is one of the ones i have some doubt about):

//#definition JavascriptUtils : 
export function a {}
export function b {}
///,2000 more lines

Now this can be used in two ways:

//#usage JavascriptUtils : 
//1-
import * as JavascriptUtils from 'Utils/JavascriptUtils'
//2-
import {a, b} as JavascriptUtils from 'Utils/JavascriptUtils'

Now i'm not sure if there is a difference between 1 or 2 or if there is, should i even care ?, is there that much difference in performance or package size, i do use this utility a lot, so i'd like to know how much advantage way 1 can give me

Type3:

//#definition UIUtils : 
export const UIUtils = {
    a,
    b,
}

export function a {}
export function b {}

//#usage UIUtils
import {UIUtils} from 'Utils/UIUtils'  

Type4:

//#definition UIUtils : 
export const UIUtils = {
    a,
    b,
}

export function a {}
export function b {}

//#definition JSUtils : 
export const JSUtils = {
    c,
    d,
}

export function c {}
export function d {}

//inside utils/index.js
export * from './UIUtils';
export * from './JSUtils';

//#usage UIUtils
import {UIUtils} from 'utils'
import {JSUtils} from 'utils'

So this all the different types of import i used until now, i really like to know which one is the best, which one is faster, which one causes less build size ? or if there is not difference or the difference is small, i'd like to know that as well.
I specially like to know if i'll notice any big difference in build size if i use {a} from import vs * as utils import, my utils are more than 2000 line and are used hundred of times throughout the program Thanks!

Stuck with design pattern choice

I have to design a validating system for reports. Each report contains multiple widgets. The validation checks are simple range and null checks and custom checks. The return type of each widget is different.

User will select one report. Data in all the widgets for the report has to be validated. The final result has to be dumped.

Which report is selected, will be decided on the fly. Please help me find out suitable design patterns. I was thinking to go for factory pattern and decorator pattern. factory pattern for choosing appropriate widgets validation tool and decorator pattern for adding behaviour at run time and sequencing them.

How are Undo / Redo functions implemented in video editing

I was wondering if anyone here had any experience in writing a video software with undo / redo features. I'm asking this out of pure curiosity, which algorithms are suitable for these features, I'd also love it if you have any references with this information.

Thanks in advance!

Extracting private methods to separate class to allow testing

Below is a skeleton Java code that invokes following methods :

  private void applyRule1(List<Data> dl) {
    System.out.println("Apply Rule 1");
  }

  private void applyRule2(List<Data> dl) {
    System.out.println("Apply Rule 2");
  }

  private Boolean isDuplicateType(Data data, List<Data> dl) {
    Set<String> l = dl.stream().map(Data::getType).collect(Collectors.toSet());
    return l.contains(data.getType());
  }

I plan to extract the above 3 methods to a separate interface/class and change their visibility to public. The new interface will be called Rule with the implementation class called RuleImpl. I'll add a new unit test class to test each of the three methods. Is this a good design ? Is there a design pattern that I can make use of that matches the result I wish to achieve ?

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class Main {

  private class Data {

    private String name;
    private String type;

    public Data() {

    }

    public Data(String name, String type) {
      this.name = name;
      this.type = type;
    }

    public String getType() {
      return this.type;
    }

    public List<Data> getData() {
      List<Data> dl = new ArrayList<Data>();
      dl.add(new Data("name1", "type1"));
      dl.add(new Data("name2", "type2"));

      return dl;
    }

  }

  private void process() {
    List<Data> dl = new Data().getData();

    if (!this.isDuplicateType(new Data("name2", "type9"), dl)) {
      this.applyRule1(dl);
      this.applyRule2(dl);
    } else {
      System.out.println("Duplicate found");
    }

    if (!this.isDuplicateType(new Data("name2", "type2"), dl)) {
      this.applyRule1(dl);
      this.applyRule2(dl);
    } else {
      System.out.println("Duplicate found");
    }

  }

  private void applyRule1(List<Data> dl) {
    System.out.println("Apply Rule 1");
  }

  private void applyRule2(List<Data> dl) {
    System.out.println("Apply Rule 2");
  }

  private Boolean isDuplicateType(Data data, List<Data> dl) {
    Set<String> l = dl.stream().map(Data::getType).collect(Collectors.toSet());
    return l.contains(data.getType());
  }

  public static void main(String args[]) {

    Main t = new Main();
    t.process();

  }
}

What is the purpose of nested static class in Builder design pattern? [closed]

I remember reading Effective Java by Joshua Bloch and a builder design pattern described there. However, I forgot what was exactly the purpose of nested static class (Builder). The only thing I can think of is that it doesn't allow creating instances without using the builder. Were there any other advantages?

Implicitly passing client context to services in Node

In node.js I have been trying to find a way to pass client context from the Express routes into the services without every service function to have a context. By context I mean an object with user type, ID, possible queries passed on the request, etc.

I see three possible ways to do this, keep the context as argument of services (already more or less how it is done), refactor all services to only receive the exact data they need (a lot of work and have to take into account that other services might be getting called passing the context) or what I am trying to do, implicitly pass the context object between services with a Service base class like:

class Service {
  call(service, context = null) {
    service._context = context || this._context;
    return service;
  }

  callWith(context) {
    this._context = context || this._context;
    return this;
  }
}

class FooService extends Service {
  constructor(model) {
    this.model = model;
  }

  async foo(bar) {
    // Calls other service and passes the context object to it
    bar.test = await this.call(barService).test(bar);
    return await this.model.foo(bar);
  }
}

// Somewhere else, defining my Express routes:
app.route(`foo/`).get(async (req, res, next) => {
  try {
    const limit = parseInt(req.query.limit, 10);
    const data = await fooService.callWith(req.context)
      .foo({ prop: req.query.property, limit: !isNaN(limit) ? limit : null });
    res.send(data);
  } catch (err) {
    next(err);
  }
});

If there is a nicer clean way to do this would be great to know. Also I am worried that as services are singleton instances somehow it can run asynchronous code while using the wrong context. I know node is single-threaded, but the context property is not async while the methods are and context can change while still resolving a promise on another service.

Any ideas are welcome, thanks.

android cache data or open file each time?

I have an activity in my app that has a recycler view. The recycler view creates items programaticly, dependence on a number of JSON files in the RAW folder. so lets say if I have 5 JSON files in RAW it will create 5 items, if it has 7 then it will create 7 items. the JSON file looks something like that:

{
    "info": {
        "metadata1": "x",
        "metadata2": "y"
    },
    "data": {
        "field1": "a",
        "field2": "b"
    }
}

So, the recycler view only needs the "info" part of the JSON. then when you click an item, you go to another activity that needs alk the "data" part of the JSON. right now what I am doing is every time a user enters the recycler view it open and reads all the raw files, every time, and then when the user enters to the specific item it opens and reads the specific json every time.

I think it causes a lot of overhead to the system and a waste of read/open actions, so I thought I should use some kind of cache mechanism to load only one time all the JSON files at the beginning, but then on the other hand, I also think it will use too much memory during runtime.

what is the best way to design this thing and is there a way to use a cache mechanism?

dimanche 26 janvier 2020

Is it better to add a conditional inside or outside of a for loop for cleaner code?

So this may sound simple, but I have a method that has a for loop inside, inside the forloop the method createprints needs a map of "parameters" which it gets from getParameters, now there are 2 types of reports, one has a general set of parameters and another has that general set and a set of its own.

I have two options:

Either have 2 getparameters method, one that is general and another that is for rp2 but also calls the general parameters method. If I do this then it would make sense to add the conditional before the for loop like this :

    theMethod(){

        if (rp1){
            for loop{
                createPrints(getgenParameters())
                do general forloop stuff 
           }
        }else{
              for loop{
                createPrints(getParameters())
                do general forloop stuff
                }
        }
    }

This way it only checks once which parameters method to call instead of having the if statement inside the loop so that it checks every iteration (this is bad because the report type will never change throughout the loop) but then this way, repeating the for loop looks ugly and not clean at all, is there a cleaner way to design this?

The other option is to pass in a boolean to the get parameters method and basically you check inside which type of report it is and based on that you create the map, this however adds a conditional at each iteration as well.

From a performance perspective, it makes sense to have the conditional outside the loop so that its not redundantly checked at each iteration, but it doesnt look clean, and my boss really cares about how clean code looks, he didnt like me using an if else code block instead of doing it with ternary operators since ternary only uses one line (i think performance is still the same no?).

Design Patterns Confusion

Visitor Pattern vs Observer Pattern vs Factory Pattern vs Decorator Pattern Can somebody give me 4 examples using JAVA distinguishing all 4 of them ? so that it is easier to understand them. It is because I kind of confuse up between Factory and Decorator and similarly with Visitor and Observer . Thank you

Communicate between View Models in MVVM

I am using MVVM pattern in my project. Here is the pseudo code.

class ViewModelA {
     propertyA;
     methodA(); // updates propertyA
}

class ViewModelB {
     methodB() {
     // update properties of ViewModelB
     // Needs to update propertyA of ViewModelA
     }
}

I have two view models ViewModelA and ViewModelB. MethodB of ViewModelB needs to update propertyA of ViewModelA.

I can keep a reference of an instance of ViewModelA inside ViewModelB and call methodA to update propertyA of ViewModelA. Is it a good practice to keep a reference of one view model inside another view model in MVVM pattern? Also, would like to know other ways in which View models can update properties of other view models.

Generic object with builder pattern

I have a Producer<?, ?> producer field in my class, which implementation depends on a given state using a builder pattern, for example:

private void changeImplementation(int state) {
    switch (state) {
        case 0:
            producer = builder
                           .setKey(Long.class)
                           .setValue(String.class)
                           .setOtherStuff(...)
                           .build() // return the object with correct key and value
        break;
        case 1:
            ...
}

But whenever I call a method on producer (for example with types Producer<Long, String>), this error is given (Eclipse EE):

The method method(Record<capture#9-of ?,capture#10-of ?>) in the type Producer<capture#9-of ?,capture#10-of ?> is not applicable for the arguments (Record<Long,String>)

Making a cast before build() or inside the method call didn't help. The build pattern works perfectly elsewhere in the project.

samedi 25 janvier 2020

Is it a good practice to send schema in web application?

I want to build a web app (SPA) that send the schema (not necessarily the raw db schema, but a representation of the data potentially in a JSON format) to the view, so in the view we can:

  1. Generate grids based on that schema instead of wiring columns
  2. Handle additional information from these fields, such as if it is editable or not, and the like.

This web app will allow users to see tabular information in a grid, and potentially do CRUD operations.

I see a lot of benefits on using the schema (We can implement validators based on the schema, forms generation should be very simple, and best, the impact of adding a simple field to the web app should be easily handled)

My question is: Is it a good strategy? Could you help me identify some drawbacks with this approach? (The stack I am using for this is not very important, but just for the sake of clarity, I am using Bottle in the backend, and React in frontend)

Destructor is not called in Factory Pattern [duplicate]

I am learning factory design pattern and this is how I have implemented in C++. CVehicle is abstract class having interface createVehical to create actual object of specific type. CVehicalBookingHandler is client code which will be exposed and needs not to be modified, it will also delete actual vehicle object in it's destructor. But when its destructor is called to delete actual objects, their destructors are not called. How can I fix it??


#include<iostream>

using namespace std;

enum EVehicleType{
    VT_Bus, VT_Train, VT_Flight 
};

class CVehical{
public:
    virtual bool Book()=0;
    static CVehical* createVehical(EVehicleType vehicleType);
};

class CBus:public CVehical{
public:
    bool Book(){
        cout<<"Bus is booked!"<<endl;
        return true;
    }
    ~CBus(){
        cout<<"CBus deleted"<<endl;
    }
};

class CTrain:public CVehical{
public:
    bool Book(){
        cout<<"Train is booked!"<<endl;
        return true;
    }
    ~CTrain(){
        cout<<"Train deleted"<<endl;
    }
};

class CFlight:public CVehical{
public:
    bool Book(){
        cout<<"Flight is booked!"<<endl;
        return true;
    }
    ~CFlight(){
        cout<<"Flight deleted"<<endl;
    }
};

CVehical* CVehical::createVehical(EVehicleType vehicleType){

    if(VT_Bus == vehicleType){
        return new CBus();
    }
    else if(VT_Train == vehicleType){
        return new CTrain();
    }
    else if(VT_Flight == vehicleType){
        return new CFlight();
    }
    else{
        return NULL;
    }
}


class CVehicalBookingHandler{
private:
    CVehical* vehicle;
    EVehicleType eVehicleType;

public:
    CVehicalBookingHandler(EVehicleType eVehicleType):eVehicleType(eVehicleType){
        vehicle=CVehical::createVehical(eVehicleType);
    }
    ~CVehicalBookingHandler(){
        if(vehicle){
            delete vehicle;
            vehicle=NULL  ;
        }
    }
    CVehical* getVehicle(){
        return vehicle;
    }

    EVehicleType getVehicleType(){
        return eVehicleType;
    }
};


int main(){
    CVehicalBookingHandler busBookingHandler(VT_Bus);
    CVehical* vehicle=busBookingHandler.getVehicle();
    vehicle->Book();

    CVehicalBookingHandler trainBookingHandler(VT_Train);
    vehicle=trainBookingHandler.getVehicle();
    vehicle->Book();

    CVehicalBookingHandler flightBookingHandler(VT_Flight);
    vehicle=flightBookingHandler.getVehicle();
    vehicle->Book();
}

output:

Bus is booked!

Train is booked!

Flight is booked!

Java design pattern for two classes sharing identical and similar but different methods

Let's say my application has some services implemented as ClassA and ClassB. Both have some similarities but also differences.

  1. Both classes have a start() method with the same method signature but a different implementation.
  2. Both classes have a process() method with a different signature and a different implementation.
  3. Both classes have an identical log() method, i.e. the code is exactly the same.

Class A

public class ClassA {

    public String start(String s1, String s2) {
        startImplementation();
        return someString;
    }

    public String process(String s) {
        processingImplementation();
        return processedString;
    }

    private String log(String s) {
        logImplementation();
        return sharedString;
    }
}

Class B

public class ClassB {

    public String start(String s1, String s2) {
        otherStartImplementation();
        return someString;
    }

    public String process(Long l) {
        otherProcessingImplementation();
        return processedString;
    }


    private String log(String s) {
        logImplementation();
        return sharedString;
    }
}

I'm having trouble thinking of a "design pattern" how I could organize this in a more generic way. As of 3. I could easily move this method to a superclass which ClassA and ClassB extend. But how would/could I design the application so that 1. and 2. are also taken into account?

Item 1. sounds a little bit like an interface to me but I don't have any idea how this could be combined with the superclass for item 3. And what about item 2?

Spring boot Design Patterns and SSR vs REST api got a few questions

i would like to ask a few questions about building spring boot 2 applications.So few months ago i decided to start building basic blog app with spring boot and angular, I've made a few entities, rest controllers for users, roles, articles, categories and comments, made a service and service implementation for each, for example my UserServiceImpl looked like this using HQL, not repositories.

@Override
    public List<User> getUsers() {
        Query q = entityManager.createQuery("select u from User u");
        List<User> users = q.getResultList();

        if(users == null){
            users = new ArrayList<>();
        }

        return users;
    }

Is this the right way to do it? Do i have to build it like that ,because I didn't used any repo's and every spring-boot-best-practices project I saw was using repositories instead of HQL and I'm not really sure should i use repositories or custom services with HQL. I am totally lost with that.This is my first question.

The second question is should I use server side rendering and api or i should use only api without server side rendering, because i saw a few projects made with ssr and rest api's which confused me a lot.

Thanks for the help provided

Best design pattern for the scenario

I have a scenario where I am using an interface implementation like

interface Sorter {
   public void sort(A a, B b){}
}

and then there are several implementation of the classes like

class RankSorter extends Sorter {
    public void sort(A a, B b) {
        // use a alone to sort 
    }
}
class WeightSorter extends Sorter {
    public void sort(A a, B b) {
        // use a alone to sort 
    }
}

and some more classes where we use only the value of a alone for the sort and finally one class like below where we use both a and b.

class MultiSorter extends Sorter {
    public void sort(A a, B b) {
         // use both a and b for the sort operation
    }
}

So my concern here is the value of b is passed to all of the sorters even though it's used only on one sorting class.

Is this the correct approach or is there a better approach ?

vendredi 24 janvier 2020

React Component Getting To Big

I am starting to notice a potential problem with the way I am structuring my React application.

I like to architect my components by having one file that acts as a container and multiple stateless components that get passed data and event emitters via props. This container will contain all the state, API Calls, and event handlers. This container will render child components that are stateless.

Here is an example of a structure I use:

- folder
  - index.js <-- container file
  - childComponent1.js
  - childComponent2.js
  - childComponent3.js
  - childComponent4.js
  ...

The size of container file and the number of child components depends on how big a feature is. The problem I had recently was that there was a very big feature that I had to implement, and while I like to use this structure, I started to realize that my container file got very big, like almost 1000 lines of code big. Now, I'm not sure if this is an issue, but seeing 1000 lines of code in one file concerns me. There is just a lot of state to keep track as well as event handlers to read/set new state.

I'm wondering if there are tips on any workaround on this or if there is a different design pattern that I can try and experiment with. Any answer is acceptable!

Thank you!

What are some software architecture/design techniques for calling a method on a subset of list items?

Imagine I have the following interfaces:

public interface IEntity {...}
public interface IFreezable {...}
public interface IBurnable {...}

Let's also imagine I have a few classes:

public class Tree : IEntity, IBurnable {...}
public class Monster : IEntity, IFreezable {...}

Finally, let's say somewhere in my code I have a list of entities:

List<IEntity> entities = ...;

Let's say I would like to go through that list, calling IFreezable.Freeze(...) on items that implement IFreezable. I'm trying to employ interface segregation to keep different types of IEntities from having to implement methods they don't need/use.

What are some ways I could approach this and what are the trade-offs? I could use casting, but I have generally read that type checks and casting could be a sign you're approaching the problem the wrong way, so I wanted to get different perspectives.

I am having trouble trying to solve a moving Car coordinate problem in C#, but java will be fine for me to understand as well [closed]

Here is a screenshot of what I have

I was given this problem, and have so far started trying to solve it, however I am stuck as to how to go about solving it, and Applying Design Pattern concepts to it. The problem wants user input of F,F,R,L,F,R,F to result in the output of (1,3)E coordinates. The picture below shows a graph table of coordinates, and based on the console input for the vehicle, it will either move forward, right, or left, which will change its coordinates. The screenshot also has conditions as to how the input should be validated.

Here is the Problem

System design pattern for recurring payments

I'd like to ask what are some common, widely adopted patterns to design a system which auto-renew user's subscription when it expires.

I'm specifically asking how to trigger that operation?

Assume there's a system, with some RenewSubscription method that do the all logic. The method should be triggered just after user's subscription expired.

The only way I see to implement it is to have some kind of background task (console app or lambda) that query DB every N seconds (or minutes) and checks if there is any expired subscription to renew.

Can this be implemented without querying DB every few seconds?

How to improve factory approach to be able to register dependencies in a right way

I need a code refactoring advice. I have a class which contains several dependencies. I will just provide a constructor, but this should be enough. The class implements this interface:

public interface ITopicPublisher<T> {} 

and the class itself:

public class TopicPublisher<T> : ITopicPublisher<T>
{
    public TopicPublisher(IEventGridClient eventGridClient, string topicEndpoint) { ... }
}

Now, the instance of this class is injected to the Controllers like this:

public class SomeController : Controller
{
     public SomeController(ITopicPublisher<MyEntity> publisher) { ... }
}

in order to create EventGridClient, I need to construct it like this (where key is a simple string):

new EventGridClient(new TopicCredentials(key))

Now, the topicEndpoint and key are taken from Environment.GetEnvironmentVariable(...). It all now is problematic when registering dependencies in ASP.NET (2.2) Startup.cs.

builder.Services
    .AddScoped(x => new TopicPublisher<MyEntity>(new EventGridClient(
        new TopicCredentials(Environment.GetEnvironmentVariable("KEY"))),
        Environment.GetEnvironmentVariable("ENDPOINT")))

I didn't like it, so I created a factory, like this:

public class EnvironmentVariableTopicPublisherFactory
{
    public static ITopicPublisher<T> Create<T>(string topicUrlEnvironmentVariable, string keyEnvironmentVariable) where T : class =>
        new TopicPublisher<T>(new EventGridClient(new TopicCredentials(Environment.GetEnvironmentVariable(keyEnvironmentVariable))), 
            Environment.GetEnvironmentVariable(topicUrlEnvironmentVariable));
}

and now the registration process seem to be a little more simple:

builder.Services
    .AddScoped(x => EnvironmentVariableTopicPublisherFactory.Create<MyEntity>("ENDPOINT", "KEY"))

I have some concerns however, that I could do it better. Could you give me some hint, how this approach can be made more clean, if this is possible?

Regexp pattern conditional extract [closed]

Imagine that we have string "-test". How to define pattern that will extract '-' to let say prefix property and rest of string to suffix property. Pattern should match also strings that don't start with '-' sign. In that case prefix property should be empty.

Best regards.

Which design pattern fits best to avoid multiple parameters in method

I have the following class:

public class SomeAssebler {

    private EnrichedRequest assembleBasicEnrichedRequest(BasicRequest request) {
        EnrichedRequest enrichedRequest = new EnrichedRequest();
        if (request != null) {
            enrichedRequest.setId(request.getId());
            enrichedRequest.setDate(request.getDate());
            enrichedRequest.setParam(request.getParam());
        }
        return enrichedRequest;
    }

    private static EnrichedRequest assembleGeoDataEnrichedRequest(EnrichedRequest request, GeoData geoData) {
        EnrichedRequest geoEnrichedRequest = Optional.ofNullable(request).orElse(new EnrichedRequest());
        if (geoData != null) {
            geoEnrichedRequest.setCity(geoData.getCity());
            geoEnrichedRequest.setCountryCode(geoData.getCountryCode());
        }
        return geoEnrichedRequest;
    }

    private static EnrichedRequest assembleUserAgentEnrichedRequest(EnrichedRequest request, UserAgentData userAgentData) {
        EnrichedRequest userAgentEnrichedRequest = Optional.ofNullable(request).orElse(new EnrichedRequest());
        if (userAgentData != null) {
            userAgentEnrichedRequest.setBrowser(userAgentData.getBrowserCode());
            userAgentEnrichedRequest.setOperatingSystem(userAgentData.getOsCode());
            userAgentEnrichedRequest.setManufacturer(userAgentData.getBrand());
        }
    }

    public static EnrichedRequest assembleEnrichedRequest(BasicRequest request, GeoData geoData, UserAgentData userAgentData) {
        EnrichedRequest enrichedRequest = assembleBasicEnrichedRequest(request);
        enrichedRequest = assembleGeoDataEnrichedRequest(enrichedRequest, geoData);
        enrichedRequest = assembleUserAgentEnrichedRequest(enrichedRequest, userAgentData);
        return enrichedRequest;
    }
}

It is then called in different transformers: In the GeoDataTransformer

new KeyValue<>(key, assembleEnrichedRequest(basicRequest, geoData, null))

In the UserAgentTransformer:

new KeyValue<>(key, assembleEnrichedRequest(enrichedRequest, null, userAgent))

If more "enrichers" will be added in the future this can get very ugly. Anyone has an idea how I can design this better? I though of the Builder design pattern but I'm not sure.

jeudi 23 janvier 2020

Ways to share common data in Android app?

How to share state/data across several Activities and all parts of application?

I have found few ways to achieve this after some research:

  1. Class with data (for example POJO that contains user data) to share must become Singleton and is called like this:
class MyActivity extends Activity {
  ...

@Override
public void onCreate(...){
  super.onCreate();
  // user is initialised somewhere else  
  final User user = User.instance();
  final String username = user.name();
}
  1. Class with data becomes static member of Application class
class App extends Application { 
  private static User sUser;

  public static User currentUser() {
    return sUser;
  }

//usage:
...
final User user= App.currentUser();
...
  1. Class with data becomes field of Application class
class App extends Application { 
  private User sUser;

  public User currentUser() {
    return sUser;
  }

//usage:
...
final User user= ((App)getApplicationContext()).currentUser();
...
  1. Class with data is injected using some DI framework (Dagger, Koin, etc.)
  2. I have created apps using React Native and Redux architecture, so I think Redux can be used in Android somehow too?

Which way do you prefer? What are the pros and cons of each way above?
Thank you for your feedback!

Return two different data types based on condition from the same method

Looking for the best strategy to handle a method returns two different data types based on condition

public Response find(int id) {

Student std = studentService.findOne(empId):

if(std == null)
    return new ErrorResponse(errorCode);
else
   return new SuccessResponse(std);  

}

One condition is like I cannot implement an Interface for ErrorResponse or SuccessResponse.

Another condition is like I cannot have a parent class for this.

These classes are dynamically generated classes by other Clients

Inheritance depending on calculated attribute

I am curently working on a small project (C#) where I have data to analyse. To do so, I pass the data into the constructor of a class.

The class makes a first analysis on the data, and a certain value is determined using the data. Using this value I can say that this data is of Type B, C, D, ... and the analysis would continue in another class corresponding to the data type.

This would be it's class diagram representation :

enter image description here

So the "Data" Class should abstract but not really ? ¯\_(ツ)_/¯

I did some reasearch about the factory design pattern, but I think this is not really what I am trying to achieve. Is there maybe an other design pattern that does what I want to do?

Thank you for helping.

Where is the better place for a function used on a lot of controllers using VIPER?

I'm using VIPER pattern into my Swift app. I need a function that is executed in a lot of controllers to open an cardViewStyle. I don't know where is the better place to add this function...

Could be a useCase? An Interactor?, common... Without forgot VIPER and clean architecture

Now the function is into view controller, into presenter and wireframe... because is called only one time.

The function would be like:

//Presenter
func showLikeCard(controller: UIViewController){ 
     wireframe.showLikeCard(controller: controller)
}

//Wireframe
func showLikeCard(controller: UIViewController){ 
     controller.present()
}

Thanks!

Android and design patterns good practices

I am designing an app on Android but I realised that I cannot implement certain design patterns such as Visitor i.e. So I was wondering if "creating my own structure" is a good practice. What I mean by creating my own structure is making a class of mine inherit from an "Android class" just like this. And, in this case, use MyImageButton as my "top" class instead of ImageButton (Of course that in this case a visitor would be useless, I used it just for the demonstration).

If this is not a good practice, what can I do to implement this kind of design patterns? Thank you.

Advanced Java RegEx and Pattern matching

private static final String MY_MATCH = "(.+)/my_path/my_file[.](.+)";

The above is working as expected.

However, if my_path is determinable during run-time, does there exist a pre-existing method that "allows" static final? e.g. Maybe similar to Perl run-time code eval.

My solution(pseudo-code):

private static final String MY_MATCH = "(.+)/[unknown_path]/my_file[.](.+)";

static method (String my_path) {
//local var
String my_match = MY_MATCH;
my_match.replace("[unknown_path]", my_path));
Pattern my_pattern = Pattern.compile(my_match);
}

I feel uneasy with the string replace, but I do not see any other solution.

Laravel listener event doesn't work at server

For some reasons Listener not worked. I made 3 Log points - at controller,at event and at listener. "Fire event" point and "Event file" are ok, but "Send SMS" dont work. What it can be?

Listener

$user = User::find($event->userId);
    if (!is_null($user->phone_verified_at)) {
        Log::info('Send SMS', (array) $user);
        PhoneSms::sendSMS($user->phone, trans(config('sms.'.$event->type)), true);
    }

Event

public function __construct($userId, $type)
{
    Log::info('Event file', (array) $userId);
    $this->userId = $userId;
    $this->type = $type;
}

Controller

Log::info('Fire event', (array) $user);
event(new UserDataChanged($user_id, 'not_success_enter'));

Testing rules for lots of combinations

I need an advice on a system design for a game. There are heroes and there are bonuses. Bonuses can be applied to the heroes. There are also rules like: If bonus B applied to hero H, then .... There are no rules for each and every combination hero-bonus, let's assume there is 50% of such combinations covered. If no rule specified, nothing happens.

Assuming there are 100 bonuses and 100 heroes, what is the best approach to design such system? I believe having each relation test gives much flexibility, but it is not the best from code readability and maintenance perspective. Also, if I am going to add either hero, or bonus, it will become a huge piece of refactoring.

Any ideas?

SQL Pattern name of using multiple tables and referencing with ID

I'm looking for a name of the following pattern:

Let's say, you have a database table with a price and the amount of purchased goods. You want to calculate and save the overall price. You could save the price directly in the original table. But I I learned it is good practise to create a different table and reference the price table by ID.

For my thesis I need to cite and explain this pattern. However, I don't know which name to look for. Can you give me a hint?

enter image description here

Event sourcing, CQRS with Axon Server / Framework - Event Sourcing the entire application a good idea?

This question is very loosely related to Axon Server / Framework, since I'm learning it specifically while studying and trying to get into learning how to build microservices. Since it's difficult to learn about all the architectural patterns without actual hands on experience (and difficult to get hands on experience to begin with without a large application to actually test/build with), I'm theorizing a lot here (my questions might just be plain stupid, sorry, I'm still learning).

I downloaded Axon Server and successfully built and ran the included giftcard demo in three separate microservices. It works great, I see the events and all that on the Axon Dashboard, but I can't help but think about the "what ifs" of if I really built a very large enterprise application.

Consider this :

I'm building a streaming platform like Twitch. There are the basic, obvious services such as Customer service with its profile data, an order service (for subscriptions, donations), etc.

But there are other services such as the chat system. Hypothetically, I feel like event sourcing a chat system would be pretty beneficial, because you would have timestamps built in for replaying the chat if viewers are watching a VOD. However, I also feel like I shouldn't be mixing events for a chat system with an event store that deals with transactions; the two are completely separate systems and just storing every event from every service in a single event store feels... Monolithic?

I'm still unclear what the best practices are. All the samples and examples from talks always show very simplistic systems with the typical Customer, Order, Item aggregates and doesn't go into detail how this simple application would grow to a large service like Twitch.

So my questions are,

1) Should you event source an entire application, or can you choose which ones to event source and not?

2) Does Axon Server support two different event stores, such as one for a chat system and one for other services? Would I just run two different instances of Axon Server in this case? Should an application ever have two different event stores, or do I dump every event into a single event store, regardless of if something like a chat system sending far more events than anything else (would event sourcing a chat system even be a good idea, given the use case that I specified where viewers might want to "replay" the chat log?)?

3) The whole idea of a single event store being the single source of truth feels monolithic. Am I wrong in thinking this, and if I'm not, what are the ways to circumvent this if I had a really large application?

Software Architecture Design

We will start a new project and need to make architecture design decision. The architecture is basically Domain driven architecture. Our layers : App.Entities, App.Common, App.UI, App.BLL, App.DAL. We have our interfaces in BLL layer. We need to know what is the optimal way to locate interfaces in application. I mean, is it ideal interface contracts to be in App.BLL layer with implementations? Or is it better to be in seperate App.BLLContract layer. Do you have any suggestions and what is the reason for it?

mercredi 22 janvier 2020

How to design class property containing a collection of translations? For patterns gurus

I am design pattern newbie, please help to properly organize classes.

My entity has a property 'name' that should have several translations:

class Entity {
   private int id;
   private TranslationCollection name;
   ...
}

'name' - should contain a set of translations:

{
  'en': 'english word',
  'sp': 'spanish word',
  ... 
}

So I decided to make class 'Translation':

class Translation {
  private string locale;
  private string value;
  public constructor (locale, value) { ... }
  ...
}

and class 'TranslationCollection':

class TranslationCollection {
   private translationArray[];
   public constructor() { 
     this.translationArray = new array() 
   }
   public addTranslation(Translation translation) {
      translationArray.push(translation);
   }
   ...
}

and there is requirements:

1 locales could be only from 'listOfLocales' which is available only at runtime.
2 Translation collection could not have repeating locales.
3 Unit testable.

Is it normal to inject 'listOfLocales' into 'Translation' constructor to check locale is in the list? In that case I will have three parameters in 'Translation' constructor. And I think it is not good design.

Or should I have some 'TranslationFactory' with 'listOfLocales' injected in the constructor to create Translation with proper locale?

Or may be I am on the wrong way, and there is a better solution?

An how to organize check that 'TranslationCollection' has no repeating locales? Should I check in addTranslation method that there is no array items with locations matching new Translation.location programmatically, which seems not best solution. Is it a way to organize non repeating collection more declaratively?

Program for this number pattern using for loop in java 1 22 3 4444 5 666666 7 88888888. Not getting the desired pattern

public static void main(String[] args) {
   int noOfRows = 8;

    printPattern(noOfRows);
}

private static void printPattern(int num){
    for(int i = 1; i <= num; i++){
        for(int j = 1; j<=i;j++){
            System.out.print(i);
        }            
        System.out.println();            
    }        

Program for this number pattern using for loop in java 1 22 3 4444 5 666666 7 88888888. Not getting the desired pattern

What is the best practice to avoid putting an "initialize" method in an interface for a data service?

I have an interface for a data service and object repositories in my domain layer, but as I write the implementation for these interfaces, I find that I am needing an "initialize" or "fill" method in the case of an XmlDataService implementation. I need to read the xml, then "load" the repositories from the xml. This feels a lot like a leaky abstraction. What is the best practice here or I am way off base?

My Interface:

public interface IDataService
{
    event EventHandler<string> StatusUpdated;
    IRepository<Points.Core.Point> GetPoints();
    ...

    void Fill();
    Task FillAsync();
}

XmlDataService implementation:

    public class XmlDataService : IDataService
{
    public event EventHandler<string> StatusUpdated;
    public void OnStatusUpdate(string s) => StatusUpdated?.Invoke(this, s);

    public IRepository<Point> GetPoints() => _pointsRepo;
    ...

    public void Fill()
    {
        using (var ds = new DataSet())
        {
            OnStatusUpdate("Reading dataset...");
            ds.ReadXml(_reader, XmlReadMode.ReadSchema);
            ds.EnforceConstraints = false;
            OnStatusUpdate("Loading points...");                
            _pointsRepo.Initialize(ds);
            ...
        }
    }

    public XmlDataService(XmlReader xmlReader)
    {
        _reader = xmlReader ?? throw new ArgumentNullException("xmlReader");
        //instantiate repos
        _pointsRepo = new PointsRepository();
        ...
    }
}

Is there a more functional implementation of this Writable Stream using RxJS that waits for a promise to resolve before processing?

I've been living under a rock for a few years so I haven't touched RxJS yet and I'm curious how it handles a situation like below.

const {Readable, Writable} = require('stream')

class DelayedStream extends Writable {
  constructor(options = {}){
    options.objectMode = true;
    super(options);

    this.promise = new Promise((resolve, reject) => {
      // open connection
      setTimeout( function() {
        console.log('resolved')
        resolve('with client')
      }, 2000) 
    }) 
  }
  _write = function(chunk, encoding, done){
    console.log(`_write("${chunk}") called`)
    // waiting for connection.
    this.promise.then((client) => {
      console.log(`processing "${chunk}"`)
      done() 
    });
  }
  _final = function(done) { //...close connection }
}

var readable = Readable.from(['one', 'two', 'three'])
var test = new DelayedStream();
readable.pipe(test)

The usage of the above is for a scenario where I am waiting for a connection to establish before processing the incoming Readable stream.

I'm not fond of having to create a new class that handles this but it works. It seems like a more functional approach would be optimal but RxJS is lower on my list of things to learn coming back to dev after a very, very long hiatus..

Thanks!