lundi 31 mai 2021

Thinking in SOLID principle during the design process

I'm new to SOLID principle and design, I understand the principle however, I have a hard time knowing where to start the design process. I understand that design is an iterative process, what step or question you ask yourself during the design process so your design conforms to SOLID.

Composition or Inheritance for classes with almost similar implementations but different input and outputs for methods?

I have the following classes, which have quite similar method implementations. Only the classes' method inputs and outputs seem to be of different types. When I put it like this, it sounds like a case for inheritance, however, the fact that the inputs and outputs are different and are related to two lambdas, make me wonder if they should remain without any relationship, as one lambda cannot be thought of in place of another (To be a case for inheritance).

My first class looks like the following.

public class JobPersistenceManager {
    private String jobIndexName;
    private JobLambda JobLambda;
    private MyDataPersistence myDataPersistence;
    private DataProcessorUtils dataProcessorUtils;
    private static final String JOB_ID = "jobId";
    private static final String JOB_NAME = "jobName";

    @Inject
    public JobPersistenceManager(String jobIndexName,
                                 JobLambda JobLambda,
                                 MyDataPersistence myDataPersistence) {
        this.jobIndexName = jobIndexName;
        this.JobLambda = JobLambda;
        this.myDataPersistence = myDataPersistence;
        createIndexIfNotExists(this.jobIndexName);
    }

    public SearchDocumentResult searchJob(MyJobInput myJobInput) throws IOException {
        return myDataPersistence
                .searchDocument(this.jobIndexName,
                        dataProcessorUtils.transformObjectDataPayloadToMap(myJobInput));
    }

    public MyJobOutput invokeCreateJobLambdaAndIndexData(final MyJobInput myJobInput)
            throws IOException {
        String personRequestPayload = dataProcessorUtils.transformObjectDataInputJson(myJobInput);
        Map<String, String> createdJobOutput = this.JobLambda.invokeLambda(personRequestPayload);
        this.indexCreatedJob(myJobInput, createdPersonOutput);
        return MyJobOutput.builder().withJobID(createdJobOutput.get(JOB_ID))
                .withJobName(createdJobOutput.get(JOB_NAME)).build();
    }

    public int indexCreatedJob(final MyJobInput myJobInput,
                               final Map<String, String> createdJobOutput) throws IOException {
        myJobInput = modifyJobInput(myJobInput);
        String documentToIndex = dataProcessorUtils.transformObjectDataInputJson(myJobInput);
        return myDataPersistence.indexDocument(this.jobIndexName, documentToIndex);
    }

    private void createIndexIfNotExists(final String indexName) {
        if (!myDataPersistence.doesIndexExist(indexName)) {
            myDataPersistence.createIndex(CreateIndexInput.builder().indexName(indexName).build());
        }
    }
}

My second class looks like the following.

public class EmployeePersistenceManager {
    private EmployeeLambda employeeLambda;
    private MyTestDataPersistence myTestDataPersistence;
    private DataProcessorUtils dataProcessorUtils;
    private String employeeIndexName;
    private static final String PERSON_ID_KEY = "personId";
    private static final String PERSON_NAME_KEY = "personName";

    @Inject
    public EmployeePersistenceManager(String employeeIndexName,
                                    EmployeeLambda employeeLambda,
                                    MyTestDataPersistence myTestDataPersistence,
                                    DataProcessorUtils dataProcessorUtils) {
        this.employeeIndexName = employeeIndexName;
        this.employeeLambda = employeeLambda;
        this.myTestDataPersistence = myTestDataPersistence;
        this.dataProcessorUtils = dataProcessorUtils;
        createIndexIfNotExists(employeeIndexName);
    }

    public SearchDocumentResult searchPerson(EmployeeInput employeeInput) throws IOException {
        return myTestDataPersistence
                .searchDocument(employeeIndexName,
                        dataProcessorUtils.transformObjectDataPayloadToMap(employeeInput));
    }

    public EmployeeOutput invokeCreatePersonLambdaAndIndexData(final EmployeeInput employeeInput)
            throws IOException {
        String personRequestPayload = dataProcessorUtils.transformObjectDataInputJson(employeeInput);
        Map<String, String> createdPersonOutput = this.employeeLambda.invokeLambda(personRequestPayload);
        this.indexCreatedEmployee(employeeInput, createdPersonOutput);
        return EmployeeOutput.builder().withPersonId(createdPersonOutput.get(PERSON_ID_KEY))
                .withPersonName(createdPersonOutput.get(PERSON_NAME_KEY)).build();
    }

    public int indexCreatedEmployee(final EmployeeInput employeeInput,
                                  final Map<String, String> createdPersonOutput) throws IOException {
        employeeInput = modifyEmployeeInput(employeeInput);
        String documentToIndex = dataProcessorUtils.transformObjectDataInputJson(employeeInput);
        return myTestDataPersistence.indexDocument(this.employeeIndexName, documentToIndex);
    }

    public Map.Entry<String, Map<String, String>> invokeLambda(final String payload) {
        return new AbstractMap.SimpleEntry<>(payload, this.employeeLambda.invokeLambda(payload));
    }

    private void createIndexIfNotExists(final String indexName) {
        if (!myTestDataPersistence.doesIndexExist(indexName)) {
            myTestDataPersistence.createIndex(CreateIndexInput.builder().indexName(indexName).build());
        }
    }
}

As you can see, the methods perform almost the same actions. Only the indexCreatedEmployee and indexCreatedJob methods from the classes have an extra step of processing the input.

Should I keep these classes as they are now without any relationships between them, or should I create an abstract persistence manager class and perform the following.

Move createIndexIfNotExists to the abstract class Create abstract methods search(), invokeLambda() and indexCreatedData() methods and implement them in each child class. The data types MyJobInput and MyEmployeeInput are POJO classes that don't have any relationship. So I guess these methods I mentioned would then take "Object" parameters? EmployeeLambda and JobLambda are again classes with no relationship between them. Another concern I had towards creating some sort of inheritance was that, Employee Lambda and JobLambda cannot be used inter-changeably. So was wondering if they should inherit the same parent class just because they're both lambda classes.

OR is there another way to go about this? Any advice would be much appreciated. Thank you very much in advance.

PHP - Design Pattern to a complex validation

What is the recommended design pattern or methodology to make multiple validations where the parameter can have different structures? Ex:

// Case A:
$toValidate = ["test" => 1]
$toValidate["test"] > 0 // First Validation
$toValidate["test"] === $x // Second Validation

// Case B:
$toValidate = [["test": 1], ["test": 2]]
$toValidate[0]["test"] === 1 && $toValidate[1]["test"] === 2 // First collection item validation...

I've made some tests with the Chain Of Responsibility, but i didn't think fluid for this case. Some alternative?

Better design pattern for implementing ever changing components

Background: The product has the following classes (entities):

  1. Module
  2. Department
  3. Layout
  4. Field

The relationships goes like this:

  • Module can be department specific or not.
  • Module has layout.
  • Layout has Fields.
  • Fields can be of many types. (Number, Line, DropDown, etc.)
  • Fields are module specific. That means field and layouts of module has many to many relationship.
  • Fields normally have module specific properties which clients use via one api.
  • There is another api that renders layouts and their corresponding fields. These have few extra details (like whether the field is mandatory in the module or not, etc.)

Problem: I need to refactor this entire sub system into proper design and make proper classes such that it solves our current use case and also for future use cases.

Currently, we have two classes for fields. One to show only module specific details and type specific details. Another that shows these along with layout specific details.

I don't want to duplicate this much of code. So, I have came up with 2 solutions:

  • Make an abstract class for fields which contains all the properties common to all field types. Then for each field type, create a new field. In this way, new types can be added easily. Also keep a bunch of interfaces as strategies - LayoutProperties, License, etc. This approach looks good but feels like slowly the abstract class will turn into god class.
  • Similar to above. Create abstract classes and put common details. And create different class for sub classes. But Create a separate interface like LayoutDetails. Each field type is then again extended to create a new field which also has layout related properties.

Both approach seem to be workable but doesn't seem clean to me. Can anyone advise on whether I am on the right track or I am missing any design pattern that will be better suited for this problem. I can share some basic code if it will help.

Make a prototype from an existing site

After a day of research and many tests, I need your help:

from an existing site (let's take for example stackoverflow.com) I would like to be able to create a prototype/model of a modification of this site

The goal is not to recode the modifications in HTML/CSS => I only need a prototype (in PPT, in adobe XD, in adobe PSD, or other) and I wish that the solution is not too heavy, I have to make prototypes on a hundred sites.

Do you have any tools or ideas to answer this need?

My tests for now:

  • Convert the site to pdf then to ppt to make the modifications on PowerPoint => very bad quality of conversion/printing. In PDF, we lose the formatting of the site.
  • Using a plugin on Adobe XD => quality a little less bad, but the design of the site is off too.

I'm not a great developer but if there is another method a little more technical, I'm interested.

Should an enum have 2 separate value sets if they are related?

This question is on the reuse of the Java Enums

Let's say I have an Enum

public enum Days {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY SATURDAY, SUNDAY
}

Now, in one of the business usecase, I also need to consider Today, Tomorrow and yesterday as Days. Though they are related concepts, but clubbing them in the same enum doesn't feel right.

Should we create a new enum or can there be any justification to overload the same Days enum and add these 3 values inside it.

public enum Days {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY SATURDAY, SUNDAY, TODAY, TOMORROW, YESTERDAY
}

How do I do pattern match on an infinite stream in Java?

I'm not sure if this is even possible. Suppose I have an infinite incoming stream of characters, and I want to find the first match of a certain string (say, a short word). Is it possible to implement it using Java's stream API?

The only obvious algorithm I can think of is that if the first charater of the word is encountered in the stream, check the next character from the stream, and if it equals the next charater of the word, check the 3rd character. Because the word or pattern only has a few charaters, this algorithm sounds plausible. But I find it very difficult to implement with the stream API. I was wondering if it's possible to achieve this.It might be theoritically impossible.

Generic test implementation design

I'm trying to write a generic test class in Java. each test checks filtering using a certain filtering attribute. The inputs for my test are: filteringAttribute, filteringCondition, filteringArgs, expectedNumOfItemsAfterFiltering.

filteringAttribute - can be of two types: integer or double. for example: the attribute age is int, but height can be 183.41566

filteringCondition - is determined by the attribute type: for example equals condition only refers to integers, between condition only refers to doubles, and greater than refers to both.

filteringArgs - are determined by the filtering condition: for example: the args for eqauls condition are integers, but for between condition are two doubles.

expectedNumOfItemsAfterFiltering - are determined by all of the above.

How can I right a test that will be generic, and will not require me to add an additional test when a new attribute is add, instead I just want to update the relevant arguments when this happens.

Thanks!

Can a microservice send async message to itself via a queue system like RabitMQ?

I am experiencing a project where a microservice sends asynchronous message to itself via RabbitMQ, because it contains both the message producer and consumer parts. The reason is that the service can then produce the same type messages to the other services and receive the same type message from the other services.

This pattern is new to me. Is it anti-pattern in the microservice world?

How do I store matching characters in a variable instead of replacing them in SNOBOL

I have been trying to find a way to separate vowels and consonants from provided input. I know how to match and replace but I don't know how to print matching characters instead of replacing them.

MY code goes like this which is removing the matching characters: I want TEXT variable to remain the same and store the matching characters in another variable

?      OUTPUT = "Please enter a string: "
?      TEXT = INPUT
?      VOWEL_WORDS = 'A' | 'a' | 'E' | 'e' | 'I' | 'i' | 'O' | 'o' | 'U' | 'u'
?      CONS_WORDS = 'B' | 'b' | 'C' | 'c' | 'D' | 'd' | 'F' | 'f' | 'G' | 'g' | 'H' | 'h' | 'J' | 'j' | 'K' | 'k' | 'L' | 'l' | 'M' | 'm' | 'N' | 'n' | 'P' | 'p' | 'Q' | 'q' | 'R' | 'r' | 'S' | 's' | 'T' | 't' | 'V' | 'v' | 'W' | 'w' | 'X' | 'x' | 'Y' | 'y' | 'Z' | 'z'
?
?MATCH TEXT VOWEL_WORDS = :S(MATCH) F(OTHER)
?OTHER
?      OUTPUT TEXT

I want to create a row in bootstrap grid system which contain 7 images to be responsive for all types devices

[Hello hope you are well! I want to create a row with gridsytems in bootstrap which contain seven images horizontal for desktop and display for one column in mobile for all types of devices to be responsive. If anyone have any answer please reply me.][2]***

dimanche 30 mai 2021

Mediator Pattern Advantage

Im reading the book of GoF. Could you please explain the following Advantage:

It limits subclassing. A mediator localizes behavior that otherwise would be distributed among several objects. Changing this behavior requires subclassing Mediator only; Colleague classes can be reused as is.

Is it meant that we should subclass the Mediator or the ConcreteMediator? Can we have more than one ConcreteMediators that inherit form the same Mediator?

Is this any pattern?

Is this a proxy pattern? I have a Type (say Service) that is composed in a Singleton class (say Controller). When we create an instance of Controller, the Service instance is created. Controllers' main objective is to expose Public APIs, which are necessary for Service clients. As a result, the controller prevents the Service class from being directly accessed.

There are some cases where the Controller performs a pre-validation check before passing the request on to the Service.

According to the Proxy pattern, the "Controller" (Proxy) and the Service implement the Common Service API interface.

In this case, they will not inherit from a common Service API.

Can we refer to this as a Proxy design pattern since the Controller shields service access from the Service? Is it an Adapter? Is this nothing?

DDD - How to design filesystem domain

I am creating a system in which the domain is a file system. There are entities such as catalog and document. Each document must exist in some directory and each directory has a parent (excluding root catalog). What should a properly created aggregate for this system look like?

class Catalog {
   private Catalog parent;
   private List<Document> documents;
   ...
}

class Document {
   private Catalog catalog;
   ...
}

The approach presented above seems to me the best from an architectural point of view. One of the DDD principleis that an aggregate must be loaded and saved as a whole. Therefore, the presented example is impossible to implement in practice, because it required to load the entire tree of files from the database.

class Catalog {
   private CatalogID parent;
   private List<DocumentID> documents;
   ...
}

class Document {
   private CatalogID catalog;
   ...
}

Another approach is to store IDs only, rather than objects in entities. However, in this case, I cannot access the related entities.

For example, consider a method that checks if a document name is unique within a given directory.

class Catalog {
   private CatalogID parent;
   private List<DocumentID> documents;
   
   public bool IsNameUnique(string name) {
      foreach (document in documents) {
        if (document.Name == name) return true; <-- docuemnt is only ID, not reference
      }
      return true;
   }
}

I can't get the document name because I only store the ID instead of the entity reference.

What approach should I choose to solve this problem in the best way? Thanks in advance for your help.

Are all interface compositions considered as strategy pattern

Using Strategy pattern, we can decouple behaviors using interfaces. Behaviors are moved in to interface which can have multiple implementations. Clients can have has-a-relationship to interface and can refer to any of its implementation in runtime.

In all explanations, it is mentioned as a solution to solve issues related to inheritance, where two classes in different branches in inheritance hierarchy need same behavior.

I think we can use the same approach to decouple behaviors from classes even when inheritance hierarchy is not present. A single class having a reference to interface can achieve multiple behaviors based on the implementation it is referring at runtime.

Can we call such use cases as an implementation of Strategy pattern? If so, are all has-a-relationships to interfaces considered as strategy pattern?

Implementing level by level fallback in C#

I have a class ScoreStrategy that describes how to calculate points for a quiz:

public class ScoreStrategy
{
    public int Id { get; set; }

    public int QuizId { get; set; }

    [Required]
    public Quiz Quiz { get; set; }

    public decimal Correct { get; set; }

    public decimal Incorrect { get; set; }

    public decimal Unattempted { get; set; }
}

Three properties Correct, Incorrect and Unattempted describe how many points to be assigned for a response. These points can also be negative. The score strategy applies to all questions in the quiz, thus there can only be one ScoreStrategy per quiz. I have two subclasses:

public class DifficultyScoreStrategy : ScoreStrategy
{  
    public QuestionDifficulty Difficulty { get; set; }
}

public class QuestionScoreStrategy : ScoreStrategy
{ 
     [Required]
     public Question Question { get; set; }
}

My questions have three difficulty levels(Easy, Medium, Hard; QuestionDifficulty is an enum). The DifficultyScoreStrategy specifies if points for questions of a specific difficulty need to be assigned differently. This overrides the base ScoreStrategy that applies to the entire quiz. There can be one instance per difficulty level.

Thirdly, I have a QuestionScoreStrategy class that specifies if points for a specific question have to be awarded differently. This overrides both the quiz-wide ScoreStrategy and the difficulty-wide DifficultyStrategy. There can be one instance per question.

While evaluating the responses of the quiz, I want to implement a level-by-level fallback mechanism:

For each question: Check if there a QuestionScoreStrategy for the question, if not, fallback to DifficultyScoreStrategy and check if there is one for the difficulty level of the question, if not, fallback to the quiz-wide ScoreStrategy, if there is no ScoreStrategy either, use default as { Correct = 1, Incorrect = 0, Unattempted = 0 }(It would be great if I can make this configurable as well).

This is how I'm currently implementing response evaluation for each respondent. This method takes in all the questions in a quiz, all the responses of one respondent and all the strategies in an exam:

public List<Result> Evaluate(IEnumerable<Question> questions, IEnumerable<Response> responses, IEnumerable<ScoreStrategy> strategies)
{
     List<Result> results = new();
     // Convert responses to a dictionary with Question as key. Question overrides Equals and GetHashCode()
     var responseDict = responses.ToDictionary(r => r.Question);
     foreach (var question in questions)
     {
         Result result = new();
         ScoreStrategy strategy = {?}; // I need the right strategy to be selected here. 
 
         if (responseDict.TryGetValue(question, out Response response))
         {
            if (IsCorrect(response))   // IsCorrect() is another method that checks if a response is correct
            {
                result.Status = ResponseStatus.Correct;
                result.Score = stategy.Correct; 
            }
            else 
            {
                result.Status = ResponseStatus.Incorrect;
                result.Score = stategy.Incorrect;
            }
         }
         else
         {
             result.Status = ResponseStatus.Unattempted;
             result.Score = strategy.Unattempted;
         }
         results.Add(result);
     }
     return results;
}

NOTE: The strategies are stored in a database managed by EF Core(.NET 5) with TPH mapping:

modelBuilder.Entity<ScoreStrategy>()
                .ToTable("ScoreStrategy")
                .HasDiscriminator<int>("StrategyType")
                .HasValue<ScoreStrategy>(0)
                .HasValue<DifficultyScoreStrategy>(1)
                .HasValue<QuestionScoreStrategy>(2)
                ;

I have a single base DbSet<ScoreStrategy> Strategies.

What I have tried:

Separate out the strategies by type at the beginning of the method:

ScoreStrategy defaultStrategy = null;
HashSet<DifficultyScoreStrategy> dStrategies = new();
HashSet<QuestionScoreStrategy> qStrategies = new();

foreach(var strategy in strategies)
{
    switch (strategy)
    {
         case QuestionScoreStrategy qs: qStrategies.Add(qs); break;
         case DifficultyScoreStrategy ds: dStrategies.Add(ds); break;
         case ScoreStrategy s: defaultStrategy = s; break;
    }
}

Then do this for each question in the loop:

ScoreStrategy strategy = new() { Correct = 1, Incorrect = 0, Unattempted = 0 };

if (var q = qStrategies.FirstOrDefault(str => str.Question.Id == question.Id) != null)
{
    strategy = q;
}
else if (var d = dStrategies.FirstOrDefault(str => str.Question.Difficulty == question.Difficulty)
{
    strategy = d;
}
else if (defaultStrategy is not null)
{
   strategy = defaultStrategy;
}

This method is a bit clumsy and doesn't quite feel right to me. How do I implement this level-by-level fallback behavior? Is there a pattern/principle I can use here? Or can someone simply recommend a cleaner solution?

MVVM Swift datasource calling service without RxSwift

I am trying to using MVVM and my final solution like below, But i am not sure it is true in terms of SOLID principles. Because I making service call in a viewcontroller. Is it okay ? Or How my approach should be?

class ViewController: UITableViewController {

let dataSource = CustomDataSource()

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = customdataSource

    customdataSource.dataChanged = { [weak self] in
        self?.tableView.reloadData()
    }

    dataSource.serviceCall("https:/..")
  }
}

Please don`t ask me share CustomDataSource and its service call, it is basically a subclass and UITableViewDataSource, if i share all code the question could be more complicated.

samedi 29 mai 2021

How to design CDK project?

recently started working on a CDK project, Wanted to have views of y'all on how to structure it. Ill lay out what I have thought.

Will be have 2 separate packages.

  1. ApplicationCommonsPackage
  2. SpecificApplicationCDKPackage(Can be many such packages), These will depend on the ApplicationCommonsPackage

The ApplicationCommonsPackage will hold all the common logic for all our applications(till now have thought of Configs, Common constructs, factory method for creating constructs)

The latter(SpecificApplicationCDKPackage) will hold configs for the constructs and will use the factory in ApplicationCommonsPackage for creating stuff.

What do you think of using factory pattern in ApplicationCommonsPackage? One issue I am facing is that I cannot expose a common interface with a generic method(or am not able to?) for the factory. The reason being every construct requires props which are of very specific type, I cannot generalise them to any or such sort as by that will lose the niceness of typescript. So am having functions like createLambda(scope: Stack, id: string, props: LambdaProps): Function in my factory. I am not liking this structure a lot, I would have loved generic function which took the Function as an input and would have determined the type of props from it. Something like create<T>(scope: Stack, id: string, props: <U derived from T => some methodology to get this?>): T so that when I actually use this in SpecificApplicationCDKPackage like so - this.factory.create<Function>(this, 'SampleLambda', {}) I get all compile time errors for the props parameter({})

What pattern I have to use to correctly call Child methodes?

I need help with how to correctly use java. Currently I rely on Jackson Object mapper and want to replace it with some pattern probably.

I have an abstract class:

@Getter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder(toBuilder=true)
@Accessors(chain = true)
public class AbstractClass {
  private String first;
  private Object second;
}

also an extened class:

@Setter
@Getter
@EqualsAndHashCode(callSuper = true)
@SuperBuilder(toBuilder=true)
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class ExtendedClass extends AbstractClass {
  @Getter
  public static final String FIRST_TYPE= "EXTENDED";

  private String first;
  private Second second;

  @Getter
  public static class Second {
    private String value;
  }
}

Later I do such a lame thing probably which I need to fix, cause I don't think it's Java way to use object mapper instead of some clever pattern here:

  @SneakyThrows
  private SomeProps mapProps(String value) {
    try {
      Values values = objectMapper.readValue(value, Values.class);
      AbstractClass valueProp = values.getProp();
      var valuesType = valueProp.getFirst();
      String ExtendedClassStaticFirstValue FieldValue =
        (String) getTypeFromStatic(Extended.class);
      // TODO: want to implement more checking here 
      if (ExtendedClassStaticValue 
        .equals(valuesType)) {
        // TODO: @pdemyane: please, think about!
        Extended valueProp =
          objectMapper.readValue(objectMapper.writeValueAsString(valueProp), Extended.class);
        return map(valueProp);
      } else {
        return null;
      }
    } catch (JsonProcessingException e) {
      log.error("Json processing exception in processing source from", e);
      return null;
    }
  }

How to write code so that not to rely on Object mapper? Do I understand correctly that this is completle wrong?

Implementing traits/ advices for cross cutting concerns, the Golang way

I'm implementing my first microservice in golang. Services currently look something like this:

type UserRegistrationService struct {
    repo UsersRepository
}
func (ur UserRegistrationService) Execute(cmd RegisterUserCommand) User {
    usr := NewUser(cmd.Username)
    ur.repo.AddUser()
    return usr
}
func serviceClient() {
    usr := NewUserRegistration(NewPgUserRepo()).Execute(RegisterUserCommand{Username: "Mr. Crowly"})
    fmt.Printf("user %v was added successfully", usr)
}

Say I wanted to log at the start of every service and add an audit record after the execution. Here are the options I thought of:

Option1: Calling "advice" functions around the service

The simplest solution would be literally calling a before() and after() functions. In the following example, I'm injecting these functions as hooks into the service.

func (ur UserRegistrationService) Execute(cmd RegisterUserCommand, before func(RegisterUserCommand), after func(RegisterUserCommand)) User {
    before(cmd)
    defer after(cmd)
    usr := NewUser(cmd.Username)
    ur.repo.AddUser(usr)
    return usr
}
func serviceClient() {
    before := func(cmd RegisterUserCommand) {
        fmt.Printf("executing %v", cmd)
        //do more stuff before
    }
    after := func(cmd RegisterUserCommand) {
        AuditJournal(cmd)
        //do other stuff after
    }
    usr := NewUserRegistration(NewPgUserRepo()).Execute(RegisterUserCommand{Username: "Mr. Crowly"}, before, after)
    fmt.Printf("user %v was added successfully", usr)

}

As you can see, we have the 100 years old problem of cross cutting concerns, that is "scattering and tangling"

Option 2: Delegating cross-cutting concerns to a "service executor"

Instead of directly calling services, I can pass the (ready to be executed) service to an "executor" which can call before and after functions as follows:

type Command interface {
    //empty interface anti-pattern
}
type Entity interface {
    // again
}

type Service interface {
    Execute(Command) Entity
}

func (ur UserRegistrationService) Execute(cmd Command) Entity {
    typedCmd := cmd.(RegisterUserCommand)
    user := NewUser(typedCmd.Username)
    ur.repo.AddUser(user)
    return user
}
func serviceClient() {
    usr := ExecuteWithAdvice(RegisterUserCommand{Username: "Mr. Crowly"}, NewUserRegistration(NewPgUserRepo()))
    fmt.Printf("user %v was added successfully", usr.(User).Name)
}
func ExecuteWithAdvice(cmd Command, svc Service) Entity {
    before(cmd)
    defer after(cmd)
    return svc.Execute(cmd)
}
func before(cmd Command) {
    fmt.Printf("executing %v", cmd)
}
func after(cmd Command) {
    AuditJournal(cmd)
}

This is a better solution in my opinion, but it forces the use of empty interfaces (See the Command and Entity) and therefore, I need type assertions (see line 2 in the serviceClient and line 1 in the Execute method).

Option 3: Introducing an interface for the service, and returning a decorator from the constructor

type UserRegistrationServiceInterface interface {
    Execute(cmd RegisterUserCommand) *User
}
func NewUserRegistration(repo UsersRepository) UserRegistrationServiceInterface {
    return &UserRegistrationServiceWithAdvice{internalService:&UserRegistrationService{repo: repo} }
}
type UserRegistrationServiceWithAdvice struct {
    internalService UserRegistrationServiceInterface
}
func (u UserRegistrationServiceWithAdvice) Execute(cmd RegisterUserCommand) *User {
    before(cmd)
    defer after(cmd)
    return u.internalService.Execute(cmd)
}

The only problem with this approach is the need to introduce an interface and a decorator for each and every service and have the constructor return the nested decorator struct.

Is there a way to decorate my services with cross cutting concerns logic without:

  1. scattering and tangling
  2. having to introduce a wrapper/ decorator for every interface
  3. using empty interfaces with type assertions

If there's no solution that matches the above requirements, which of the previous solutions is the most idiomatic way in Go?

What is the best approach to reuse similar method in multiple Services that use similar objects?

I have several services that have the same method that is called by a Scheduler. This is one example of one service.

@Service
public class MyService1 {

     @Autowired
     private MyLocalMapper1 localMapper1;
     
     @Autowired
     private MyLocalRepository1 localRepository1;

     @Autowired
     private MyExternalMapper1 externalMapper1;
     
     @Autowired
     private MyExternalRepository1 externalRepository1;
  

     public void startProcess() {
          //I use the mappers and the repositories in here
     }
}

I have 15 services exactly similars to this one but every service has a specific mappers (e.g. MyLocalMapper2, MyLocalMapper3, etc...) and also repositories.

e.g

 @Service
 public class MyService2 {

     @Autowired
     private MyLocalMapper2 localMapper2;
     
     @Autowired
     private MyLocalRepository2 localRepository2;

     @Autowired
     private MyExternalMapper2 externalMapper2;
     
     @Autowired
     private MyExternalRepository2 externalRepository2;
  

     public void startProcess() {
          //I use the mappers and the repositories in here
     }
}

Is there any design pattern which allows to reuse the code inside startProcess method taking into account that the objects it uses are different in every service?

I thought in creating interfaces for every object such as: LocalMapperInterface, LocalRepositoryInterface, etc.. and pass it to a single method with all those interfaces as parameters but not sure if that is the best approach.

Thanks in advance.

vendredi 28 mai 2021

How to design hardware interfaces in C# while staying DRY and SOLID?

I am having a design problem with an application that handles two or more networked I/O devices.

Both devices share properties like a name, IP address, and port. They will also share methods such as Connect(), Disconnect(), IsConnected().

In an effort to stay DRY, this leads me to believe I need some interface - IODevice.

public interface IODevice
{
    int Id { get; set; }
    string Name { get; set; }
    IPAddress IPAddress { get; set; }
    int Port { get; set; }
    
    bool IsConnected();
    void Connect();
    void Disconnect();
}

With both devices defined:

public class DeviceOne : IODevice
{

    private DeviceOneApi _api;
    
    public int Id { get; set; }
    public string Name { get; set; }
    public IPAddress IPAddress { get; set; }
    int Port { get; set; }
        
    public DeviceOne()
    {
        _api = new DeviceOneApi();
    }

    public bool IsConnected()
    {
        return _api.IsDeviceConnected();
    }

    public void Connect() 
    {
        _api.OpenConnection();
    }
    
    public void Disconnect()
    {
        _api.CloseConnection();
    }

}
public class DeviceTwo : IODevice
{
    ...
}

I will need to monitor the I/O to detect changes - this could be a digital sensor or a bit-change in memory. I was thinking of using some controller to loop through all defined devices and check the device I/O. An event aggregator will be used to send out notifications.

public class IOController
{
    private Thread _monitorThread;
    private int _monitorDelay;  
    private bool _canMonitor;
    private ILogger _logger;
    
    public static List<IODevice> Devices { get; set; }
    
    public IOController(ILogger logger)
    {
        _logger = logger;
        _monitorDelay = 100;
        _monitorThread = new Thread(Monitor);
    }
    
    public void AddDevice(IODevice device)
    {
        Devices.Add(device);
    }
    
    public void StartMonitor()
    {
        _canMonitor = true;
        _monitorThread.Start();
    }
    
    private void Monitor()
    {
        while(_canMonitor)
        {
            foreach(IODevice device in Devices)
            {
                // Check I/O Points
                EventAggregator.Instance.Publish(new SomeIOChange(IODetails));
                Thread.Sleep(_monitorDelay)
            }
        }
    }
}

This is the first place I am trying to make a decision. Each device implements its own types of I/O. I.e. DeviceOne may use integers in memory and DeviceTwo may use booleans from digital signals. A device may also use multiple types of I/O - digital, analog, strings, etc and the device API will implement methods to read/write each of these types.

So, I could either keep a seperate list of each device type and run multiple foreach loops:

foreach(IODeviceOne deviceOne in DeviceOnes) {  }
foreach(IODeviceTwo deviceTwo in DeviceTwos) {  }

Or, I could have the IODevice implement a method that checks its own I/O.

public interface IODevice
{
    ...
    void CheckIO();
}
private void Monitor()
{
    while(_canMonitor)
    {
        foreach(IODevice device in Devices)
        {
            device.CheckIO();
        }
    }
}

However, there will also be external scripts and user input that will need to read or modify an I/O type directly. With the IODevice interface defined in a way to be shared across devices, there is not a specific implementation of read/write.

For instance, a user may hit a toggle on the front-end that will affect a digital output in device one. Eventually, this action needs to be propagated to:

public class DeviceOne : IODevice
{
    ...
    public void WriteDeviceOnePointTypeOne(DeviceOnePointDetails details)
    {
        _api.WriteDeviceOnePointTypeOne(details);
    }
}

Since I am using EventAggregator, should I just implement the event listeners in each device instance?

public class DeviceOne : IODevice, ISubscriber<DeviceOnePointUpdate>
{
    ...
    
    public void OnEvent(DeviceOnePointTypeOneUpdate e)
    {
        _api.WriteDeviceOnePointTypeOne(e.Details)
    }
}

Or should I just use specific interfaces all the way down even though this may not follow DRY?

public DeviceOneController : IDeviceOneController
{
    ...
    private void Monitor()
    {
        while(_canMonitor)
        {
            foreach(IODeviceOne deviceOne in DeviceOnes)
            {
                // Check for I/O updates in device one
            }
        }
    }
}

Would casting be an option while still remaining SOLID?

public class FrontEndIOEventHandler
{
    private ILogger _logger;
    private IOController _controller;
    
    public FrontEndIOEventHandler(ILogger logger, IOController controller)
    {
        ...
    }

    public void UpdateDeviceOnePointTypeOne(int deviceId, DeviceOnePointTypeOneUpdate details)
    {
        DeviceOne deviceOne = _controller.GetDeviceById(deviceId) as DeviceOne;
        deviceOne.WriteDeviceOnePointTypeOne(details);
    }
}

I am using interfaces to aid in unit-testing and I eventually want to implement an IoC container. The device information will come from some external configuration and this configuration will include a device map (the only important I/O points will be defined by the user).

<devices>
    <device type="device_one">
        <name></name>
        <ip_address></ip_address>
        <port></port>
        <map>
            <modules>
                <module type="point_type_one">
                    <offset>0</module>
                    <points>
                        <point>
                            <offset>0</offset>
                        </point>
                        <point>
                            <offset>1</offset>
                        </point>
                    </points>
                </module>
            </modules>
        </map>
    </device>
    <device type="device_two">
        <name></name>
        <ip_address></ip_address>
        <port></port>
        <map>
            <integers>
                <integer length="32" type="point_type_four">
                    <offset>0</module>
                </integer>
            </integers>
        </map>
    </device>
</devices>

The overall goal is to read the configuration, instantiate each device, connect to them, start monitoring the specified I/O for changes, and have the device available for direct read/write.

I am open to all comments and criticisms! Please let me know if I am way off. I am still a novice and attempting to become a better (read: more professional) developer. I know there are ways to do this quick and dirty, but this is part of a bigger project and I'd like this code to be maintainable + extensible.

Let me know if I need to provide any additional detail! Thanks.

Spark Streaming Design Pattern

I have a stream of events contains different type of activities, in spark streaming application need to do different persistence and aggregation processing based on different activity type, is there a good design pattern I could use in the spark streaming application to avoid simply filter/select by activity type ? currently I am doing something like below:

inputDF.persist()

val userActivityDF = inputDF.filter(col("activityType") isin("clicked", "chatted", "opened")) 
userActivityDF.writeStream....

val userClosedDF = inputDF.filter(col("activityType") = "closed")
processUserClosed(userClosedDF) 

val userSkippedDF = inputDF.filter(col("activityType") = "skipped")
processUserSkipped(userSkippedDF) 

.....

inputDF.unpersist()

Should I do DAO as Singleton when Implementing Abstract factory or there is a better appoach?

I have DaoFactory abstract class that return concrete Factory I have done it only to Mysql yet

public abstract class DAOFactory {
    public static final int MYSQL = 1;
    public abstract CarDao getCarDao();
    public abstract UserDao getUserDao();
    public abstract OrderDao getOrderDao();
    public abstract CarCategoryDao getCarCategoryDao();
    public static DAOFactory getDAOFactory(
            int whichFactory) {
        switch (whichFactory) {
            case MYSQL:
                return new MySQLDAOFactory();
            default :
                return null;
        }
    }
}

And I have MysqlFactory that return Dao implementation

public class MySQLDAOFactory extends DAOFactory {
    private static final Logger LOGGER = LogManager.getLogger(MySQLDAOFactory.class);
    private static DataSource DATA_SOURCE;

    public static void dataSourceInit(){
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:comp/env");
            DATA_SOURCE = (DataSource) envContext.lookup("jdbc/UsersDB");
        } catch (NamingException e) {
            LOGGER.error(e);
        }
    }
    public static Connection getConnection(){
        Connection connection = null;
       if(DATA_SOURCE==null){
         dataSourceInit();
       }
       try {
           connection = DATA_SOURCE.getConnection();
            } catch (SQLException e) {
                LOGGER.error(e);
            }
        return connection;
    }
    @Override
    public CarDao getCarDao() {
        return new MySQLCarDao();
    }
    @Override
    public UserDao getUserDao() {
        return new MySQLUserDao();
    }
    @Override
    public OrderDao getOrderDao() {
        return new MySQLOrderDao();
    }
    @Override
    public CarCategoryDao getCarCategoryDao() {
        return new MySQLCarCategoryDao();
    }
}

Do I need to make Dao singletons or is there a better approach?I took this implementation from oracle site

What's an appropriate design for creating different objects/invoking different methods depending on use case?

I'm not too sure what this use-case is called but let me explain: I am developing a service that uploads data. My service handles different types of uploads and each upload type is unique e.g. content of UPLOAD_A != content of UPLOAD_B.

The data comes to me a json file. From the json file, I know what type of upload it is. I need to parse this json into an appropriate UploadDataX object. For example, if I get a json data file for UPLOAD_A, I need to serialise this into an UploadDataA object.

Once I have my UploadDataX object, I will need to upload the data. I do this by using an external client object: UploadClient(). However, I need to invoke specific upload methods depending on the data type. For example, for an UPLOAD_A type, I need to invoke UploadClient().uploadDataA(UploadDataA) and for an UPLOAD_B type, I need to invoke UploadClient().uploadDataB(uploadDataB).

The problem is that I do not own any of these UploadDataX and the client object. Unfortunately, the UploadDataX do not come under a super-class. I'm wondering what is an effective design pattern for dealing with this use-case?

I can think of a brute force solution, using simple switch-case statements:

// BRUTE FORCE SOLUTION
public void upload(UploadType uploadType, String jsonString) {
   switch (uploadType) {
      case UPLOAD_A: {
         UploadDataA uploadDataA = Gson().fromJson(jsonString, UploadDataA.class);
         UploadClient().uploadDataA(uploadDataA);
         break;
      }
      case UPLOAD_B: {
         UploadDataB uploadDataB = Gson().fromJson(jsonString, UploadDataB.class);
         UploadClient().uploadDataB(uploadDataB);
         break;
      }
   }
   ...
}

as you can see, this seems repetitive and I can't help but feel there is a better design approach. I was thinking about a Factory pattern but I want to see what everyone else thinks.

Design Pattern other than Page object model with Page factory for Automation Framework

Looking for a Design Pattern other than a Page object model with a Page factory for Automation Framework.

jeudi 27 mai 2021

python substring based on a specific pattern

I am very new to Python. I am trying to substring a specific pattern from a long string of txt. This specific pattern occur multiple times in the same txt. For example, s = 'apple/gfgfdAAA1234ZZZuijjk/pear apple/009456/pear apple/dsakjdaghdj/pear' start = s.find('apple') end = s.find('pear', start) s[start:end] This was my initial attempt. However, it only gives me the very first chunk of text, which is 'gfgfdAAA1234ZZZuijjk'; instead, I will also need '009456' and 'dsakjdaghdj'.

Storing S3 Urls vs calling listObjects

I have an app that has an attachments feature for users. They can upload documents to S3 and then revisit and preview and/or Download said attachments.

I was planning on storing the S3 urls in DB and then pre-signing them when the User needs them. I'm finding a caveat here is that this can lead to edge cases between S3 and the DB.

I.e. if a file gets removed from S3 but its url does not get removed from DB (or vice-versa). This can lead to data inconsistency and may mislead users.

I was thinking of just getting the urls via the network by using listObjects in the s3 client SDK. I don't really need to store the urls and this guarantees the user gets what's actually in S3.

Only con here is that it makes 1 API request (as opposed to DB hit)

Any insights?

Thanks!

How to split a big Aggregate Root to smaller?

I´m developing a domain layer that has a specific Aggregate Root. That aggregate root consists of a Company that has various types of related persons. Something like this:

public class Company
{
   public virtual ICollecion<PersonType01Entity> Person01 {get; private set;}
   public virtual ICollecion<PersonType02Entity> Person02 {get; private set;}
   public virtual ICollecion<PersonType03Entity> Person03 {get; private set;}

   public void AddPersonType01(PersonType01Entity p) 
   { 
      if(Person01.Any(c => c.id == p.id )
         throw new Exception();
   }
   // more code
}

Imagine that I need to do this type of checking for every person type, and other invariants checks. My Aggregatte Root entity became to big and I´m do not know how to split it to be smaller. Any suggestions on this?

Is there a pattern design to consume web services (mobile)?

I'm looking a pattern design to consume web services in Swift(5.2.4) If you use any pattern, please tell me your experience

What are the best practices for handling menu clicks in a complex java fx application?

I am trying to create a javafx desktop application which has the following layout:


    +------------+-----------------------------+
    |            |                             |
    |            |                             |
    |            |                             |
    |            |                             |
    |            |                             |
    | MENU VIEW  |          DETAIL VIEW        |
    |            |                             |
    |            |                             |
    |            |                             |
    |            |                             |
    |            |                             |
    |            |                             |
    |            |                             |
    +------------+-----------------------------+

The menu will contain several menu options which, when clicked, change the detail pane view. The detail pane will contain complex information.

At the moment my code design looks like this:


    +----------------------------------------------------------------------+                
    |                     +---------------------------+                    |                
    |                     |         MAIN CLASS        |                    |                
    |                     |                           |                    |                
    |                     --------------|--------------                    |               -
    |                   -/              |              \-                  |                
    |      +-----------/--+      +-------\------+    +---\----------+      |                
    |      |        -/    |      |       |      |    |     \        |      |                
    |      |  MENU        |      | DETAIL PANE 1|    |DETAIL PANE 2 |      |                
    |      |  CONTROLLER  |      |  CONTROLLER  |    |  CONTROLLER  |      |                
    |      |              |      |              |    |              |      |                
    |      |              |      |              |    |              |      |                
    |      +--------------+      +--------------+    +--------------+      |                
    |                                                                      |                
    +----------------------------------------------------------------------+  

A main class which is called when the application is ran creates the menu controller which belongs to the menu view. The same controller also contains the detailview anchorpane.

The main class now adds listeners to the buttons by using a getter from the menu controller. When the listener is fired it will create the detail pane view and put on the anchorpane which it also got from the menu controller.

The reason I don't load the FXML for the detail view in the menu controller is because I want to use the data from the detail controllers in the main class for other operations.

QUESTION

Is this the way to do it? Are there any resources where I can read more about patterns/strategies to do this the "correct" way?

All the resources I can find online are more basic hello world like scenarios where everything is handled in the menu controller.

Nested re-use/enhancement of react context (anti-pattern?)

I would like to know if it is an anti-pattern to create nested context providers (the same context) and progressively extend the data. So, using the current context and enriching/overriding it from that point downward.

Why

I am building a sort of ABAC system for a product. This access can be affected by different items which are available for a specific item.

Approach

const AuthContext = React.createContext({});

const AuthContextProvider = ({ children, value }) => {
  const parentAuth = React.useContext(AuthContext);
  const updatedAuth = { ...parentAuth, ...value };

  return (
    <AuthContext.Provider value={updatedAuth}>{children}</AuthContext.Provider>
  );
};

And my usage would be something like

<AuthContextProvider value=>
  <SomeConsumingComponent permission="RE_ORDER" />
...    
  <AuthContextProvider value=>
    <SomeConsumingComponent permission="EDIT_TEXT" />
  </AuthContextProvider>
....
  <AuthContextProvider value=>
    <SomeConsumingComponent permission="MODIFY_MEDIA" />
  </AuthContextProvider>
</AuthContextProvider>

Of course the consuming components can appear in quite more complex structures and i want to add the relevant "extra" data at the higher available point.


Are there obvious (not to me yet) disadvantages to this approach ?

Is there relevant terminology for this that i might be missing, in order to search for more info ?

Subset pattern implementation

I am trying to write an implementation on C# of Subsets pattern read here 14 Patterns to Ace Any Coding Interview Question:

enter image description here

It looks obvious but confuses me. My research says me it should be implemented via Jagged Arrays (not Multidimensional Arrays). I started:

int[] input = { 1, 5, 3 };
int[][] set = new int[4][];
// ...

Could someone help with 2, 3 and 4 steps?

Applying design patterns whilst collaborating with Facade pattern

At first, I had an input which is either "online" or "offline"

If the input is online, it gets data from online resources, and if it's offline, it gets data just from a mock text file that I personally made. Then I displayed the result on GUI using swing.

So at first, my main method was like this:

public static void main(String[] args) {

    if(args[0].equalsIgnoreCase("online")) {
        JFrame frame = new JFrame("Online");
        JTextField...
        ...
    } else if(args[0].equalsIgnoreCase("offline")) {
        JFrame frame = new JFrame("Offline");
        JTextField...
        ...
    }
}

And I used a design pattern in order to hide the complexity of the system.

Applying the facade

public static void main(String[] args) {

    Facade facade = new Facade();

    if(args[0].equalsIgnoreCase("online")) {
        facade.online();
    } else if(args[0].equalsIgnoreCase("offline")) {
        facade.offline();
    }
}

But the problem is, I now have one more input which is either "pdf" or "txt" which will decide in which file extension should the output of the data be stored.

So what I want to achieve here is, I want to apply a design pattern to cover up the second input as well whilst keeping the facade pattern.

The main method I desire to have is like:

public static void main(String[] args) {
    SomeRandomDesignPattern pattern = new SomeRandomDesignPattern();
    pattern.execute(args);
}

I am thinking of using the Strategy pattern here, but when I searched up google, people don't get used to using if/else statement with the Strategy pattern and that makes me confusing about how I should apply it to the system.

Can anyone tell me what kind of design pattern I can apply for it and how?

If applying the design pattern is not the best way, is there any better way for it? (I personally want to avoid using nesty if/else statements...)

Thanks in advance!

Best way to construct complex states with state pattern?

I have a menu that can be in different states so I decided to use the state pattern. Reading online about the pattern seems like the usual way is to construct states from another state but this will not work for me because I have more complex states which need other dependencies. I could pre-create all states in a context object and then switch states from the context object, but I also need some info from the previous state so it becomes messy too.

     class State1 {
         public State1(Context context, /*some complex constructor*/) {
         }
         public void Action() {
            //Something happend and we want to transition to other state
               
            //Usual way 
            //this will not work because state1 doesnt have 
            //dependencies to construct state2
            //context->SetState(new State2());
            

            //My current way
            //This is better because it works, but you will have to create
            //such functions for every state and context object needs to be 
            //modified if new states are added which is not ideal
            context->SetState2(/*something produced by action in state1*/);
         }
     }   

    class State2 {
         public State2(Context context, /*some complex constructor*/) {
         }
     }   
     
     
    class Context {
      //has current state 
    }

Is this a sign of a bad design?
Is there a clean solution to this or I thinking too much about this?

Best way to using static container instead a lot of singleton class...can you show me some example? [closed]

I have a legacy winForms application that now i'm in charge of maintaining and developing. This app has a lot of singleton instance in all the code that rappresent the component used by the application. Some are very similar to service that wrap other component or other class. Other instead wrap some entities to making a cache-like pattern

This is an example of this cached class

public class SingletonCycle
{
    private static Cycle _instance;
    private static DevExpress.RackManager.RackManager _rackManager;

    public static event EventHandler<Cycle> OnCycleUpdated;

    private static void RaiseOnCycleUpdated(Cycle cycle)
    {
        OnCycleUpdated?.Invoke(cycle, cycle);
    }

    public static Cycle GetInstance()
    {
        return _instance;
    }
    
    public static void SetCycleInstance(Cycle cycle)
    {
        if (_instance != null)
        {
            SingletonAuditTrail.GetInstance().ModifiedCycle(cycle);
        }
        else
        {
            SingletonAuditTrail.GetInstance().StartCycle(cycle);
        }
        _instance = cycle;
        _instance.CreationDate = DateTime.Now;
        _instance.Operator = CommonUIManager.GetInstance().GetConfig().GetCurrentUser;

        SaveCycle();
    }
}

I want to try to start a refactor by using Di and Simpleinjector. Because i want to begin to test some part of the software Basically i want to trasform all this singleton in service that will be registered in container as singleton.

The problem is that all this services are spread out in all the software and for now i can't use everywhere constructor injection because i can't put all the classes inside container.

For now I try to use the container as static and everywhere use it instead of every singleton instances I now that it's not good to spread out static container everywhere and using container as static but i don't have any other clue on how to do this

Register container in the static Main

public static Container Container { get; private set; }

static void Main()
{
........
    var crpConfig = SingletonCrpCompactConfig.GetInstance();
    var container = new Container();
    
    container.Register(typeof(UnitOfWorkManager),
        CreateUOWManager(crpConfig),
        Lifestyle.Singleton);
    container.Register(typeof(RecipeModuleCache),
        CreateRecipeModuleCache(crpConfig, container),
        Lifestyle.Singleton);
        container.Verify();
    Container = container;
......
}

private static Func<object> CreateRecipeModuleCache(CrpCompactConfig crpConfig, Container container)
{
    return () =>
    {
        var uowManager = container.GetInstance<UnitOfWorkManager>();
        var cache = new RecipeModuleCache(crpConfig, uowManager);
        return cache;
    };
}

Example of the service to be registered inside the container

public class RecipeModuleCache
{
    private readonly CrpCompactConfig _config;
    private readonly UnitOfWorkManager _uow;
    private CrpCompactRecipeModule _instance;
    private bool _cached;

    public RecipeModuleCache(CrpCompactConfig config, UnitOfWorkManager uow)
    {
        _config = config;
        _uow = uow;
    }

    public CrpCompactRecipeModule GetCached()
    {
        if (_cached)
            return _instance;
        _instance = StaticBuilders.Create(_uow);
        _cached = true;
        return _instance;
    }

    public void Invalidate()
    {
        _instance = null;
        _cached = false;
    }
}

After this registration where there is the singleton i use instead

Program.Container.GetInstance<RecipeModuleCache>()

There is some problem of using this kind of patterns instead static singleton

Can you suggest some other advice?

How to avoid hardcoded @HostListener events in Angular 11?

Context

After implementing HostListeners for a certain keyboard event in my Angular application I ran into the problem that some users might not have conveniently placed keys. As an example the English QWERTY keyboard has its "/" next to the right shift button. On the other hand, the German "QWERTZU" keyboard has its "/" in the numbers row, next to the "`" and it requires two modifier keys in order to perform. The goal was to improve usability by allowing certain keyboard shortcuts, but in this case for the German keyboard, it does the opposite.

Goal

My goal is to specify certain hotkey combinations in a specific application configuration class. This should not be too difficult to perform. The users can then configure their hotkeys themselves.

Problem

At the moment my implementation for a certain hotkey looks like this.

@HostListener('window.keydown.esc') escapeEvent(): void {
...
}

As you can see the @HostListener annotation requires an argument in order to listen for a certain event. The downside of this, is that it cannot be set statically. I can for instance not define a variable and insert it into this parameter. The error I would get is the following

@HostListener's event name argument must be a string. Value could not be determined statically

How can I avoid this, in order to configure these hotkeys in a settings file and improve user experience and usability?

Thanks beforehand!

Call method by name in loop iterating by objects, looking for design pattern

I need to advice or idea on how to implement the following. I have an interface with lots of methods each can throw exception (in fact it is WCF call). So the each call must be wrapped by try block

public interface ISomeInterface
{
 MethodThatCanThrow1(Arg1 arg);
 ..
 MethodThatCanThrow101(Arg2 arg);
}

Now we have a collection of objects

var items = new List<ISomeInterface>();

Now I have to call MethodThatCanThrow1 method in loop for every object. Method can throw exception, in that case I need to continue for remaining ojects

void CallMethodThatCanThrow1()
{ 
 foreach(var item in items)
 {
  try
  {
    item.MethodThatCanThrow1(Arg1 arg);
  }
  catch(Exception ex)
  {
   // do something
  }
 }
}

Now I need to call MethodThatCanThrow2 So for second method I need to copypaste the try catch block stuff.

void CallMethodThatCanThrow2()
{ 
 foreach(var item in items)
 {
  try
  {
    item.MethodThatCanThrow2(Arg2 arg);
  }
  catch(Exception ex)
  {
   // remove failed item from items
   // continue foreach for the rest
  }
 }
}

So for the rest 101 method I have to copy paste the whole block only changing the method name.

So I am thinking about refactoring it. What I want is put try catch block in separate Methodand pass the Method Name that needs to be called

void CallMethodofISomeInterfaceForGivenReference(delegate methodProvide)
{ 
 foreach(var item in items)
 {
  try
  {
     // take item and call method that is provided
  }
  catch(Exception ex)
  {
   // do something
  }
 }
}

mercredi 26 mai 2021

adding argument via constructor or method

I have these validators classes

interface Validator {
     bool Validate(string value,object options)
}

class NumberValidator extends Validator {}
class EmailValidator extends Validator {}
class RangeValidator extends Validator {}
...

as you can see that the options are passed on the call to the Validate method. but I was wondering if it's better to have the options argument to be passed via constructor instead of the Validate method? (from CleanCode perspective).

so the interface and my implementation classes will be like this:

interface Validator {
    bool Validate(string value)
}

class SomeValidator extends Validator {
     private object options;
     public SomeValidator(object options) {...}
     public bool Validate(string value) {...}
}

...

I sense that having the options on the constructor will be better, but honestly, I don't have a reason why it's better.

how generic type with a recursive type parameter along with the abstract self method allows method chaining to work properly?

I am reading Effective Java Edition 3. in chapter 2 page 14, the author talks about the builder pattern and presents this code:

public abstract class Pizza {
    public enum Topping { HAM, MUSHROOM, ONION, PEPPER, SAUSAGE }
    final Set<Topping> toppings;
    abstract static class Builder<T extends Builder<T>> {
        EnumSet<Topping> toppings = EnumSet.noneOf(Topping.class);
        public T addTopping(Topping topping) {
            toppings.add(Objects.requireNonNull(topping));
            return self();
        }
        abstract Pizza build();
        // Subclasses must override this method to return "this"
        protected abstract T self();
    }
    Pizza(Builder<?> builder) {
        toppings = builder.toppings.clone(); // See Item 50
    }
}

an implementation of above abstract class:

public class NyPizza extends Pizza {
    public enum Size { SMALL, MEDIUM, LARGE }
    private final Size size;
    public static class Builder extends Pizza.Builder<Builder> {
        private final Size size;
        public Builder(Size size) {
            this.size = Objects.requireNonNull(size);
        }
        @Override public NyPizza build() {
            return new NyPizza(this);
        }
        @Override protected Builder self() { return this; }
    }
    private NyPizza(Builder builder) {
        super(builder);
        size = builder.size;
    }
}

and we can use code like this:

NyPizza pizza = new NyPizza.Builder(SMALL)
.addTopping(SAUSAGE).addTopping(ONION).build();

quote from the book:

Note that Pizza.Builder is a generic type with recursive type parameter. this, along with the abstract self method, allows method chaining to work properly in subclasses, without the need for casts.

now my question is what power/value <T extends Builder<T>> added to Pizza class and how it is different with <T extends Builder>? if you are going to explain <T extends Builder<T>> to a five years old kid in simple English how would you explain it?

and I can't figure out the purpose of abstract self method in the super class?

Fetching data in separate servers

I have a monolithic REST API and a separate WebSocket server that’s used for real-time updates. They're both separate so that I can scale them independently. The API fetches data from the database and sends it to the users who request it, but I also want to fetch data from the database in my WebSocket server and I'm not sure how I should do it in a way that is consistent.

Options: (the ones I thought of)

  1. Create a shared database module with the schemas and models for my database and use it across both servers.
  2. On the WebSocket server, I could request the API using the user token to fetch data on their behalf.
  3. I could split up my API logic into a microservice architecture and have the API act as a gateway with auth logic and proxying requests to the micro services, and the WebSocket server could directly request the microservices without going through the gateway so it doesn’t have to authenticate.
  4. Fetch the data from the API using RPC over RabbitMQ.
  5. Move logic that needs to query the database to my API instead (not very ideal)

Concerns:

  • For option #1, it’s apparently bad design to do this, and in all fairness I don’t need to fetch a lot of my data in my WebSocket server, only certain fields (that can be cached), and if I decide to implement some form of database cache there would be two separate caches (not to mention both servers should be scaled so there would be multiple instances). I could implement the cache in my shared module but it sounds like a bad idea.
  • Option #2 seems pretty sound to me. Although again I don’t need to fetch ALL data like you would when requesting the API, maybe this is overkill?
  • Option #3 seems like an okay idea but I’m not sure how to design it with Node/TypeScript, there aren’t many resources for it and I’m also concerned about how I would setup my firewall to prevent external users from being able to access the private microservices, ufw is good enough on a single node but what if I have multiple? and what if I decide to start using Kubernetes? Just seems like a pain in the ass to setup and prone to issues.
  • I like option #4 but I’m not sure how fast it’ll be. Since this is a WebSocket server, I need things to happen in real-time as fast possible.
  • For option #5, the WebSocket "requests" that need the data are based on the socket's session, so if I moved them to the API, I would have to use RabbitMQ or a pub/sub to send the requests to my WebSocket server anyway. Seems like a slow roundabout process.

What would be the best way to approach this? Are there other options?

Reusing screen but deciding what widgets to show based on a limited number of states

I have a screen that has a certain amount of functionality that will be reused for different workflows. Each of these workflows will reuse most of the functionality of the screen, and most of the UI elements. Each workflow is predetermined, and therefore the page does not need to be dynamic in terms of logic. The things that will change on the screen will be small things, such as the title, and whether or not to show the number of the step of the current workflow.

I know of multiple ways to do this, but am wondering about best practice. I am currently using BLoC as the state management.

My current idea is to create an enum that will be passed into the widget, then use ternary expressions to determine what UI elements to show based on the state enum passed in.

How to handle conditions when using the TypeState pattern?

I am currently learning the TypeState pattern and came into a situation that is not covered by online examples.

Let's suppose that I have a Connection object with a state. The new() method for the object performs an authentication handshake with a remote server, and it's for this handshake that I want to use the TypeState pattern. My problem is how to handle conditions.

When performing the authentication handshake I need to send a Hello packet to which the server then responds with a list of authentication methods (no password, plain text password, md5 password).

From my understanding, the TypeState pattern always knows which state to return next. What happens when I have 3 options?

XML decoration with CSS

I have a valid XML file that contains a lot of information for many books. For the web design, I need to create a CSS file in order to style the representation of the data. I have already proceeded to a result but yet I can't achieve to contain all the information shown below to be placed into a box. I need to contain all the information including the title ("The Ugly Truth") into a box. But I'm struggling without HTML divs.

Until now: enter image description here

XML file:

<?xml version = "1.0"  encoding = "utf-8"?>
<!DOCTYPE online_bookshop SYSTEM "online_bookshop_new.dtd"> 
<?xml-stylesheet type="text/css" href="bookshop.css"?>

<online_bookshop free_ship="no">
    <heading>Dreamy Book Storage</heading>
    <name>The Ugly Truth</name>
    <author_list>
        <author auid="_5" name="Elin">Author: Jeff Kinney</author>
    </author_list>
    (..many elements included..)
</online_bookshop>

CSS file:

online_bookshop{
    color: whitesmoke;
    background-color: gray;
    width: 100%;
    background-image: url(bookstore.jpg);
    background-repeat: no-repeat;
    background-size: 100%;
}

heading, name, author_list, ISBN, dimensions, illustration, translation, pages, language, cost_information, other_information, weight, contact_details, other_partners, review, for_ages, publisher{
    display: block;
    text-align: center;
}

heading{
    color: red;
    font-size: 50px;
    background-color: rosybrown;
}

name{
    font-size: 40px;
    font-weight: bold;
    font-family: 'Times New Roman', Times, serif;
}

Any thoughts?

Pattern for naming query params in REST Api

Is there any guideline or pattern for query params nomenclature in the url of a Rest API?

In my case I have an entity and I want to pass some parameters in the url that refer to the IDs of other entities that compose it. I am uncertain if I should name my query params with the prefix "id" or just the name of the child entity that they refer to.

  1. /foo?idBar=1

  2. /foo?bar=1

Which one is the correct way?

Desing pattern for two inputs?

First of all, I had task 1 and it was about rest API, requesting calls using httpclient in order to use the functions of an API. We get an input from a user, either "Online" or "Offline". If it is an "Online", we request calls such as generating tokens, and we display the result on GUI using javafx or swing. If the input is "Offline", we just request calls from a mocked API that I personally made so that the program can be run even if the server is down or the internet is cut off. I used a facade pattern here in order to flexibly and simply change in between online and offline.

In the main method, it goes like this:

if(input == "online") {
    facade.online();
} else if (input == offline) {
    facade.offline();
}

The second one is the extension of task 1. They are similar to each other but the thing is, we get two inputs in which they are, the first one is the same as the one in task 1, but the second input is for the output of the result. For example, saying that we have A and B APIs and we get information/data from A by requesting calls, then we output the result through the B API (B can be an api like a pastebin, which we can save the result by creating a note on the pastebin site). If the second input is "Offline", we just save the result on a notepad.

I need to keep the facade pattern here, but what kind of design pattern should I apply in order to cover the second input as well?

I am thinking of using Factory or Strategy pattern for it, and am doing some researches for that, but still not getting ideas of how to collaborate facade with factory or strategy pattern...

Thanks.

mardi 25 mai 2021

star pattern using ternary operator

<?php
for ($row = 1; $row <= $_POST["number"]; $row++)
{
for ($col = 1; $col <= ($row >= ($_POST["number"]/2) ? ($_POST["number"]+1)- $row : $row); $col++)
    {
        echo '* ';
    }

     echo "<br>";
}
print(json_encode(count($row)));

?>

the question is to print the pattern and also the total number of stars in each row. i tried degugging my self but if i change the condition and only for some inputs the answer is correct. final

How to achieve reusability or avoid the parent interface editing in OOP

Let say I have the following interface,

interface Component{

 public String name();
 public Integer id();

}


class ButtonComponent implements Component{

 public String name(){
    return "button";
 }
 public Integer id(){
    return 123;
 }

}

Then I'm using the component like this.

class ComponentHolder {

  public static Component getButtonComponent(){
    return new ButtonComponent();
  }

}

Component component = ComponentHolder.getButtonComponent();

component.name();
component.id();

Later on, I have the new component called ImageComponent and I want to get dimension of that image so how I can add the dimension method in the ImageComponent without editing the parent because if I edit the parent, I have to define the dimension in the ButtonComponent also.

class ImageComponent implements Component{
  public String name(){
    return "Image"
  }
  public String id(){
    return 111;
  }
  public String dimension(){
    return new int[]{300,250};
  }
}

class ComponentHolder {

  public static Component getButtonComponent(){
    return new ButtonComponent();
  }
  public static Component getImageComponent(){
    return new ImageComponent();
  }


}

Component component = ComponentHolder.getImageComponent();

component.name();
component.id();
component.dimension(); // Compile Time Error, no dimension is defined in the Component Class.

Are inner functions a bad practice in python? [closed]

According to the SRP principle, a function shouldn't do more than one action in one's code. In contrast, we have python inner functions, where you can define one function inside another. Can it be interpreted as a bad practice?

Graph - modelling node with two parents

I have a graph with nodes, and I need to follow from leaf to root, and to know the single path - even when there are two parents for some of the nodes. Example - Child is the same concept, that can belong to Parent 1 or Parent 2. Leaf 1 and Leaf 2 are also concepts that belong to Child either through Parent 1 or Parent 2. So it can happen that some nodes under Leaf 1 have parent structure of Parent 1 -> Child -> Leaf 1 -> * or Parent 2 -> Child -> Leaf 1 -> *. If modeled using the following approach, that information is lost:

enter image description here

So far, I have a few approaches to disambiguate this:

First one is duplicating all the nodes - everything is separated (at a cost of duplication).

enter image description here

Second one is using labels on the edges - but still duplicating some of the nodes:

enter image description here

And the third one is also using labels - without duplicating nodes, but labels are further away from parents:

enter image description here

Is there any other solution for this? Are there any best practices in modelling this kind of graph?

Star pattern in php

<html>
    <body>
    <form action="" method="post">
    input:<input type="number" name="number">
    </form>
    <?php
    for ($row = 1; $row <= $_POST["number"]; $row++)
    {
    for ($col = 1; $col <= ($row >= ($_POST["number"]/2) ? ($_POST["number"]+1)- $row : $row); $col++)
        {
            echo '* ';
        }
    
         echo "<br>";
    `enter code here`
    print(json_encode(count($row)));
    
    ?>
 

if i give the input 12,13 and so on i am not able to get correct output.

current output:

current output

expected Output:

expected output

and i want to get the total number of stars count for each row.

What does "Provider" mean?

I've seen the term Provider used in various packages and language. What does Provider generally mean? Is the meaning the same in all these examples? Is this a design pattern?

Does storing host and port data in an app makes the server vulnerable?

I recently started development and was wondering. Every frontend application needs a host address and service port to connect to the backend server and the databases. For example when you use fetch in React you cannot avoid addressing the server, which can lead traces for many important internal services exposed, which can be extracted from the source code.

Doesn't that leave the system (backend server) exposed and vulnerable ?? And what can be best practice to avoid such thing from happening ?

PHP - third party rest call, wait for response, prevent reload

I've got a logic problem. Application is in php, written by me. There's a form where the user enters some data and press a button to submit. I know the Post/Redirect/Get pattern to prevent the site reload. In my case when the user press the button im talking with a third party rest api and need to wait for an response to store it in a database. So I cant close the current form till I've got my reponse. The response taking 5-10seconds.

Is there a way to handle this scenario?

How to design function overriding with different arguments in python

I am making a Machine Learning pipeline repository. I have a BasePipeline class and 2 child class - TabularPipeline and ImagePipeline. Both the child classes have a function named enable_cross_validation(). Since the cross-validation techniques differ, the parameters of both the enable_cross_validation function differ.

TabularPipeline has 4 arguments namely method, metrics, n_split, validation_split whereas ImagePipeline has only validation_split.

Now I have a few design strategies but each has its own flaws. First, I used all four arguments in the Base class and only one argument in the Image class. This approach shows that the signature doesn't match (Just a convention issue, not a technical issue). Secondly, I used *args and **kwargs in the Base and define specific parameters in the child class function, but the coding guidelines say that we should always define the function signature and not keep the arguments dynamic. The third might be to keep the signature the same but don't use arguments in Image class, which doesn't sound good.

I know none of them is technically wrong but the design isn't good. I need a suggestion on better design or handling parameter variations in a subclass. Please note that there might be another parameter in Image that won't be there in the Base or Tabular class.

Composite pattern simultaneous task

I have been reading about the composite pattern but I don't know if fits in my problem, actually I need to manage a hierarchy of events like, for example, send an email, send SMS, and of course, these events could have children. The thing is I need to run in parallel tasks according to the answer of the first "node" and so on. they depend on each other at the flow level but the process of executing the tasks is independent.

I attached an example of what do I need.

  1. The first task is to send the email to 100 people.
  2. The tree hierarchy allows conditional events. So in this case I added a conditional that verify if the email was successful. At this point, I need to check in my analytics which people receive the email. So assuming that 25 received the email and 75 not received the email.
  3. The last step is to send an email to the 25 who receive the email and for the other 75 an SMS will be sent to them (Those tasks have to run parallel).

example diagram

Do composite patterns could fix this problem? I mean I don't want to "hack" the pattern, even I was planning to use it with a chain of responsibility but maybe the parallel task could corrupt the CoR pattern.

How to do modular programming best? (python)

I have (five) categories of products and I want to sort/rank the products in each category separately. For that I have (four) different steps/rules to do the sorting of the products, but there are small differences in calculating the sorting among the categories:

  • For each step/rule I need the possibility to turn "on/off" the particular step for a specific category
  • For each step/rule there are different parameters for each category.

Have you got some ideas how to do this quite modular in python?

lundi 24 mai 2021

How to enforce respect method execution order access in c#

Long story short, i have following class:

   public class FlowBasePipeline<T>{
   private List<StepBaseBusiness<T>> stepList = new List<StepBaseBusiness<T>>();
    
        public void Push(StepBaseBusiness<T> step)
            {
                stepList.Add(step);
            }
    
             public void Trigger(T result)
            {
                foreach (var step in stepList )
                {
                    result = step.Execute(result);
                    if (!result.IsSuccess)
                    {
                        break;
                    }
    
                }
            }
}

What I'm looking for is forcing programmer to call Push method in the first place and then give them access to Trigger method, in this case following scenario is not allowed

var pipeline=new FlowBasePipeline<MyStepResult>();
pipeline.Trigger()// Trigger method is not recognized

we should first call Push method

var pipeline=new FlowBasePipeline<MyStepResult>();
pipeline.Push(new MyStep()).Trigger()//Now Trigger is recognized

What I've done:

I applied explicit interface method implementation as follows to get it to work:

public interface IBasePipeline<T> where T:BaseResult,new()
{
    void Trigger();
    IBasePipeline<T> Push(StepBaseBusiness<T> step);
}


  public class FlowBasePipeline<T>:IBasePipeline<T> where T:BaseResult,new()
   {
          private List<StepBaseBusiness<T>> stepList = new List<StepBaseBusiness<T>>();
        
            public IBasePipeline<T> Push(StepBaseBusiness<T> step)
                {
                    stepList.Add(step);
                    return this;
                }
        
                void IBasePipeline<T>.Trigger(T result)
                {
                    foreach (var step in stepList )
                    {
                        result = step.Execute(result);
                        if (!result.IsSuccess)
                        {
                            break;
                        }
        
                    }
                }
    }

Now it works well and we don't have access to Trigger method before Push method, but from my prospective it's not a good way as we might need more level of orders and i don't know how it could be done in this way.

Is there any pattern or strategy to implement this kind of orders?

Update:

we need to call push method multiple time

var pipeline=new FlowBasePipeline<MyStepResult>();
pipeline.Push(new MyStep1()).Push(new MyStep2()).Trigger();

naming convention: What is the difference between "from" vs "of" methods

From naming conventions and usability: What is the difference between "from" vs "of" methods in a class? when to create each one?

Repeating vibration pattern of notification channel

Is there any way to repeat the vibration pattern of the notification channel without using the Vibrator class?.. This is for alarm notification using full screen intent.

Do i correctly use PRG pattern in Java servlet or should i do someting else?

I have this controller and in Get method I use request dispatcher and in Post I use redirect.

@WebServlet(name = "ControllerOrder", value = "/User/Order")
public class ControllerOrder extends HttpServlet {
    private static final Logger LOGGER = Logger.getLogger(ControllerOrder.class);
    private MySQLCarCategoryDao categoryDao;
    @Override
    public void init() throws ServletException {
        super.init();
        MySQLDAOFactory dao = (MySQLDAOFactory) getServletContext().getAttribute("MySQLFactory");
         categoryDao = (MySQLCarCategoryDao) dao.getCarCategoryDao();
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ImageManager manager = ImageManager.getInstance();
        List<CarCategory> carCategories = categoryDao.findExistingCarC();
        List<ToggleButton> buttons = IntStream.range(0, carCategories.size())
                .mapToObj(i -> {
                    ToggleButton button = new ToggleButton();
                    button.setIcon("img:data:image/png;base64," + manager.getBase64String(manager.imageToByte(carCategories.get(i).getCarCategoryImage())));
                    button.setValue(carCategories.get(i).getCarCategory());
                    button.setSlot(i+1+"");
                    return button;
                })
                .collect(Collectors.toList());
        ObjectMapper mapper = new ObjectMapper();
        try {
            request.setAttribute("CarCategories",carCategories);
            request.setAttribute("CarCategoriesButtons",mapper.writeValueAsString(buttons));
        } catch (JsonProcessingException e) {
            LOGGER.error(e);
        }
        request.getRequestDispatcher("/WEB-INF/view/order.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        String login = (String) session.getAttribute("Login");
        String userAddress = request.getParameter("userAddress");
        String userDestination = request.getParameter("userDestination");
        String[] stingNumbers = request.getParameterValues("numOfPas");
        String[] categories = request.getParameterValues("categories");
        if(stingNumbers != null && stingNumbers.length > 0&&categories != null && categories.length > 0) {
            OrdersMaker maker = new OrdersMaker();
           String message = maker.makeOrder(stingNumbers,categories,userAddress,userDestination,login);
            if(message.startsWith("false")){
                response.sendRedirect(request.getContextPath() + "/User/Order?NotAvailable=" + message);
                return;
            }
            response.sendRedirect(request.getContextPath() + "/User/Order?takenTime=" + message);
        }
    }
}

I know you could say this pattern is easily understand but I want to know that I'm doing all right. Thanks for answering.

Production-ready WebSocket IOT System - Software Design Advice

I'm developing a system to control a range of IOT devices. Each set of devices is grouped into a "system" which monitors/controls a real-world process. For example system A may be managing process A and have:

  • 3 cameras
  • 1 accelerometer
  • 1 magnetometer
  • 5 thermocouples

The webserver maintains socket connections to each device. Users are able to connect (via a UI - again with websockets) to the webserver and receive updates about systems which they are subscribed to.

When a user wants to begin process A, they should press a 'start' button on the interface. This will start up the cameras, accelerometer, magnetometer, and thermocouples. These will begin sending data to the server. It also triggers the server to set recording mode to true for each device, which means the server will write output to a database. My question:

Should I send a single 'start' request from javascript code in my UI to the server, and allow the server to start each device individually (how do I then handle an error, for example if a single sensor isn't working - what about if two sensors don't work?). Or do I send individual requests from the UI to the server for each device, i.e. start camera 1, start camera 2, start accelerometer, startRecording camera1, etc. and handle each success/error state individually?

My preference throughout the system so far has been the latter approach - one request, one response; with an HTTP error code. However programming becomes more complex when there are many devices to control, for example - System B has 12 thermocouples.

Some components of the system are not vital - e.g. if 1 camera fails we can continue, however, if the accelerometer fails the whole system cannot run and so human monitoring is required. If the server started the devices individually from a single 'start' message, should I return an array of errors, or should the server know which components are vital and return a single error if a vital component fails. And in a failure state, should the server then handle stopping each sensor and returning back to the original state - and what if that then fails? I foresee this code becoming quite complex with this approach.

I've been going back and forth over the best way to approach this for months, but I can't find much advice online around building complex, production-ready IOT systems for the real world. If anybody has any advice or could point me towards any papers/books/etc. I would really appreciate it.

Thanks in advance,

Tom

Java Decorator Pattern

I'm trying to implement the Java decorator pattern in my project. Basically the project has two sets of warriors (aggressive and defensive) and I created an abstract warrior class that is the parent to the two different types of warriors. Aggressive warriors and defensive warriors have their attack, defense, and boost fields calculated differently. I have created a decorator class that manipulates the getDefense() method where I just get the double of the defense. Now I'm supposed to calculate the attack, defense, boost, and power of this decorated warrior class. I was able to pass most of the test but the tricky part came when I was supposed to calculate the attack, defense, and boost twice with different return values. For example defensive warrior calculates defense by adding the defense to (2*level) but aggressive warrior does the same by just adding the defense + level. This is where I run into trouble because I'm not sure how to use the same method twice with two different calculations.

public class ArmoredWarriorDecorator extends Warrior {

    Warrior warrior;

    public ArmoredWarriorDecorator(Warrior warrior) {
        super(warrior);
        this.warrior = warrior;
    }

    @Override
    int getDefense() {
        int defense = (int) (2 * warrior.defense);
        return defense;
    }

    @Override
    public int calculateAttack() {
        return (int) warrior.attack + warrior.level;
    }

    @Override
    public int calculateDefense() {
        return (int) (warrior.defense * 2 + (2 * warrior.level));
    }

    /*
     * @Override public int calculateDefense() { return (int) (warrior.defense * 2 +
     * (warrior.level)); }
     */

    @Override
    public double calculateBoost() {
        return warrior.defense;
    }

}
@Test
void double_defense_calculate_defense_defensive() {
    Warrior warrior = new ArmoredWarriorDecorator(new DefensiveWarrior.Builder(1).defense(10).build());
    assertSame(22, warrior.calculateDefense());
}

@Test
void double_defense_calculate_defense_aggressive() {
    Warrior warrior = new ArmoredWarriorDecorator(new AggressiveWarrior.Builder(1).defense(10).build());
    assertSame(21, warrior.calculateDefense());
}

Where should I put the actual computation functions in my MVC Java project?

I have simple java project with separated DAO classes, Controllers and Models.

First of all, who should care/use DAO instances? I have DAO interfaces and classes that manage queries to DB, but the actual instances of this DAO classes should be in Controllers or Models?

Then, the actual computation of what the controller receives from the View, where should I manage it? Should I pass all the inputs to the model and create a method that manages and calculate the result and then return it to the controller? Or the controller should have this method?

I don't find clear answers on the internet regarding this aspect of MVC.