mardi 31 mars 2020

How can I make algorithm like that

How can I make algorithm like I want to put LOT'S of numbers and if there is 1 digit number, let's say a, then it's coordinate with (a;0), if two digit number let's say ab, then coordinate (a;b), 3 digit number abc (a+b; c) and etc. Help? :d

Can't implement DAO design pattern in Java application [duplicate]

I'm a newbie in Java and I'm trying to design an application that has methods to fetch data from a database getCountries(), a method that finds countries in the table by searching for an input ID value findCountryByCode(int codeID) and finally, a method that saves new countries to the table called saveCountry(Country countries). I am asked to use all the good practices of OOP and design patterns in this exercise.

I have several classes managing the data encapsulation but I got stuck trying to debug some output errors. The class that connects to the database MySqlCountryDAO establishes a connection but not only doesn't return any table values on the terminal, instead, I'm prompted with a "java.lang.NullPointerException". I did my research but could not find out why this error appears there. Would anyone be able to have a look at this class and give me a light, please? Here is the code for the class that connects to the DataSource class [i.e. the database connector].

public class MySqlCountryDAO implements CountryDAO {

DataSource db = SingletonInstance.getInstance();

/**
 * Returns an ArrayList of all the Countries in the database
 * @returns arrayList of country Objects
 */
@Override
public ArrayList<Country> getCountries() {

    ArrayList<Country> countries = new ArrayList<Country>();
    String query = "SELECT * FROM country"; // MySQL query
    ResultSet rs = db.select(query); // catch the ResultSet and place the result of the query in the result set

    int code = 0;
    String name = "";
    Continent continent = null;
    long surfaceArea = 0;
    String headOfState = "";
    Country c = null;

    // loop over the resultSet to fill ArrayList w results
    try {
        while (rs.next()) {
            code = rs.getInt(1); // don't quite get it why starts at 1
            name = rs.getString(2);
            continent = Continent.valueOf(rs.getString(3));
            surfaceArea = rs.getLong(4);
            headOfState = rs.getString(5);

            //builder pattern to be implemented here
            c = new Country(code, name, continent, surfaceArea, headOfState); //new instance of Country class
            countries.add(c);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return countries;
}

}}

And the main class:

public class Main{

public static void main (String[] args){
    /**
     * instance of the client connecting to the DataSource class
     */
    MySqlCountryDAO dao = new MySqlCountryDAO(); //instance of dao

    ArrayList<Country> countries = dao.getCountries();
    for (Country c : countries){
        System.out.println(c);
    }
}
}

Below, the output returned when I run the code. SQL Exception: java.lang.NullPointerException Exception in thread "main" java.lang.NullPointerException at MySqlCountryDAO.getCountries(MySqlCountryDAO.java:28) at Main.main(Main.java:11)

I don't know what is causing it nor how to debug it. And there are a lot of other features I want to implement on it but I can't test them until the main app runs. Would really appreciate inputs to fix the problem and welcome suggestions to improve the program's structure as well.

Link for GitHub with the complete project is here.

Thanks a million!

Junction table with DAO design pattern

I have a question regarding the DAO design pattern.

I have 3 tables called user, role and user_role. In my application I have two DAOs, UserDao and RoleDao. I also have two services that use the DAOs, UserService and RoleService.

How can I do if when I get all the users I also want to get the roles associated to each user? Should I have my user domain model populated with all the information in the UserDao performing all the neccessary queries to all related tables? Or should I have the UserService service call both Dao's to get the user first and then their roles to fill user domain model (entity)? Which way of doing it is the most correct in relation to good practices? Is a new DAO related with the junction table needed?

Thank you very much!

Solution: Iterator which doesn't know if it has a next element

I wrote an iterator, which returns subgraphs of a fixed size of another given undirected simple graph. It maintains an internal graph which is the currently calculated subgraph and has private stacks and lists from which it calculates the next subgraph.

It is not possible to know if the iterator can return another element, because maybe the algorithm terminates when trying to find the next subgraph.

In this design, the pattern of next() and hasNext() which Java offers doesn't work out. I currently wrote my own Interface BlindIterator with the following abstract methods:

 /**
 * @return True iff the current element is a valid return.
 */
public boolean hasCurrent();

/**
 * @return Returns the current element, but does NOT generate the next element. This method can be called


 * as often as wanted, without any side-effects.
 */
public T getCurrent();

/**Generates the next element, which can then be retrieved with getCurrent(). This method thus only provides
 * this side-effect. If it is called while the current element is invalid, it may produce and exception,
 * depending on the implementation on the iterator.
 */
public void generateNext();

Is this a common pattern and are there better designs than mine?

c++, Is there any good solution for Message Sender to support send method about various type?

I want to make MessageSender to support send method about various type and satisfy followings conditions.

condition A) 'send XXX Type Message' can be added later (=Easy to expand)

condition B) each sendXTypeMessage is called in other thread (=Each method needed to be thread independent)

first my thinking was followings

class MessageSender
    {
    public:
     sendATypeMessage(ATypeData)
     sendBTypeMessage(BTypeData)
     sendCTypeMessage(CTypeData)
     ...(it can be added other type later)
    }

But in case of this, when I want to add sendDTypeMessage(data). I have to modify MessageSender class.


second my thinking was followings

class XTypeData : public IMessage
{
...
}
class MessageSender
{
public:
 sendMessage(const IMessage& data); 
}
MessageSender::sendMessage(const IMessage& data)
{
1) mutex lock
2) switch(check message type)
3) do something...
}

but in case of this, I have to use mutex lock in sendMessage.

then it can cause performance issue because each message sender thread can be blocked in sendMessage.


Is there any good solution to satisfy these conditions?

Pattern for developing an indie game

I want to create my game in Unity3D, but to make it all logical and at least with some architecture + it was not too difficult to expand the functionality of the game. What are the approaches or patterns for this?

Perhaps the game concept will help: Typical single player roguelike style game

enter image description here

How to extract numbers from string using a pattern?

I have the following ten rows in a pandas dataframe. I want to extract the coordinates as in [49,49],[31,78] etc.(for each row).

I tried to use string extract but I couldn't figure out the pattern.

[{'y': 49, 'x': 49}, {'y': 78, 'x': 31}]
[{'y': 78, 'x': 31}, {'y': 75, 'x': 51}]
[{'y': 75, 'x': 51}, {'y': 71, 'x': 35}]
[{'y': 71, 'x': 35}, {'y': 95, 'x': 41}]
[{'y': 95, 'x': 41}, {'y': 88, 'x': 72}]
[{'y': 88, 'x': 72}, {'y': 75, 'x': 77}]
[{'y': 25, 'x': 23}, {'y': 15, 'x': 39}]
[{'y': 15, 'x': 39}, {'y': 20, 'x': 33}]
[{'y': 85, 'x': 61}, {'y': 80, 'x': 67}]
[{'y': 80, 'x': 67}, {'y': 61, 'x': 59}]
[{'y': 61, 'x': 59}, {'y': 45, 'x': 45}]

Java SOLID Principals Pratice Sources Recommandation

I want to master SOLID Principals using Java. I actually made several researches about the topic and understood as well the concepts but i need now to pratice in order to assimilate it as well and so that it becomes as a second nature for me.

Any recommandation (eBook, Book, Online Free Course, ...) but for pratice purposes. Basically i would like to have a kind of exercices where the problem is given, a SOLID Design is required, and a provided solution to compare with mine.

Thank you in advance

How to extract a pattern from PDFs in R

I have several pdfs with dates in this format: 01.04.2020. I need to extract these dates. I am new to programming, so my knowledge is very limited. I tried using the keyword_directory function, where I am able to see which of the documents has the pattern, but it doesn't say which pattern it is. Only if it has or not.

Does anyone know about other functions I can use? Thanks.

result <- keyword_directory(folderwithpdfs, 
                            keyword = "[:digit:].[:digit:].[:digit:]",
                            surround_lines = 0, full_names = TRUE)

Regex Valdation Pattern Required

Can anyone here tell me about creating this validation pattern?

all sentences start with a capital, the message ends with a full stop. there are no spelling mistakes.

lundi 30 mars 2020

Best practices for creating csv file(s) with multiple record types

I am trying to build a csv file format for a complex type that follows a structure similar to a Car (A) which has Wheels (B) and Speakers (C), wherein each of these entities (Car, Wheel, Speaker) will also have their own properties specific to them (such as Car's color, Wheel's Air Pressure, Speaker's decibel).
I wanted to know if there are general best practices with regard to organizing multiple record types (in this case these 3 entities) in a csv format which make extracting data from the file simpler and error-free.
Should I create 1 file per record type or can group all of these 3 in single file?
If I put them in single file, should i organize them together per entity type (A-A-A-B-B-B-C-C-C) or per object (A-B-C-A-B-C-A-B-C)?

The csv file(s) will be loaded daily as a batch into a SQL database that has these 3 entities relationship in a normalized structure.

What is an envelope pattern in Pubsub messaging?

I am looking for some resources in understanding the envelope pattern and google isn't being too helpful. Can someone illustrate this with an example? For more info, I am working with Pubsub in Python and I'm looking to tag messages with some additional info (apart from plainly adding that info in the message body) for complex applications.

How can I create a connection manager and process query result in multiple ways? (Java)

sorry for the long post. I will try to be as clear as possible.

I'm creating an app for my Software Engineering class and I am in front of this problem:

As suggested by one of our teachers, I should assign the responsibility of managing database resources to DAOs. I created an abstract DAO class which creates the connection to my database (it's a PostgreSQL database) to manage every connection in a single class, which opens the stream and closes it after the result of a query is consumed through an abstract method that will be implemented by many concrete DAO singleton classes. At the end of the post, there is an example of what I coded.

Everything seems fine to me because thanks to the inheritance I can connect several and different DAOs to the database, that is my case. The true point now is that I can't figure out how can I process the data inside the ResultSet, without taking care of the query that was made or what method of one of the concrete classes asked for connection.

P.S.: I tried to look for some patterns/solutions but I didn't find anything that fit my case. P.P.S.: I know that I should use DataSource instead of DriverManager, but this is what was taught in class.


The abstract class Example:

public abstract class AbstractDAO {
  private static final String URL = "my_url";
  private static final String USR = "my_usr";
  private static final String PWD = "my_pwd";

  private final Logger logger = Logger.getLogger(getClass().getName());

  protected void connect(String query){
      try(Connection con = DriverManager.getConnection(URL, USR, PWD);
          PreparedStatement pst = con.prepareStatement(query)){
          ResultSet rs = pst.executeQuery();
          processResult(rs);
      }catch (SQLException e){
          logger.log(Level.SEVERE, e.getMessage());
      }
  }
  // abstract method to process atomically the result in each DAO.
  protected abstract void processResult(ResultSet rs) throws SQLException;
}

The concrete class Example:

public class ConcreteDAO extends AbstractDAO {
  private static ConcreteDAO instance = null;

  private ConcreteDAO() {
      super();
  }

  private static synchronized ConcreteDAO getInstance() {
      if (ConcreteDAO.instance == null) {
          ConcreteDAO.instance = new ConcreteDAO();
      }
      return ConcreteDAO.instance;
  }
  @Override
  protected void processResult(ResultSet rs) throws SQLException {
      int numCols = rs.getMetaData().getColumnCount();
      while (rs.next()) {
          for (int i = 1; i <= numCols; i++) {
              System.out.println("\t" + rs.getString(i));
          }
          System.out.println("");
      }
  }
  public static void main(String[] args) {
    String query = "select name, surname from test";
    getInstance().connect(query);
  }
}

If a particular component is frequently referenced in a composite pattern, how can it be referenced?

First, sorry for my poor English.

The composite pattern is configured, as shown in the image. EventListener G, H ,I must refer to ComponentC. There are two ways to do this ,that I know.

(1) pass ComponentC's reference through ComponentA - ComponentE (2) declare static reference of ComponentC

but I think, (1) has too much code. because, ComponentC's reference is used for only ComponentE, not D,F

and I think, (2) has risk of wrong access.

then, I'd like to know if there are another ways besides (1) and (2).

I hope the questions are delivered correctly. Thank you for reading it.

enter image description here

how to get employee using optimal way by id,name ,exp

i have written below code without applying any design pattern,Is anything wrong in this code.

class Employee {
    public int EmployeeID
    { get; set; }
    public int YearOExperience
    { get; set; }
    public int Salary
    { get; set; }
    public string EmploeyeeType
    { get; set; }
}

interface IEmployee {
    List<Employee> getInformation(int id, int exp, int sal);

}

class EmployeeData1 {

    public List<Employee> GetData(int id,int exp , int sal)
        {
            List<Employee> empInfo = new List<Employee> {

    new Employee { EmploeyeeType = "P", EmployeeID = 1, Salary = 20000, YearOExperience= 2  },
     new Employee { EmploeyeeType = "P", EmployeeID = 2, Salary = 20000, YearOExperience= 2  },
      new Employee { EmploeyeeType = "C", EmployeeID = 3, Salary = 20000, YearOExperience= 2  }

        };
            return empInfo;
        }

    }

    static void Main(string[] args) {EmployeeData1 emp = new EmployeeData1();
        emp.getInformation(1, 2, 2000);
    };
}

Here is the assignment: problem

Angular @Input best practices

I have a question about the use of @Input in a component. My problem concern the use of non-primitive object. So the variable is pass by reference as the following code :

@Input() public data: any;

In a lot of project I can see some people changed directly the data as following into the child.

this.data.name = 'something';

For me it's a problem because we change also the value into the parent, and to do that we have to use an @Output. By definition an @Input is only for one way, parent to child.

For me it's an anti-pattern, is it right ?

Each time my solution is to clone the @Input into a child attribute and send it back edited by @Output to the parent. Or only the part of the object edited because for me only the parent have the responsability to edit the entire object.

Do you have a basic solution or a pattern ? Maybe the problem is because the app isn't well design and have to be more divided. Because I think it's a common problem on each app but I didn't find something in internet.

Meaning of '+' at the end of pattern in HTML [duplicate]

In HTML when using patter in input, it works when in the end it has '+', and doesnt work when there is no plus sign. Example:

<input name = "username" patterm = "[^' ']+">
<input name = "username" patterm = "[^' ']">

these lines should only allow strings without space. The first one does exactly that, but the second one always says that string doesn't meet requirements. Why is that plus sign necessary at the end?

Design pattern suggestion for system with multiple scenarios

I am working on a scenario, where I have a list of orders.
Order DTO:

public class Order{
  private int orderId;
  private String orderType;
  private String orderingSystem;

  ... GETTER & SETTERS
}


  • orderTypes can have NEW,EXCHANGE,RETURN possible values.
  • orderingSystem can have INTERNAL_SYSTEM, EXTERNAL_SYSTEM possible values.

Based on the orderType & orderingSystem I have to process every order.

Common business to be applied on every order:

  1. Order validation.
  2. Order Enrichment
  3. Execute ordering algorithm(will vary on the orderType & orderingSystem).
  4. Finally persist the list of processed orders into DB.



Possible combinations can be

  1. NEW order with INTERNAL_SYSTEM
  2. NEW order with EXTERNAL_SYSTEM
  3. EXCHANGE order with INTERNAL_SYSTEM
  4. EXCHANGE order with EXTERNAL_SYSTEM
    & so on..



How can I design my application to accommodate each and every possible combination?

objects 1:1 relation with "Pass by reference"

I have two classes User and Task:

public class User {

private Task task;
private List<Item> items;

// constructor
public User() {
    this.task = new Task(this);
    this.items = new ArrayList<>();
}

// getters

}

the Task class has a reference to User:

public class Task{

// should be always the same as user.items !!!
private List<Item> items;
private User user;

// constructor
public Task(User user){
    this.user = user;
    // Pass by reference ?
    this.items = user.getItems();
}

public void addItem(Item item){
    this.items.add(item);
}

}

Now my questions:

  1. If I add an item with task.addItem(item) will this item also be added to user.items? Is the lifecycle and the instance of user.items exactly and always the same as task.items.

  2. Actually I have a lot of methods within User.class and want to extract that methods within Task.class. With this, I have a 1:1 relationship between user and task. Is there any other design pattern for that (composition/aggregation).

Nested-loop odd pattern in Python

I want to make a pattern as shown below:

N = 1
*

N = 3
  *
***
  *

N = 5
    *
  ***
*****
  ***
    *

and so on...

Nevertheless, I write this program only works for N = 5. Could anybody please explain what the mistake is and what the solution is? Thanks.

N = int(input())
k = 1
for i in range(1, N - 1):
    for j in range(1, N + 1):
        if(j <= N - k):
            print(' ', end = '')
        else:
            print('*', end = '')
    k = k + 2
    print()

k = 2
for i in range(1, N - 2):
    for j in range(1, N + 1):
        if(j >= N - k):
            print('*', end = '')
        else:
            print(' ', end = '')
    k = k - 2
    print()

Correct implementation pattern in java: multiple classes inherit from abstract class but one method differs

I've tried to find a solution for my doubt in the forum but I haven't been able to.

On top I have an abtracts class Item. On a first depth level of inheritance I have ClickableItem and DraggableItem and them many items extend those 2 classes. Then I have a class View which contains many items (into an arraylist) and this class has 2 methods: onClick and onDrag.

What I am doing right now is to check on the onClick method all the items and if the item extends the ClickableItem, then call the onClick method of the item. Same thing for the onDrag method.

But I feel that this is not very good oop. The item object should know if it has to call that method or not, not the View class right? The View class should call a method which all the items should have in common and the items should decide whether to call onDrag or not.

Right now I have something like this:

public abstract class Item{
    int x, y;
    public Item(int x, int y){
        this.x = x;
        this.y = y;
    }
}

abstract class ClickableItem extends Item{
    protected boolean amIclicked(int x, int y);
    public ClickableItem(int mouseX, int mouseY){
        super(x, y);
    }
}

abstract class DraggableItem extends Item{
    protected boolean amIdragged(int x, int y);
    public ClickableItem(int mouseX, int mouseY){
        super(x, y);
    }
}

class ClickableImage extends ClickableItem{
    String imgRoute;
    public ClickableImage(int x, int y, String imgRoute){
        super(x, y);
        this.imgRoute = imgRoute;
    }
    public boolean amIclicked(int mouseX, int mouseY){
    }
}

class DraggableImage extends DraggableItem{
    String imgRoute;
    public DraggableImage(int x, int y, String imgRoute){
        super(x, y);
        this.imgRoute = imgRoute;
    }
    public boolean amIdragged(int mouseX, int mouseY){
    }
}

class View{
    ArrayList<Item> items;
    DraggableItem draggedItem;

    public View(){
        items = new ArrayList<Item>();
        items.add(new ClickableImage(200, 200));
        items.add(new DraggableImage(500, 500));
    }
    void onClick(int mouseX, int mouseY){
        for(Item it : items){
            if(ClickableItem.class.isAssignableFrom(it.getClass())){
                ((ClickableItem)it).amIclicked(mouseX, mouseY);
            }
        }
     }
     void onDrag(int mouseX, int mouseY){
         for(Item it : items){
             if(DraggableItem.class.isAssignableFrom(it.getClass())){
                 if(((DraggableItem)it).amIdragged(mouseX, mouseY)){
                     draggedItem = (DraggableItem)it;
                 }
             }
         }
     }
}

Does SharedViewModel violate Single Responsibility Principle?

I have one activity and 4 fragment, I have SharedViewModel which helps me to pass data from Activity to all other Fragments

                             Activity
                                |
                          SharedViewModel
                                |
         ----------------------------------------------------
         |               |                |                 |
      (Fragment A)   (Fragment B)     (Fragment C)    (Fragment D)

Now here you can see that SharedViewModel has Activity along with all Fragment's data. So, one SharedViewModel contain variables and functions of 5 different class, like variables such as LiveData, other database related functions or some network operation related functions.

1) only one function is used as a common to share data between all classes.

2) Other functions are individual functions of all other class.

so is this violate Single Responsibility Principle? If not then how?

dimanche 29 mars 2020

How to extract IDs from a matched string in FASTA files using Perl script?

I am new in Perl programming and stuck with my script.

I am trying to search for a motif in a FASTA file and if found print out the ID of the proteins containing it.

I can load my file but after putting my motif, nothing happens. I get the following error: Use of uninitialized value $data[0] in concatenation (.) or string at test.pl line 36, line 2.

Here is my code:

#!/usr/bin/perl -w
# Searching for motifs
print "Please type the filename of the protein sequence data: ";
$proteinfilename = <STDIN>;
# Remove the newline from the protein filename
chomp $proteinfilename;
# open the file, or exit
unless ( open(FA, $proteinfilename) ) {
print "Cannot open file \"$proteinfilename\"\n\n";
exit;
}
@protein = <FA>; # Read the protein sequence data from the file, and store it into the array variable @protein

my (@description, @ID, @data);

while (my $protein = <FA>) {
    chomp($protein);
    @description = split (/\s+/, $protein);
    push (@ID, $description[0]);   
}
# Close the file 
close FA;
my %params = map { $_ => 1 } @ID;
# Put the protein sequence data into a single string, as it's easier to search for a motif in a string than in an array of lines
$protein = join( '', @protein);
# Remove whitespace
$protein =~ s/\s//g;

# ask for a motif or exit if no motif is entered.
do {
print "Enter a motif to search for: ";
$motif = <STDIN>;
# Remove the newline at the end of $motif
chomp $motif;

# Look for the motif
@data = split (/\s+/, $protein);

if ( $protein =~ /$motif/ ) {
    print $description[0]."\n" if(exists($params{$data[0]}));
}
# exit on an empty user input
} until ( $motif =~ /^\s*$/ );
# exit the program
exit;

The example of the input is:

sp|O60341|KDM1A_HUMAN Lysine-specific histone demethylase 1A OS=Homo sapiens OX=9606 GN=KDM1A PE=1 SV=2 MLSGKKAAAAAAAAAAAATGTEAGPGTAGGSENGSEVAAQPAGLSGPAEVGPGAVGERTP RKKEPPRASPPGGLAEPPGSAGPQAGPTVVPGSATPMETGIAETPEGRRTSRRKRAKVEY

Let's say I would like to find motif 'PMET' in a given sequence. If it exists, I want to get an ID as an output -> O60341

Thank you very much in advance!

Any feedback very much appreciated!

Exposing Internal IDs to Users vs. Having 2 IDs on a Single Schema?

Wondering whether this is bad practice:

I'm working on an app, where users will be able to type in the id of a component and jump to that component. I will make sure that these ids will be unique & are kept short: e.g. : XXD-1, XXD-2 etc. - so that users can remember them.

However, my app is internally also making use of ids.

The question is now whether I should make the ids I am using internally (in my database in the backend, but also as refs & keys in react, redux etc.) the same ids that I expose to the user?

Or should my component have 2 separate ids: One which serves as a proper id in my database, generated by Mongo etc., and one that I expose to the user, that's sort of a pseud-id, short and memorable? I am wondering what advantages / disadvantages each approach has.

{
  id: '1201203172637612637172312887', //generated by mongodb, for example,
  mycoolappId: 'XXD-2', //just short and memorable, for users to engage with
}

I feel it might make sense to have a single id to work with and having 2 ids feels redundant, on the other hand it makes sense to me, and it would be way less prone to error, if I have the proper ids generated by mongo.

PS: I am not sure how to best tag this question, so feel free to edit the tags!

What is the recommended code structure in Java for springboot based REST microservice?

What is the recommended code structure in Java for springboot based REST web service (microservice)? What I have seen in some java projects and also managed to deduce after searching on internet is below

ApplicationMainClass (hosting static void main())

<EntityA>
    <EntityA>.java
    <EntityA>Controller.java
    <EntityA>Service.java
    <EntityA>Repository.java

<EntityB>
    <EntityB>.java
    <EntityB>Controller.java
    <EntityB>Service.java
    <EntityB>Repository.java

pom.xml

etc

Q1. Is that how (i.e. above) the code in project should be structured or why not something like below as well

ApplicationMainClass (hosting static void main())

Entities
    <EntityA>.java
    <EntityB>.java
Controllers
    <EntityA>Controller.java
    <EntityB>Controller.java
Services
    <EntityA>Service.java
    <EntityB>Service.java
Respositories
    <EntityA>Repository.java
    <EntityB>Repository.java

pom.xml

Q2. Are there any other component/layer (i.e. apart from controller, Service, Respository) that should be in code structure?

Q3. Is their any best practices documentation or blog which I can refer so that I start with a meaningful code structure rather than starting with something which then have to be refactor-ed later.

samedi 28 mars 2020

Special keyword as {id} in URI to identify special resource

I'm designing a REST API, and have a collections of items, just call it PROD;

PROD has its typicals endpoints that accept the typical operations (POST, GET and so on)

api/prods/AAAAA
api/prods/BBBBB
api/prods/CCCCC

Now, I'd like to identify a specific item called the current PROD;

The current PROD is one of the items choosed by a logic that resides completely in the backend, and should accept all the HTTP operations;

How should i create an endpoint to identify it?

is this a good choice?

api/prods/current

then, in the backend i transparently apply the operations to whatever item i consider current.

I'm trying to implements this solution but doesn't seems perfectly right.

Any ideas on how to handle this scenario right?

how to set the dependencies of bottom layer android library from top layer Android Project?

I have an Android library which acts as a service and has some personality such as receiving notification, sending notification delivery message to server, etc.

This library is dependent to some data like `server url', 'the state of user logging' and some other data. Now my problem is what is the best design to set those information to this library from the top layer Android Project(the project that uses this library). For now I have declared setter methods and set the data which is required when they are available in the top layer but I think this is not a good design. It is important to say that the url may be change periodically and I have to update the url whenever it changes.

Any help is appreciated.

C# design - How can I essentially group classes and enums in a list without an empty interface?

I am designing a text renderer. I am building the logic of how to split a string into lines to fit within the textbox. The way I would like to do this is by first splitting the full string into "Words", "Spaces" and "Newlines", then building an algorithm to measure how much can fit on one line before moving onto the next.

However, "Word" needs to be a class/struct because it wants to hold extra attributes such as "FontStyle", "Colour", etc. "Space" and "NewLine" are just markers - they don't need any data.

At the moment I have the following framework:

interface ILineComponent
{
}

struct Word : ILineComponent
{
    public string Text;
    public FontStyle Style;
    public Colour Colour;

    public Word(string text, FontStyle style, Colour colour)
    {
        Text = text;
        Style = style;
        Colour = colour;
    }
}

struct Space : ILineComponent
{
}

struct NewLine : ILineComponent
{
}

struct Line
{
    public List<ILineComponent> Segments;

    public Line(List<ILineComponent> segments)
    {
        Segments = segments;
    }
}

The idea then being I will go through the Line and measure how many (word,space,...,word,space) will fit on a line (or word,...,newline) before breaking it up to another line. At the moment this will utilise logic like:

foreach (ILineComponent component in line)
{
    if (component is Word)
    //..
    else if (component is Space)
    //...
    else if (component is NewLine)
    //...
}

But this design breaches CA1040.

How could I design this better?

How find seasonals patterns that had more than x% rate of success in a time serie - R

data = data['1990::2019'] head(data) KO.Open KO.High KO.Low KO.Close KO.Volume KO.Adjusted 1990-01-02 1.045447 1.055597 1.038680 1.055597 12128000 1.055597 1990-01-03 1.053904 1.053904 1.036988 1.040371 12976000 1.040371 1990-01-04 1.040372 1.042064 1.021764 1.035297 7841600 1.035297 1990-01-05 1.035296 1.045446 1.025146 1.026838 8305600 1.026838 1990-01-08 1.026839 1.048830 1.023455 1.048830 10064000 1.048830 1990-01-09 1.048829 1.052213 1.035296 1.040371 7419200 1.040371 tail(data) KO.Open KO.High KO.Low KO.Close KO.Volume KO.Adjusted 2019-12-23 54.52184 54.75975 54.36323 54.43262 9300800 54.43262 2019-12-24 54.32358 54.52184 54.16497 54.23436 3359300 54.23436 2019-12-26 54.44254 54.54167 54.31367 54.54167 6228500 54.54167 2019-12-27 54.53175 54.96793 54.52184 54.86880 6895500 54.86880 2019-12-30 54.70028 54.90845 54.58132 54.78949 6431700 54.78949 2019-12-31 54.72010 54.89854 54.50202 54.86880 7982600 54.86880

As I mentioned in the title, I am looking for some R code that finds seasonal patterns in a time series with the option of setup or input the rate of success as a kind of filter. The minimum time= a week and max time infinite. This example is the time series from 1990 to 2019 and despite I can have the seasonal plot and some other information I am not even remotely of finding a code that returns what I am looking for (I am so newbie). I look to have some details as weel like the % return for each seasonal pattern found and the total average as well. But this maybe I manage to do it in the future. I really appreciate if somebody could help in some way with this matter. Thank you in advance

Microservices pattern everyone should know?

I was wondering what, in your opinion, are the most important microservice design patterns that everyone should know and why.

JS callback-promise combined pattern : good or bad practice?

I'm writting some library that will provide asynchronous methods, I want the user to be able to use classic callbacks or modern promises depending on its own preference.

I was coding two versions of each methods by naming them 'myMethod' and 'myMethodPromise', then a thought came accross my mind :

Why not coding a method that combines the two patterns?

One single method with an optional callback argument, if not provided then the method returns a promise instead of calling the callback.

Would it be a good practice?

// Promise-callback combined pattern method
function myAsyncMethod ( callback = null ) {
        if(callback) {
        var result = "xxx";
        // Do something...
                callback(result);
    } else {
          return(new Promise((res, rej) => {
        var result = "xxx";
        // Do something...
        res(result);
    }))
  }
}

// Usage with callback
myAsyncMethod((result)=>document.getElementById('callbackSpan').innerHTML = result);
// or with promise
myAsyncMethod().then((result) => document.getElementById('promiseSpan').innerHTML = result);
<p>
Result with callback : <span id="callbackSpan"></span>
</p>
<p>
Result with promise : <span id="promiseSpan"></span>
</p>

**

React - Design Pattern or things to have in mind when rendering an UI based on what i fetch

I have a React app, that i now want to render differently based on what mode the app is run in. Let's say the app has 3 modes, Mode A, mode B and mode C. The app was designed to run with only 1 mode in mind and i now want to add the other 2 modes.

The app fetches data from the back-end and then renders the UI, and now, based on what mode its in, it will fetch different data from the back-end. The data it fetches will be slightly similar, but will still be in a slightly different format, so it's not like i am fetching Kittens or Puppies and then just rendering an attribute called name. Based on what mode the app is in, it will need to render more or less components. For example, if its in mode B, it will need to render a dropdown next to a profile picture, if its in mode C, it will need to render only the profile picture.

  • Are there any design patterns or ideas that i should look at before i attempt to do this major refactor/feature ?
  • Is this issue perhaps too case-specific and there is no general rule when it comes to a thing like this?

Also as a side note, if this is not the right stack exchange for this question, please let me know in the comments and i will remove it. I did search for 'design-pattern' type questions before i posted this, and they seem to exist and get a positive response. Thank you!

Java function depended of another function implementation

I want to implement a function that "reacts" to another function.

I am implementing the card game Dominion, in this game there are attack cards and reaction cards. When an attack card is played a reaction card can be played in response, changing the outcome the attack card would cause. The Cards use a Consumer Object to achieve what they are out to do, at the moment I handle reaction cards in the attack cards (if this reaction-card played then this), which leads to a lot of redundant and ugly code. I want, ideally, to be able to implement the reaction card generically for all attack cards, without having to specifically tell them what to for each card but to derive it from the attack card itself.

In my implementation there are different "items" that are executed one after another to implement a card. Sometimes after user input, I could give the reaction card these items as input. But i would still not know what exactly they do since the main functionality is handled in Consumers, which I would have access to as objects.

I heard that tensorflow in python can track your computations to compile it to c++ code, so maybe something like this is also possible here? Or there is a pattern that would be applicable?

Calling Microserice using REST or dedicated client jar

When microservices need to talk with each other, the common practice will be to have some REST (or gRPC) communication.

I'm wondering what should be a better approach? (let's assume all services are in Java) -

  1. Each service is using a freestyle REST client (e.g. OkHttp)
  2. When service A needs to talk with service X, it has to include a dependency jar library of "service X client" that hides the network communication from service A.

Let's say this is our system - where service A uses services X and Y as its data resources:

   /-X
A--
   \-Y

Here are some cases:

New Functionality in X

If service X has new functionality for A, in both approaches there will be a need to update the code of A to support it and to add new HTTP calls. If we are using a dependency JAR, we will also need to create a new version of the jar.

New versions of X / Y

Versions update in X and Y, as long as they don't break the interface doesn't require any change in A - in both approaches.

Different HTTP library versions in X & Y clients

It is possible that X & Y client libraries will include different versions of the same HTTP client - this may cause dependency library conjunction in service A.

What is the best practice these days? I found this post and this post where each of them supports the other approach.

How to populate module internal progress status to another module?

let us say I have a python 3.7+ module/script A which does extensive computations. Furthermore, module A is being used inside another module B, where module A is fully encapsulated and module B doesn't know a lot of module's A internal implementation, just that it somehow outputs the progress of its computation.

Consider me as the responsible person (person A) for module A, and anyone else (person B) that doesn't know me, is writing module B. So person A is writing basically an open library.

What would be the best way of module A to output its progress? I guess it's a design decision.

  1. Would a getter in module A make sense so that module B has to always call this getter (maybe in a loop) in order to retrieve the progress of A?
  2. Would it possible to somehow use a callback function which is implemented in module A in such a way that this function is called every time the progress updates? So that this callback returns the current progress of A.
  3. Is there maybe any other approach to this that could be used?

Pointing me towards already existing solutions would be very helpful!

How to add missing methods to classes in a type hierarchy to allow for uniform processing?

I'm using Java 8 / Java 11. I have a type hierarchy (basically dtos or Java Beans) like

public abstract class Animal {
  public abstract String getName();
  public abstract int getAge();
}

And some imeplementations providing additional properties:

public class Dog extends Animal {

  // implementation of abstract methods from base class animal

  // additional properties
  public String getSound() {
    return "woof";
  }
}

public class Dog extends Animal {

  // implementation of abstract methods from base class animal

  // additional properties
  public String getSound() {
    return "miaow";
  }
}

public class Fish extends Animal {
  // implementation of abstract methods from base class animal

  // no implementaion for "getSound()"
}

Now, I'd like to process a Collection of Animals in a uniform way, e.g.

animals.forEach(x -> {
  System.out.println(x.getName());  // works
  System.out.println(x.getSound();  // doesn't work, as Fish is missing the method
});

I was wondering, what would be a good way to implement the "missing" methods assuming that they should return a default value like "n/a" for a String.

One obvious way would be to move all the missing methods to the base class and either declare them abstract or provide a default implementation. But I'd like to have them more separate, i.e. making clear which properties were added for the "uniform processing". Another way would be to introduce a helper class using instance of to determine, if the method is missing:

public class AnimalHelper {

  public static String getSoundOrDefault(Animal animal) {
    if (animal instanceof Dog) {
        return ((Dog)animal).getSound();
    }

    if (animal instanceof Cat) {
        return ((Cat)animal).getSound();
    }
    return "n/a";
  }
}

which then gets called with an Animal:

System.out.println(AnimalHelper.getSoundOrDefault(animal));

This works, but the caller must now which methods to call on Animal directly and for which methods to use the helper.

Another solution, I came up with the adding an interface AnimalAdapter using the Java 8 feature of default implementation:

public interface AnimalAdapter {

  default String getSoundOrDefault() {
    return "n/a";
  }
}

And adding it to the Animal class:

public abstract class Animal implements AnimalAdapter {
...

which results in adding the getSoundOrDefault() method in Dog and Cat, but not Fish:

public class Dog extends Animal {
  ...
  @Override
  public String getSoundOrDefault() {
    return getSound();
  }
}

(likewise in Cat).

Any comments on the above considerations or other ideas would be highly appreciated.

C++: implementing multiple instances of an interface or an optional interface in a class

I'm having trouble finding best practice information about what I believe should be a fairly common problem pattern.

I will start with a specific (software update related) example, because it makes the discussion more concrete, but the issue should be fairly generic.

Say that I have a software updater interface:

class Software_updater {
    virtual ~Software_updater() = default;
    virtual void action1(const Input1& input1) = 0;
    virtual void action2() = 0;
    virtual bool action3(const Input2& input2) = 0;
    virtual Data1 info1() = 0;
    virtual Data2 info2() = 0;
    // etc.
};

For my first implementation A, I am lucky, everything is straightforward.

class A_software_updater : public Software_updater {
    // ...
};

A B_software_updater, however, is more complicated. Like in the A-case, it is connected to the target to update in a non-trivial manner and maintains a target connection state. But more importantly, it can update two images: the application image, and the boot loader image.

Liking what I have so far, I see no real reason to go for a refactoring, so I assume I can just build upon it. I come up with the following solution:

class B_software_updater {
public:
    Software_updater& application_updater() { return application_updater_; }
    Software_updater& boot_loader_updater() { return boot_loader_updater_; }
private:
    class Application_updater : public Software_updater {
        // ...
    } application_updater_;
    class Boot_loader_updater : public Software_updater {
        // ...
    } boot_loader_updater_;
};

I.e. I am returning non-const references to "interfaces to" member variables. Note that they cannot be const, since they mute state.

I think it is a clean solution, but I would be happy to get some confirmation.

In fact, I have recently faced the issue of having to optionally provide an interface in a class, based on compile-time selection of a feature, and I believe the pattern above is a solution for that problem too:

class Optional_interface {
    virtual ~Optional_interface() = default;
    virtual void action1(const Input1& input1) = 0;
    virtual void action2() = 0;
    virtual bool action3(const Input2& input2) = 0;
    virtual Data1 info1() = 0;
    virtual Data2 info2() = 0;
    // etc.
};

class A_implementation {
public:
#ifdef OPTIONAL_FEATURE
    Optional_interface& optional_interface() { return optional_implementation_; }
#endif
// ...
private:
#ifdef OPTIONAL_FEATURE
    class Optional_implementation : public Optional_interface {
        // ...
    } optional_implementation_;
#endif
// ...
};

I could not find a simple (as in: not unnecessarily complicated template-based) and clean way to express a compile-time optional inheritance at the A_implementation-level. Can you?

OOP Programing - Vending Machine and a Client

Problem: A Vending Machine stores diferent types of candy from different companies with different prices. For example: company A has a chocolate with price X and company B has also a chocolate with price Y and a candy bar with price Z. A client can only pay with a credit card. At the end of the day the vending machine makes the totalAmount which is the gain that it made during that day. Also the vending machine verifies if the client has enough money to buy the item

Question: Is there a design pattern or best practice that can be used in order to solve this problem? How should this problem look in a UML Diagram?

Sorry if I made some mistakes in English.

vendredi 27 mars 2020

How to avoid destroying and recreating threads inside loop?

I have a loop with that creates and uses two threads. The threads always do the same thing and I'm wondering how they can be reused instead of created and destroyed each iteration? Some other operations are do inside the loop that affect the data the threads process. Here is a simplified example:

const int args1 = foo1();
const int args2 = foo2();
vector<string> myVec = populateVector();
int a = 1;
while(int i = 0; i < 100; i++)
{
    auto func = [&](const vector<string> vec){
        //do stuff involving variable a
        foo3(myVec[a]);
    }
    thread t1(func, args1);
    thread t2(func, args2);
    t1.join();
    t2.join();

    a = 2 * a;
}

Is there a way to have t1 and t2 restart? Is there a design pattern I should look into?

Pattern for dealing with types with different interfaces in a collection

I'll start with what is it that I want to achieve. We have a graph DB that stores different types of nodes. Each type of nodes have a certain set of properties. Each property is a string in the DB, but can be an encoding of a more complicated data structure. For example, let's say we have:

PersonNode {
  name,
  age,
}

DogNode {
  breed,
  favorite_foods, // JSON-encoded list of strings
}

In our client code, we have a low-level Node class that exposes the properties of a node as a key-value map. We want to built upon this low-level Node to expose a type-safe interface to end users, so they don't have to check for key existence / decode things themselves.

A coworker proposed that we can create a different class for each type of nodes, with different getters for properties. For example (in pseudocode):

class PersonNode {
  string get_name() { ... }

  int get_age() { ... }
}

class DogNode {
  string get_breed() { ... }

  list<string> get_favorite_foods() { ... }
}

But my concern with this approach is that if we want to return different types of nodes from the DB, we need to store them in a collection, which means we need to make different node types inherit from a BaseNode. But then the user will need to do runtime type checks for each node before they can use their getters. I feel this defeats the purpose of polymorphism:

list<BaseNode> nodes = get_nodes_from_db()

for node in nodes:
  if instanceof(node, PersonNode):
    ...
  elif instanceof(node, DogNode):
    ...

Is there any pattern we can use that avoids runtime type checks, but can also give us type safety when accessing the properties of each node type?

Do forked nodes have to be joined? UML State Diagram

Do forked nodes have to be be joined in the end? And can outgoing fork nodes have guards?

Basically what I'm trying to do is return the change to the customer and continue with the car wash at the same time.

But, maybe there's a better way to do it?

UML State Diagram

Alternatives to CQRS for vertical slice architecture

In front of me lies a web API project, which is to be modernized and newly implemented. In this project I want to use a vertical slice architecture, because the layered architecture does not fit our feature-oriented approach. Also, things like the repository would become very large.

So I started to implement the project using CQRS, but now I realize that this is not appropriate either, because we have commands that need to return DTO's. This is to avoid multiple unnecessary database accesses or (as in example 1) there is no database access at all, but the result is different after each call (unlike a query).

/// Example 1: Create access token and return the result directly, no database access (no query possible)
AssetsAccessToken token = await this.createAccessTokenCommandHandler.Handle(accessTokenCommand);

/// Example 2: Create or get available storage space.
AssetsStorageSpace storage = await this.createOrGetStorageSpaceCommandHandler.Handle(storageSpaceCommand);

Are there alternative software architectures for vertical slices that can solve these problems?

Repository + factory pattern implementation for classes with multiple inheritance in PHP?

Here is the case: let's say I have a User abstract class. This class is extended into Employee and Customer subclasses.

The User class has basic attributes like name and address. Employee has an additional attribute sallary. Customer has an additional attribute membership_code.

These entities are stored in multiple tables: users, employees, and customers. The users table contains basic information about any user. The employees and customers table refer to the users table, and in each contains the additional attributes.

users table:

id | name       | address           | type
---+------------+-------------------+---------
1  | Employee 1 | First Address St. | Employee
2  | Customer 1 | First Address St. | Customer

employees table:

user_id | salary
--------+---------
1       | 5000

customers table:

user_id | membership_code
--------+---------
2       | 1325_5523_2351

Here is what I have in mind as to how these should be implemented in PHP:

abstract class User
{
    protected $id;
    protected $name;

    public static function load(int $id): User
    {
        /** @var array $data */
        $data = get_a_row_from_users_table_by($id); // this part does a query to DB

        return new $data['type']($data['id'], $data['name']);
    }

    final public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
        $this->init();
    }

    abstract protected function init();
}

class Employee extends User
{
    protected $salary;

    protected function init()
    {
        /** @var array $data */
        $data = get_a_row_from_employees_table_by($this->id); // this part does a query to DB
        $this->salary = $data['salary'];
    }
}

class Customer extends User
{
    protected $membership_code;

    protected function init()
    {
        /** @var array $data */
        $data = get_a_row_from_customers_table_by($this->id); // this part does a query to DB
        $this->salary = $data['membership_code'];
    }
}

However, I feel like the code above still seems a bit hacky to maintain. Recently I read a book discussing about domain-driven design and how the persistence mechanism should be separated into a Repository. On the other hand, I also discovered that the type-switching mechanism, for example between Employee and Customer, should be done in a Factory.

I have a bit of a grasp to the concepts of Repository and Factory, but I still failed to understand how to combine and implement those concepts into a working code.

In this case, how should the above be implemented to use Repository and Factory pattern in PHP?

jeudi 26 mars 2020

How to make one class execute multiple sub-classes which have the same template?

I have the following code design with two classes with the same methods, like this:

class Worker1:
    def __init__(self, tools=None):
        if tools is None:
            self.tools = self._get_tools()
        else:
            self.tools = tools

    def _get_tools(self):
        return ['hammer', 'nails']

    def do_work(self):
        return 1 * len(self.tools)


class Worker2:
    def __init__(self, tools=None):
        if tools is None:
            self.tools = self._get_tools()
        else:
            self.tools = tools

    def _get_tools(self):
        return ['car', 'gas']

    def do_work(self):
        return 2 * len(self.tools)

Note that:

  • both classes have the same methods inside
  • both classes have the same initialization code

Now I want to have one Master Class which can perform operations on the Worker classes. What I currently have is:

class Manager:
    def __init__(self):
        self._worker_map = {}
        self.worker_names = self._worker_map.keys()

    def register_worker(self, worker_name, worker):
        self._worker_map[worker_name] = worker

    def do_work(self, worker_names=None):
        if worker_names is None:
            worker_names = self.worker_names
        return {worker_name: self._worker_map[worker_name].do_work()
                for worker_name in self.worker_names}

# I initialize the Manager class in my module and register all the workers one by one.
manager = Manager()
manager.register_worker('Joe', Worker1())
manager.register_worker('Ben', Worker2())

This works fine for me, in the sense that I can use the manager to operate all the register workers and get information from all of them; for example:

manager.do_work() # returns a dict with keys as worker's name and values as output

, however the big issue I have here is that it only works if I don't have any input when I initialize the workers... If I want to initialize each worker with the same set of tools, that's now not possible.

My question is: How can I have a Manager class to control my workers, when I want to give each worker the same set of tools?

I guess that then I will have to somehow have all workers already register in the manager, but the manager needs to be initialized at runtime, such that I can pass to the manager the tools I want each worker to have, before the workers are initialized... but since I initialize on registration, this is currently not possible. I hope my question / example is not too confusing. I did my best to simplify as much as possible.

P.S. I was reading up on the Factory design patter, but could not truly see whether it fits my desired use case here.

Update

I think by writing this I figured it out. If I write my Manager class like so, then I can initialize it with or without the tools. However, is this a good design at all?

class Manager:
    def __init__(self, tools=None):
        self._worker_map = {
            'Joe': Worker1(tools=tools),
            'Ben': Worker2(tools=tools)
        }
        self.worker_names = self._worker_map.keys()

    def do_work(self, worker_names=None):
        if worker_names is None:
            worker_names = self.worker_names
        return {worker_name: self._worker_map[worker_name].do_work()
                for worker_name in self.worker_names}

Maintaining time in an wpf application

I'm developing a real-time wpf application in the context of certain tasks need to be executed a specific times within the day. Thus, I'm trying to decide on the best approach to maintaining time in the application. My inclination is to initialize an additional thread at application startup that will serve as the task scheduler for the application. Any ideas on design patterns here would be helpful!

Recursive inheritance as parameter

I'm looking for a solution to this recursive builder. I prefer the non-working constructor since it will help if Test class have tons of class members.

class Test
    {
        int value;
        protected Test(int value) 
        {
            this.value = value;
        }

        protected Test(TestBuilder<?> builder) // What to do here with ?
        {

        }

        class TestBuilder<T> where T : TestBuilder<T>
        {
            private int value;

            public T Value(int value)
            {
                this.value = value;
                return (T)this;
            }

            public Test BuildWorks()
            {
                return new Test(value);
            }

            public Test BuildDoesNotWork()
            {
                return new Test(this);
            }
        }
    }

Does anyone have any suggestion? C# doesn't seem to have a wildcard for generic type.

Thanks.

Angular 8+ Observable - Pattern to update underlying value?

I have a question about using Observables in Angular 8/9. My template uses the async pipe on an observable object, which is great for displaying data. But what if I want to update it? I'm looking for a good-practice pattern here.

One of my work applications has a service that communicates with an HTTP server to get an Observable. It turns that observable into a BehaviorSubject, and publishes its own observable of the BehaviorSubject. The component injects the service, gets a local copy of the observable, and the template reads its value with the async pipe. The template has an event handler that allows an edit; the component's function calls a "mutate" method on the service, which updates the subject's value, and calls .next() on it.

This seems like a lot of extra work, and I was wondering if there was perhaps a better pattern to follow. When I asked about this pattern at work, I was told that angular handles updating from observables better than plain old objects.

Thanks!

Shortened code examples:

Model:

public class Person {
    firstName: string;
    lastName: string;
}

Service:

public class PersonService {
    private personSubj: BehaviorSubject<Person>(null);
    public person$: Observable<Person> = this.personSubj.asObservable();

    public mutateFirstName(newName: string): void {
        this.personSubj.value.firstName = newName;
        this.personSubj.next(this.personSubj.value)
    }

    private getFromHttp(): void {
        this.http.getPerson().subscribe(p => this.personSubj.next(p));
    }
}

Component:

public class PersonComponent {
    // personService is injected in constructor
    this.person$ = this.personService.person$;
}

Template:

 <div *ngIf="(person$ | async) as person">
    <input value="person.firstName" (click)="mutateFirstName('Sam')" />
 </div>

Modified Composite pattern / Food, Recipes and Subrecipes

I'm having troubles implementing the Composite Pattern correctly (to make it the most efficient).

There are two entities involved: Food and Recipes. They are to be parsed from a CSV file. A Basic Food object would contain a letter (to denote if it's a food or recipe - in this case f), name, calories, fat, carb and protein. The Recipe would contain the letter r and the name of the recipe.

I'm aware that the basic food should be a corresponding leaf, and the recipe would be composite. However, the recipes in the CSV file can contain subrecipes in a way that it has a name (of food) and count (number of servings) pairs. However, the food can be a subrecipe, which raises to question how to make an optimal solution?

My first though is to make the composite hold a List<Food> to store it's composites, and have a property Map<Food, Double>. What would be the easiest way of checking if we're dealing of a certain type of food and provide CRUD-like functionalities? The program implementation is in Java.

E.g. b, FoodName, 1, 2, 3, 4 (basic food) 
E.g. r, RecipeName, foodOneName, foodOneCount, foodTwoName, foodTwoCount, ...

Parent Child Relation with restricted method access

Let's assume I have the following interfaces:

public interface IChild
{
    IParent MyParent { get; }
    string Name { get; set; }
}

public interface IParent : IChild
{
    IEnumerable<IChild> Children { get; }
}

In addition for the parent implementation there is the following abstract class:

public abstract class Parent : IParent
{
    private List<IChild> _children = new List<IChild>();

    public Parent(IParent parent, string name)
    {
        Name = name;
        MyParent = parent;
    }

    public IEnumerable<IChild> Children => _children;
    public IParent MyParent { get; }
    public string Name { get; set; }

    protected void Add(IChild child)
    {
        _children.Add(child);
    }
    protected void Remove(IChild child)
    {
        _children.Remove(child);
    }
}

Now I use the following implementation based on the interfaces and abstract class above:

public class Tree : Parent
{
    private Branch _left;
    private Branch _right;
    private Leaf _goldenLeaf;

    public Tree(IParent parent, string name) :
        base(parent, name)
    {
        _left = new Branch(this, "left branch");
        Add(_left);
        _right = new Branch(this, "left branch");
        Add(_right);
        _goldenLeaf = new Leaf(this, "the golden leaf");
        Add(_goldenLeaf);
    }
}

public class Branch : Parent
{
    private Leaf _singleLeaf;

    public Branch(IParent parent, string name) :
        base(parent, name)
    {
        _singleLeaf = new Leaf(this, "the golden leaf");
        Add(_singleLeaf);
    }
}

public class Leaf : IChild
{
    public Leaf(IParent parent, string name)
    {
        MyParent = parent;
        Name = name;
    }

    public IParent MyParent { get; }

    public string Name { get; set; }

    public void DoSomething()
    {
        // How can I have a method in the parent which can only be called
        // by the corresponding child. How to prevent the outside to call
        // the method "Inform" on the parent?
        MyParent.AskBeforeExecute(this, "data");
    }
}

The main problem I have is that I want to call a method from the parent within the "DoSomething" call which is only accessible by the children. So the "AskBeforeExecute" method can not be in the public interface of the IParent definition because then the "outer" world can also call this method. I am not sure if my idea can be implemented at all with interface as I have right now. Anyway I am stuck a little bit and I am looking for a better pattern or idea to handle this?

How do you resolve circular imports in Kotlin

I'm new to programming in Kotlin and I've already managed to run into the classic circular dependency issue - I know Kotlin can cope with those but I'd like to know how would I go about changing my design to avoid it. What structures or Kotlin functionality should I use in the following?

import myClass

interface myInterface {
    fun useMyClass(myInstance: myClass)
}
import myInterface

class myClass(myList: List<myInterface>) {
    val storedList: List<myInterface> = myList
    var myValue: Int = 10
}

I would like myClass to store multiple objects which implement myInterface, but I would also like each of those objects to reference the class they have been passed to, i.e. each call of useMyClass would have the signature of useMyClass(this).

For example, I could create a class

class implementingMyInterfaceClass(): myInterface {
    override fun useMyClass(myInstance: myClass) {
         myInstance.myValue += 10
    }
}

and call it somewhere within myClass:

implementingMyInterfaceClass().useMyClass(this)

Technically I could create another construct in the middle which would be used by myInterface and inherited/implemented by myClass, but this just doesn't feel correct. Any suggestions?

Best way to generate Feign Client for JHipster

I have to services and two entities

entity AEnt {}
microservice AEnt with A
entity BEnt {}
microservice BEnt with B

And I want to realize the relation like

relationship OneToOne {
    A{b} to B
}

but programmatically.

So I need JPA + DTO for BEnt in microservice B and only service-layer DTO and service class or service interface with implementation based on feign client (or rest template) in service A.

Is there are the best way to do this? Do I need:

  1. Copy BEntDto and Service Interface from B app to A app and implement interface manually?
  2. Extract dto POJO and interface into the third library, something like microservices-core?
  3. Maybe run service B, download OpenAPI spec, generate spring-client from it?

To clarify my problem:

Service A - Book info service

Service B - for images, ie store book cover

I need to create full info json-response for some book, ie size, color and url in s3 storage from a book. But my API and data-model not stable now, I often change data and do not want to do it manually, but completely automated (jhipster jdl and etc.)

Android common functionality in activity

I have 10 activities in my app. Some activities inherit from FragmentActivity and some from AppCompatActivity. I want to implement some common functionality for all activities. E.g. I want to implement timeout functionality for all activites, i.e I want to display warning on screen when there is no user interaction during timeout period (= onUserInteraction not called during timeout period). What is the best way to achieve this? I want to minimize having the same code in my activites. The best would be to have no common code in my activities.

Need to autowire same bean in two different controllers

I have 2 urls and two different controllers

  1. localhost:8080/myservice/foo/1/0/updatesStatus --> FooController
  2. localhost:8080/myservice/bar/1/0/updatesStatus --> BarCOntroller

For both the controller I need to autowire the same Service class.

MyService --> Interface and MyServiceImpl --> Implementation class.

@Autowired
MyService myService;

In MyServiceImpl I am updating database tables based on URL. At any point in time If both requests came at the same time with both controllers using the same service, will there be any impact like one request updating other data or fetching the wrong fields?

Phone number Regex Angular form Validation [duplicate]

I'm looking for a phone pattern (regex) that will allow these inputs: 052-5989502 052 5985402 0525985402 09-984021 09 90532352

and that will not allow

1--------------------1

-- 11 -- 111 - 111 and etc

mercredi 25 mars 2020

Java: How to run a method C of a class with methods A,B,C if methods A and B of this class are never called?

So I (newbie) am working with state design pattern and having trouble in interchanging states. For reference, there is a door, that can be in four states-closed, closing, opened, opening or pause state. So in the code that I am attaching , I am supposed to do this - door starts in closed state, up is pushed, now the door is in opening state. Now my problem is, I am not sure how to do this - when the door is in the opening state, if no button was pushed on the remote control, its state should be changed to opened. I am attaching the code for both closed and opening state classes. Any help would be appreciated. Opening State code:

public class OpeningState implements StateDoor{
GarageDoor door;
public OpeningState(GarageDoor door) {
    this.door=door;
    fullyOpen();
}
@Override
public void fullyOpen() {
    door.setState(door.OpenedState);
}

@Override
public void fullyClosed() {
    System.out.println("Can't close fully right now.");

}

@Override
public void upPushed() {
;   
}

@Override
public void downPushed() {
    door.setState(door.PauseState);
    System.out.println("Now changing to pause state from opening state.");
    }
public String toString() {
    return "OpeningState";
}


}

Closed State code:

public class ClosedState implements StateDoor{
GarageDoor door;
public ClosedState(GarageDoor door) {
this.door=door;
door.setState(door.ClosedState);
}
@Override
public void fullyOpen() {
    System.out.println("Can't open fully right now.");
}

@Override
public void fullyClosed() {
    System.out.println("Already fully closed.");
}

@Override
public void upPushed() {
    door.setState(door.OpeningState);
System.out.println("Now entering opening from closed state");
}

@Override
public void downPushed() {
    ;

}
public String toString() {
    return "ClosedState";
}


}

How to handle relational data without SQL

Context

I need to convert a WebSQL app to Indexeddb for an offline centered web app.

The intent is to have a user pull down all necessary data while on a connection, then have them travel into areas with little-to-no connectivity. The app will need to still function and periodically sync when ever a connection is available.

Caveats

Right now it seems like changing any queries is out of the question and so I will need to work with the current response, which is essentially a collection of tables converted to JSON. With the WebSQL API, they used sql operations to query data on the client using combinations of join, where, order by, etc.

I've never had a constraint like this before and am left scratching my head on what approach to take. As far as I know, Indexeddb doesn't offer any sort of relational querying, so I will need to implement that in code.

Question

What approaches could I take to mimic the functionality of sql, such as join sets of data, in JavaScript?

*Note: once I have the data on the front-end, I'm free to restructure it anyway I like that benefits managing it.

Repository - Service Pattern Sharing Entity

Think of an application designed to implement following layers:

  1. MyProject.UI (Blazor App)
  2. MyProject.Services (referenced by 1)
  3. MyProject.Repositories (referenced by 2)

    • Number 3 accesses ORM / web services (depending on the context).
    • Services layer contains Models and BL that is used by layer 1 to present the data

Question: Should the models that live in the Services layer be shared with the repository layer as well, or does the Repository layer needs to have their own entities / models to return the data? Consider the following example.

public interface IInstanceRepository
{
    Task<IEnumerable<InstanceData>> GetAllInstancesAsync(); //IEnumerable<T> is the object in MyProject.Services layer
}

public class InstanceRepository : IInstanceRepository
{
    //IEnumerable<T> is the object in MyProject.Services layer
    public async Task<IEnumerable<InstanceData>> GetAllInstancesAsync() 
    {
        //doesn't matter what happens in this part.
        await Task.Run(() => await SomeExternalDependency.GetInstances("blah blah"));
        return new List<InstanceData>
        {
            MyProp = "yeah boiii"
        };
        //doesn't matter what happens in this part.
    }
}

///////////////////////////////////////////////////////////

public interface IInstanceService
{
    Task<IEnumerable<InstanceData>> GetAllInstancesAsync();
}

public class InstanceService : IInstanceService
{
    private readonly IInstanceRepository _instanceRepository;

    public InstanceService(IInstanceRepository instanceRepository)
    {
        _instanceRepository = instanceRepository;
    }

    public async Task<IEnumerable<InstanceData> GetAllInstancesAsync()
    {
        //call the repo and get the data
        var instances = _instanceRepository.GetAllInstancesAsync(); 

        //apply business logic to data then return it
        return instances;
    }
}

///////////////////////////////////////////////////////////

# Inject IInstanceService and IInstanceRepository -> UI action -> call the service.GetAllInstancesAsync() method

PATTERN

If this is the wrong approach, how should this be structured? Should the Repository layer not return the type of the entity but a Dictionary<,> or whatever type is suitable for the return type and do the mapping in the Services layer? My understanding was to do the mapping in the Repo then return it and apply the BL.

Multi-dimensional object interface

Let's say I have a 2DPosition class:

double x;
double y;

void update(double x, double y) { ... }
double getX() { ... }
double getY() { ... }

a 3DPosition class:

double x;
double y;
double z;

void update(double x, double y, double z) { ... }
double getX() { ... }
double getY() { ... }
double getZ() { ... }

and so on. An object may need to use one of these implementations, so a common Interface is required. What is the best way to design such thing?

Dependency Injection - service accessing the private members of the client

I have a client class A which has some data structure (m_data). Now I need a function which needs to perform some operations on the data. Is it a good practice to use the dependency injection, so the given service will access m_data of the client class?

Note: There are more service, they all operate on m_data, I would just like to avoid inheritance. The reason for that is that class A is also a derived class, so there might be other classes delivering the foo() functionality, but not the m_data data structure.

class B()
{
public:
    // constructor, destructor, ...
    void foo();
}

class Service()
{
public:
    // constructor, destructor, ...
    void foo(Data);
}

class A() : public Base
{
public:
    A(Service &_serv) :
        m_serv(_serv)
    {
        init_data();          // initializes m_data
    }

    void foo()
    {
        m_serv.foo(m_data)    // is this a good practice?
    }

private:
    Service m_serv;
    Data m_data;
}

I guess this is a bad practice, so could someone provide some good design patterns, or any other solutions? Thanks!

Would it be wrong to call another microservice on the same server?

I have a microservice architecture where several .war are deployed under the same weblogic server. I need to orchestrate the call between 2 of them, is it correct to create a 3rd service that does that? Or it is more correct to leave the orchestration to the frontend?

Best pattern for converting between potentially lossy types, ie Coordinate in DMS

So I'm working on a program that uses coordinates in two formats, decimal and degrees minutes and seconds. I have a requirement to allow the user to convert between the two on a drop down.

All of this is fine, but I started to think that I could use a pattern of some sort to store which version was originally entered and is the 'truth', and which is the lossy one. However this would need to switch if someone entered 10.123 in decimal, converted it to DMS as 10:07:23 (where the seconds would be 22.8 if using a decimal).

Just for context, the conversion is below, due to the divisor containing a factor of 3, its going to be inherently lossy.

double decimal = 10.123;
int degrees = (int) Math.floor(decimal);
int minutes = (int) Math.floor((decimal - degrees) * 60d);
int seconds = (int) Math.round(((decimal - degrees) * 60d - minutes) * 60d);

I feel like the observer pattern may be the best way to start, but I'll be the first to admit my knowledge of patterns is limited.

Happy to provide more context if needed.

Memento pattern and violation of encapsulation

Across the internet I come across with examples of implementation of memento pattern which I consider are fully incorrect. They can be written in both Java and C#.

Here a several of them

  1. Incorrect implementation of Memento pattern 1
  2. Incorrect implementation of Memento pattern 2
  3. Incorrect implementation of Memento pattern 3

The code:

public class Originator
{
    private string _state; //the private field of originator that shouldn't be exposed!!!!

    public Memento CreateMemento()
    {
        return new Memento(_state);
    }

    public void SetMemento(Memento memento)
    {
        _state = memento.GetState();
    }
}


public class Memento
{
    private string _state;

    public Memento(string state)
    {
        _state = state;
    }

    public string GetState()
    {
        return _state;  // here caretaker can access to private field of originator!!!
    }
}


public class Caretaker
{
    public Memento Memento { get; set; }
}

In code I left comments that should describe situation.

The caretaker class can read private field of originator through memento that violates one of the main principles of memento pattern:

The object's encapsulation must not be violated.

So the question is am I right?

mardi 24 mars 2020

Design pattern to call a list of methods selected by user C# [closed]

I have 108 methods that generate custom SQL query strings and then each method query string is executed. These methods are in their own class called “Reports”. Each of these methods take in the same 4 parameters. All 108 methods return different results.

I have a web application that lists all the 108 reports(why I have 108 methods from above) and the user can select which reports they would like to run. I have a database table that has the list of all 108 reports. The table design is Report (ID, ReportName, ReportType, Description). The methods I have created are named after the “ReportName” in the database table.

Method Naming example: Date Gaps -> DateGaps

When the user submits the reports to be ran, a List is created containing the report ID from the Report Table.

I was thinking about creating a method in my “Reports” Class that would have a foreach loop to loop through the list of report IDs and have a switch statement inside to call the report method based on the report ID. This would result in 108 case statements and that seems a little ridiculous.

I feel like this is a bad design from a maintaining standpoint. I also thought about using reflection, but I feel that will be to slow. I have been look at the Strategy pattern, but I am not sure if that is the best approach. My main question is, would a switch statement be acceptable in this case or would a pattern be better?

This might not be a normal question type. Trying to create a discussion for the best design pattern.

Call API method PUT from POST or vise versa

I know what both PUT and POST method is and use for, but I wanted to know a few things in my current scenarios.

Just before that, brief out about my API:

  • POST endpoint for insert new records and in request body has existing record client will get the duplicate and ask for do the PUT as record already exists.

  • PUT for updating my existing records and if not existing record is coming on the body client will get the message to use POST as the record is new one.

  • GET for comment select operations

Our use case -

we wanted to automate this API interaction, I used PostMan for all my development/testing part.

Now, I am writing the Azure DevOps pipeline to automate the insert and update stuff for this I would get the input from one repository which the user will update with required input, the input will be in the JSON format. I will have one bash script for checkout the inputs repository and I will loop through the all input JSONs and will those API.

My question is - as I have a separate endpoint for insert and update... so how I can automate it as from the pipeline? I would gonna call one POST/PUT for the given JSON input.

Should I have to write PUT call within the POST method when I find data having already existed and same in case of PUT if an incoming record is new I should have to call POST method instead.

I think this will violate the separation of concern principle for any of the method.

let me know what is the best way to deal this condition with best practices.

Database Schema for a file storage System

I need to build a file storage system based in users with permissions (like a Dropbox)

Additional constraints:

  • the file content will be stored in AWS S3 Bucket (every user will use a specific folder created for that user only)
  • a user can contain multiple files or folders

  • each folder can contain multiple files or other folders (like a
    normal file system)

  • a user can rename or relocate any of his own files

  • a file can be shared temporarily with a link (that expires after 1
    hour or some predefined time)

  • it should be secure

What is the best way yo create a relationship between them?

this is my current design:

enter image description here

Is this an incorrect warning?

Let's see this code pattern I'm seeing often:

struct Foo
{
    template <typename T>
    T* as1() { /* ... */ }

    template <typename T>
    T* as2(T*) { /* ... */ }  
};   

The former method is to be used like this:

    SomeComplexTypeAndNotAuto * a = foo.as1<SomeComplexTypeAndNotAuto>();

While the latter is more convenient to use since you don't need to repeat the complex type:

    SomeComplexTypeAndNotAuto * a = foo.as2(a); 

However, most compiler rejects the 2nd case with a Wuninitialized warning:

warning: variable 'a' is uninitialized when used within its own initialization [-Wuninitialized]

It's quite clear the variable is not used in the initialization, only its type is. Is there a way to avoid this warning without dealing with the hell of per-compiler pragma ?

What's the best func signature for a function that fetches an object and might not find it?

This is a very similar question to this, but focusing Go implementation.

Let's say you have a function that fetches an object using some ID. The function might not find that object.

Something like:

func FindUserByID(id int) User {
    ....
}

How should you handle a situation where the user is not found?

There's a number of patterns and solutions to follow. Some are common, some are favorable in specific languages.

I need to choose a solution that is suitable in Go (golang), and so I want to go through all the options and get some feedback on what's the best approach here.

Go have some limitations and some features that can be helpful with this issue.

Option 1:

The obvious solution is to have the "Find" function return nil, in case the object wasn't found. As many know, returning nil is unfavorable and forces the caller do check for nil, making "nil" the magic value for "not found".

func FindUserByID(id int) User {
    ...
    if /*user not found*/ {
       return nil
    }
    ...
}

It works. And it's simple.

Option 2:

Returning an exception - "NotFound". Goland does not support exceptions. The only alternative is to have the function to return an error, and check the error in the caller code:

func FindUserByID(id int) (User, error) {
    ...
    return errors.New("NotFound")
}

func Foo() {
    User, err := FindUserByID(123)
    if err.Error() == "NotFound" {
      ...
    }
    ...
}

Since Go does not support exceptions, the above is a code smell, relying on error string.

Option 3:

Separate to 2 different functions: one will check if the object exists, and the other will return it.

func FindUserByID(id int) User {
   ....
}

func IsExist(id int) bool {
   ...
}

The problem with it is:

  1. Checking if the object exists in many cases means also fetching it. So we pay penalty for doing the same operation twice (assume no caching available).
  2. The call to "IsExist" can return true, but "Find" can fail if the object was removed by the time it was called. In high concurrency applications it can happen very often. Which again forces checking nil value from "Find".

Option 4:

Change the name of "Find" to suggest it may return nil. This is common in .Net and the name can be "TryFindByID". But many people hate this pattern and I haven't seen it anywhere else. And anyhow it's still makes the nil value the magic "not exist" mark.

Option 5:

In some languages (java, c++) there's the "Optional" pattern. This makes a clear signature and helps the caller understand she needs to call "isEmpty()" first. Unfortunately this is not available in Go. There are some projects in github (like https://github.com/markphelps/optional) but since Go is limited and does not support returning generic types without casting, it means another compilation step is required to creat an Optional struct for out object, and use that in the function signature.

func FindUserByID(id int) OptionalUser {
   ....
}

func Foo() {
    optionalUser := FindUserByID(123)
    if optionalUser.IsEmpty() {
      ...
    }
    ...
}

But it depends on 3rd parties and adds compilation complexity. It doubles the amount of structs that follow this pattern.

Option 6:

Go support returning multiple values in a function. So the "Find" function can also return a bool value if the object exists.

func FindUserByID(id int) (User, bool) {
    ...
    if /*user not found*/ {
       return nil, false
    }
    ...
}

This seems to be a favorable approach in Go. For example, casting in Go also returns a bool value saying if the operation was successful.

I wonder what's the best approach and to get some feedback on the above options.

Syncing unsent messages from server to client with local db

In an instant messaging app, the users' mobile devices contain a db like SQLite for offline storage, and the server has Postgres for cold storage, and Redis for storing X recent messages.

When a user is offline, I want to be able to sync new messages to their SQLite using the push notification sent to them. And then once they go online, check with the server whether there are some messages that he didn't receive.

How can this be done efficiently?

Example + semi-solution :

When a user is offline, I send FCM pushes to the user with the new messages sent to them. That means, the app can update the local SQLite db with those new messages even if I'm not showing the notification itself (if a user has opted-out from receiving those).

Initially I thought about storing the last time the SQLite was updated and then upon connection establishment (websocket), check and retrieve all the messages (if there were) from that timestamp in server.

But push notifications are something rather unreliable, and FCM can skip messages or send those with a great delay.

For example, imagine we sent messages A, B, C through FCM push, and B is skipped by the FCM for some reason. That means that C's timestamp would be set, and then the server would think "alright, the user has all the messages up until C's timestamp, so no point in sending him anything before that". Thus, B will never get to the user.

I could solve that, by retrieving ALL the messages from the last time the user was online, and then check on their app locally against the SQLite whether I have all those messages stored there. But that seems rather inefficient.

How is this sort of syncing usually done in an efficient manner?

Javascript design patterns in context of SPAs

While there are tons of design patterns which can be used, I wanted to understand some of the important ones in the context of Single Page applications e.g. EmberJS, Angular

Just to give a simple example, Services are based on singleton pattern (both in Ember/Angular) So, I am looking at similar patterns for SPAs.

lundi 23 mars 2020

Sharing Open Source Projects for Leveling Up Programming Skills

I'd appreciate if you share any open source projects to contribute, That helps upgrading the contributor's skills in solid principals, design patterns, software design and architecture, software testing and overall helps leveling up skills and knowledge to become a better software engineer.

It would help better if these projects are based on PHP programming language.

How to setup Role-Based Access Control for web app with multiple resources/namespaces?

I work in NodeJS with ExpressJS and I'm rather new to the concept of RBAC and I'm trying to wrap my head around one specific scenario. I've been researching this for a while by reviewing online guides and been unable to figure one detail out.

Consider this scenario: There is a company that has a web app it sells as a service to clients. The web app serves BOTH clients and employees of the company. Clients can only view their account:

/app/clientAccounts/:id/dashboard/

whereas employees of the company can view multiple clients (but maybe not ALL clients):

/app/clientAccounts/1/dashboard/
/app/clientAccounts/2/dashboard/
etc..

Users can be either employees or clients, the only data the user object contains is email, password, and roles. The client account data is stored separately.

My understanding is the the ClientAccount ID route represents a 'resource' or 'namespace'. Is this correct?

My main question is: how does one address Employees viewing a subset of client accounts? I believe I understand how Roles and Permissions can be defined and stored in memory. However, this selective assignment of resource access seems like it requires a DB to be managed.

Finally, if my proposed scenario is illogical or a bad idea because of my lack of knowledge, please let me know.

Thanks!

How to have different request and response for classes of same interface in Java?

Seems like that it is the usecase of generics and interface. I am not so fluent with java.

class A {
  String field1;
  Int field2;
}

//Let ITransformer is an interface. Every class which is implementing Itransformer have different output. Suppose 1 class returns the output and we update field1=output and for other class we need to update field2=output. transformers is the list of these classes.

A a = new A();
for(ITransformer transformer : transformers) {
    Object t = transformer.transform(vendorAspectReviewTransformerRequest); //don't know how to make sure that transformer of type 1/ or returning string should update field1 and other transformer should update field2 
}

Better solution to avoid struggle with the property rename in a class

I created the following simple class

class Animal{
    constructor(feet) {
       this.feet = feet; //I mean paws.I think it should be in the prototype of subclass but here is an example
    }

  set feet(value){
    if(Number.isInteger(value) && value>0) {
       this._feet = value;
    }
    else {
      //Print a message report
      throw new Error('Invalid Initialization');
    }
  }

  get feet(){
    return this._feet;
  }

  static calcFeet(...animals)
  {
    return animals.reduce((prev,cur) => prev+cur.feet , 0);
  }

}

const an1 = new Animal(2);
const an2 = new Animal(4);

console.log(an1.feet); //2
console.log(an2.feet); //4
console.log(Animal.calcFeet(an1,an2)); //6

I have setter and getter to check integrity of the value for the property feet and an utility method on the constructor Animal. Everything nice but in this way if I would to change the name property feet in paws I should do it in several points of the code class definition. Thus I implemented an alternative version:

class Animal{
    constructor(paws) {
       this.setPaws(paws);
    }

    setPaws(paws){
      if(Number.isInteger(paws) && paws>0) {
        this.paws = paws;
      }
      else {
        //Print a message report
        throw new Error('Invalid Initialization');
      }
    }

  getPaws(){
    return this.paws;
  }

  static calcFeet(...animals)
  {
    return animals.reduce((prev,cur) => prev+cur.getPaws() , 0);
  }

}

const an1 = new Animal(2);
const an2 = new Animal(4);

console.log(an1.getPaws()); //2
console.log(an2.getPaws()); //4
console.log(Animal.calcFeet(an1,an2)); //6

I was wondering if the latest version is more correct than first both from software engineering point of view or from javascript style perspective. And if it isn't the case what could be a cleanest up implementation?

What is the clean way to integrate another service to django

I have a Django 3 application, using an LDAP service class, like this :

class LDAPService:
    def init(self, host: str, user: str, password: str, ssl: bool = True):
        ...
    def bind():  # The connection is done here, __init__ just sets values
        ....
    def create_ou(base: str, ou_name: str):
        ....

Where (or when) should I initialize the service to use it in views ? The bind step takes about 2 seconds to apply, I can not do it on every request. How can I keep an instance of this class shared, and not done every single time ? I may have a solution using singleton, and/or initializing it in like settings files, but i think there is a better way to do it.

I know in production, there may be multiple workers, so multiple instances, but i am ok with it.

Another question: How can everything above be done, with connections credentials from a database model (so not at django startup, but at anytime)

I am totally new to the django ecosystem, the things i have found about a service layer were all about django models. I want to do the same interface i would do for models in a regular service layer, but working on something else than django models.

I think the LDAP connection itself should not be there, only the CRUD methods, but i do not know where to place it, and how to make django interact with.

Thanks in advance for your suggestions :)

How can I make enum available to users of a class without additional dependencies?

I have a number of acceptable values as an input into a class method and I think a nice way to control this is by using an enum type. The catch is that I don't want to create an additional dependencies.

Is there a nice Pythonic way to do this?

As an example, the following will work, but it won't get me code completion.

import enum

class A(enum.Enum):
  one=1
  two=2
  three=3

class Myclass:

  def method(self, a: A):
    print('Inside method')
    print(a)

  # Two approaches I've looked at
  method.input = A  # Approach 1: Associates directly with the method
  method_input = A  # Approach 2: Provides access to enum through the class

m = Myclass()

# Approach 1: Doesn't give code completion. Associates with the method
m.method(m.method.input.one)

# Approach 2: Gives code completion. Depends on a naming convention
m.method(m.method_input.one)

I've also considered putting it in the parameters, but I don't think it's appropriate since I'm only interested in a single value - though it could be done. The more promising alternative is to use a dictionary map, but that won't give my users code completion.

DDD Aggregate Root for static tables

We are refactoring an existing application using Spring Data JPA. There are close to 250 static code database tables which can be referred by other aggregate roots. In order to attach a code table to an aggregate root, we need to access the particular code table record. Does that mean we should create 250 repositories? I mean a repo per static code table since it's an aggregate root itself?

I saw this question, which is kind of similar, but in my case I have a lot of static tables.