vendredi 31 juillet 2020

Best practice to generate string? [closed]

I have a system to generate messages string based on user action. I have more than 200 different messages,I need to know which is the best design pattern to handle the creation of strings

switch in factory class

I have a factory class that decides to which bank service should instantiated based on input so I created it with switch in factory class like this:

class BankFactory
{
    public static function build($iban)
    {
        switch ($iban){
            case "123":
                return new BankXService();
            case "456":
                return new BankYService();
        }
    }
}

But every time that I want to add a bank service switch case is longer and longer.

Is there any better design pattern for this task?

How to implement a middleware using object oriented design pattern in node.js?

I am new to an object-oriented design pattern. I just want to convert my middleware function and models to follow an object-oriented design pattern and use that throughout my code.

// sample middleware

const isActivated = async (req, res, next) => {
  const { email } = req.body
  try {
    const user = await User.findOne({ email: email })
    if (!user) {
      next(new Error('No such user is found!'))
    }
    if (user && !user.isActivated) {
      next(new Error('Please activate the account!'))
    }
  } catch (Error) {
    return res.status(HttpStatus.BAD_REQUEST).json({ Error })
  }
}

module.exports = isActivated

CSS : Is there a way to activate a hover element whitout activating the one below?

I know my question is hard to understand but I have made a gif to explain my problem. I would like the menu to go above the horizontal bar without activating it.
CSS of the vertical menu :

.dropbtn {
    color: white;
    padding: 5px 10px;
    border: none;
    cursor: pointer;
}

.dropbtn a {
    font-weight: bold;
    text-decoration: none;
    color: #ffffff;
}

.dropdown {
    position: relative;
    display: inline-block;
}

.dropdown-content {
    display: none;
    position: absolute;
    right: 0;
    text-align: left;
    background-color: #f9f9f9;
    min-width: 200px;
    z-index: 3;
    padding: 5px;
}

.dropdown-content a {
    color: black;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    z-index: 4;
}

.dropdown-content a:hover {
    background-color: #dddddd;
}

.dropdown:hover .dropdown-content {
    display: block;
    box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}

.dropdown:hover .dropbtn {
    background-color: #ffffff;
    box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
}

.dropdown:hover .dropbtn a {
    color: #333333;
}

CSS of the horizontal bar :

nav {
    margin: 27px auto 0;

    position: relative;
    width: 800px;
    height: 50px;
    background-color: #34495e;
    border-radius: 8px;
    font-size: 0;
}

nav a {
    line-height: 50px;
    height: 100%;
    font-size: 15px;
    display: inline-block;
    position: relative;
    z-index: 1;
    text-decoration: none;
    text-transform: uppercase;
    text-align: center;
    color: white;
    cursor: pointer;
}

nav .animation {
    position: absolute;
    height: 100%;
    top: 0;
    z-index: 0;
    transition: all .5s ease 0s;
    border-radius: 8px;
}

a:nth-child(1) {
    width: 400px;
    z-index: 2;
}

a:nth-child(2) {
    width: 400px;
    z-index: 2;
}

nav .start-home,
a:nth-child(1):hover~.animation {
    width: 400px;
    left: 0;
    background-color: #39aeb4;
}

nav .start-likes,
a:nth-child(2):hover~.animation {
    width: 400px;
    left: 400px;
    background-color: #39aeb4;
}

As you can see, I tried to add some Z-Index properties to the menu but that didn't change anything.

Thanks for your help !

How handle transaction in Chain Of Responsibility pattern?

I have a transaction issue on COR pattern:

       AbstractChainHandler
      |                   |
      |                   |
   FirstChainHandler     SecondChainHandler
    -create A               -create B
    -delete A               -delete B

FirstChainHandler and SecondChainHandler both extend AbstractChainHandler and they do some persistence tasks. Is it possible to handle transaction so if SecondChainHandler fails to save A on db also FirstChainHandler does the rollback of B persistence?

I am trying with spring @Transactional but it is not working and I am not sure if COR pattern matches my goal. I tryied to change propagation and isolation configurations but I didn't work.

Python: Referring to different dictionary items in a dictionary item

I have a dictionary:

region = {
"DACH": ["Germany", "Switzerland", "Austria"],
"BLX":["Netherlands", "Belgium", "Luxembourg"]
}

I would like to add an item like this:

region = {
"DACH": ["Germany", "Switzerland", "Austria"],
"BLX": ["Netherlands", "Belgium", "Luxembourg"],
"EUROPE": region["DACH"] + region["BLX"]
}

Python - rightfully so - complains about Unresolved reference: region.

I can solve this by using a lambda expression, like this:

region = {
"DACH": ["Germany", "Switzerland", "Austria"],
"BLX": ["Netherlands", "Belgium", "Luxembourg"],
"EUROPE": lambda: region["DACH"] + region["BLX"]
}

Are there more elegant ways to do this in Python? It doesn't feel pythonic to me, but rather glued together.

Boolean expressions, visitor pattern and.. stack overflow

Boolean expressions, visitor pattern and.. stack overflow

I have some kind of expression library than defines boolean expressions (something that can evaluate to true or false). The code looks like this:

class ExpressionVisitor;

class Expression
{
public:
    virtual ~Expression() {}    
    virtual void Accept(ExpressionVisitor &visitor) = 0;
    //.. other methods
    
}

class ConstantExpression : public Expression
{
public:
    ConstantExpression(bool val) : m_val(val){}
    void Accept(ExpressionVisitor &visitor) override { visitor.VisitConstantExpression(this); }
    bool GetValue() const { return m_val; }
private:
    bool m_val;
}

class NotExpression : public Expression
{
public:
    NotExpression(Expression *pInnerExpression) : m_pInnerExpression(pInnerExpression) {}
    void Accept(ExpressionVisitor &visitor) override { visitor.VisitNotExpression(this); }
    Expression* GetInnerExpression() const { return m_pInnerExpression; }    
private:
    Expression *m_pInnerExpression;
}

class BinaryExpression : public Expression
{
public:
    AndExpression(Expression *pLeftExpression, Expression *pRightExpression) : m_pLeftExpression(pLeftExpression), m_pRightExpression(pRightExpression) {}
    Expression* GetLeftExpression() const { return m_pLeftExpression; }
    Expression* GetRightExpression() const { return m_pRightExpression; }
private:
    Expression m_pLeftExpression, m_pRightExpression;
}

class AndExpression : public BinaryExpression
{
public:
    AndExpression(Expression *pLeftExpression, Expression *pRightExpression) : BinaryExpression(pLeftExpression, pRightExpression) {}
    void Accept(ExpressionVisitor &visitor) override { visitor.VisitAndExpression(this); }
}

class OrExpression : public BinaryExpression
{
public:
    OrExpression(Expression *pLeftExpression, Expression *pRightExpression) : BinaryExpression(pLeftExpression, pRightExpression) {}
    void Accept(ExpressionVisitor &visitor) override { visitor.VisitOrExpression(this); }
}

class ExpressionVisitor
{
public:
    virtual ~ExpressionVisitor() {}
    void VisitConstantExpression(ConstantExpression*);
    void VisitNotExpression(NotExpression*);
    void VisitAndExpression(AndExpression*);
    void VisitOrExpression(OrExpression*);
}

Now to evalate an expression I have a concrete visitor:

class EvaluatorVisitor : public ExpressionVisitor
{
public:
    EvaluatorVisitor() : m_result(false){}
    
    bool GetResult() const { return m_result; }

    void VisitConstantExpression(ConstantExpression* pExpr)
    {
        m_result = pExpr->GetValue();
    }
    void VisitNotExpression(NotExpression* pExpr)
    {
        pExpr->GetInnerExpression()->Accept(this);
        auto innerResult = m_result;
        m_result = !innerResult;
    }
    void VisitAndExpression(AndExpression* pExpr)
    {
        pExpr->GetLeftExpression()->Accept(this);
        auto leftResult = m_result;
        pExpr->GetRightExpression()->Accept(this);
        auto rightResult = m_result;
        m_result = leftResult && rightResult;
    }
    void VisitOrExpression(OrExpression* pExpr)
    {
        pExpr->GetLeftExpression()->Accept(this);
        auto leftResult = m_result;
        pExpr->GetRightExpression()->Accept(this);
        auto rightResult = m_result;
        m_result = leftResult || rightResult;
    }
    
private:
    bool m_result;
}

And I use it like this:

EvaluatorVisitor evaluator;
Expression *pExpr = ...;
pExpr->Accept(&evaluator);
bool result = evaluator.GetResult();

Now for really large (deep) expressions that contains a lot of binary expressions, I get a stack overflow because the EvaluatorVisitor is inherently recursive (because of the Accept() call). How do I solve this (besides the obvious 'increase the stack size')?

jeudi 30 juillet 2020

What way would be best to adhere to both DRY and limit unintended functionality given this kind of design in C# or Java?

Please excuse my limited paint skills, but how would I best create objects that would function in the way depicted in this diagram?, given the single-class inheritance nature of the languages? The Moon, Rocky Planet, and Asteroid classes should implement IColonizable, but the issue is that they would implement it in the exact same way, say, with a simple getter. In this case, I would assume it would be better to put the functionality into the parent class Body. However, I would then be giving the GasGiant class the ability to getOwner() when I do not want this functionality to exist.

The best solution I can come up with is implementing getOwner in the Body class, but only inheriting the IColonizable interface in the desired classes, then maybe when getOwner() is called in GasGiant, I could override with an exception. Any thoughts?

Handling errors creting an Entity. Factoy and Result

I write some code to control the way mi entites are created by and static method putting the constructor private. ¿Factory?

I am not returning the instance, but a Resonse With a value Entity if it is isSuccess. The idea is to handle errors whitout thorw and error, just returning an extended response whit that information. [Example all together at the end]

My problem is:

class Customer<CustomerProps> extends Entity<CustomerProps>{
    private constructor(props: CustomerProps){
       
    }

    public static create(props: CustomerProps): Result<Customer>{
        ....
        if(someError) return Result.fail('String error');

        return Result.ok<Customer>(new Entity(props));
    }
}

And the result class

class Result<T>{
  
  private constructor(isSuccess: boolean, error: string, value?: T) {
  ...
  this.isSuccess = isSuccess;
  this.error = error;
  this._value = value;
  }
 
  public getValue(): T{
    if (!this._value) {
        throw new Error("Can't get the value of an error result. Use 'errorValue' instead.")
    }
    return this._value;
  }

  public static ok<U>(value: U): Result<U> {
    return new Result<U>(true, '', value);
  }

  public static fail<U>(error: string): Result<U> {
    return new Result<U>(false, error);
  }

I can now ask if the response was successful and get the value.

The problem is: in Result class I have getValue() and it is asking if there is _value and throwing an error if not. Because in the case of Result.fail() there is no value. Throw Error is the issue... i am doing it again because not always there is _value.

Does this represent a problem for you? Should I just throw an error and Catch that exception?

Automatically login to Wordpress from another web application

I have a site A which deploys and configures Wordpress instance for user Y (users are managed by site A). Together with the installation, it creates a Wordpress user X.

User Y (logged in) can click on a link on site A which opens the Wordpress instance in a new window. I do not want the user to login to the Wordpress instance separately, but rather somehow automatically log him in as user X (so it would be "hidden" for the user). Hence, the user opens Wordpress from site A and is automatically logged in.

I have access to both applications (site A and Wordpress instance) and can deploy any code to each.

How would you solve this? Which pattern would you go with?

How can we implement a stateful visitor pattern?

I have a class similar to Node (There are multiple derivatives of Node). The RecursiveFunction processes the sourceNode referenced by the current node which internally processes its sourceNode. The structure of the graph formed can either be a tree or a DAG. In order to avoid re-processing the same node and reuse the result of the previous processing I need to maintain a map of processed entries and remember a node had already been visited. Adding iteration into node class is not right. One consideration was to use visitor pattern. But then the visitor instance should internal keep a map of previously visited nodes. Essentially introducing state into the visitor. The problem with that is, we cannot enforce that the client should always pass a new visitor instance when RecursiveFunction is called

Class Node {
    public Node SourceNode;

    public Node RecursiveFunction1() {
        //Some logic
        this.SourceNode.RecursiveFunction();
        // Some logic
        return transformedNode;
    }

    public Node RecursiveFunction2(someInput..) {
        //Some logic
        this.SourceNode.RecursiveFunction2(someInput..);
        // Some logic
        return transformedNode;
    }
}

With visitor pattern:

Class Node {
    public Node SourceNode;

    public Node RecursiveFunction(IVisitor1 visitor) {
        return visitor.RecursiveFunction(this);
    }

    public Node RecursiveFunction2(IVisitor2 visitor, SomeInputs..) {
        return visitor.RecursiveFunction2(this, SomeInputs..);
    }
}

class Visitor1 : IVisitor1 {
    private Dictionary<Node,Node> map;

    public Node RecursiveFunction(DerivedNode1 x) {
        if(!this.map.Contains(x)) {
            // Some logic
            x.SourceNode.RecursiveFunction(this);
           // Some logic

            map[x] = result;
        }

        return map[x];
     }

    public Node RecursiveFunction(DerivedNode2 x) {
        if(!this.map.Contains(x)) {
            // Some logic
            x.SourceNode.RecursiveFunction(this);
           // Some logic

            map[x] = result;
        }

        return map[x];
     }
    
}


P.S: The psudo code was just a high level thought to articulate my thought process better. Have not coded it. Could be utterly wrong. Any alternate designs are well appreciated. Goal is to keep iteration away from Node. And in the visitor pattern approach I'm also having to check/populate the map for every function in every visitor. This is a lot of duplication. If the suggestion is to use iterator pattern please provide psudo code as I could not quite grasp how to get that working for this model.

Delegate complicated exception handling to separate class?

I've been trying to follow the default rule of using composition over inheritance to share functionality between classes, but have run into a situation where an existing base class' method's very complicated exception handling now needs to be specialized for certain sub-classes (multiple).

So the exception handling in the base class is something like:

try {
    doSomething()
} catch (HttpClientErrorException ex) {
    // complicated logic
} catch (HttpServerErrorException ex) {
    // complicated logic
} catch (RestClientException ex) {
    // complicated logic
} catch (Exception ex) {
    throw ex;
}

But now for certain extensions of this base class, we want to first check for a certain type of HttpClientErrorException and do special logic instead. Instead of parenting the classes that need this special logic to a new base class that extends the original base class, should we consider creating a separate exception handler interface and injecting it into the base class?

An implementation of the interface would implement handleException which might look something like:

public void handleException(Exception ex) {
    if (ex instanceof HttpClientErrorException ) {
        // complicated logic
    }
    ..etc..
}

Is this considered bad practice? Are there drawbacks I'm not seeing? If so, what is the preferred way to deal with this situation?

Xml options pattern

I'm trying to get the options pattern working with Xml. Here is what I've done so far :

public IndexModel(ILogger<IndexModel> logger, IConfiguration configuration)
{
    _logger = logger;
    Configuration = configuration;


    var mySettings = new MySettings();
    Configuration.GetSection(nameof(MySettings)).Bind(_mySettings);

    var xmlSettings = new XmlSettings.ConfigurationOptions.configuration();
    Configuration.GetSection(nameof(MySettings)).Bind(xmlSettings);

    var xmlSettings2 = new XmlSettings.ConfigurationOptions.configuration();
    Configuration.GetSection("configuration").Bind(xmlSettings);

}

In my program.cs :

config.AddXmlFile(@"C:\temp\web.config", optional: true, reloadOnChange: true);
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();

My appsettings.json:

{
    "Logging": {
    "LogLevel": {
        "Default": "Information",
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
    }
},
"AllowedHosts": "*",
"MySettings": {
  "MyJsonSetting": "myJsonValue1234"
}

}

My web.config :

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <MySettings>
    <basicSetting>SometBasicSetting</basicSetting>
  </MySettings>
</configuration>

My JSON POCO:

public class MySettings
{
    public string MyJsonSetting { get; set; }
}

And then finally my Xml class :

// NOTE: Generated code may require at least .NET Framework 4.5 or .NET Core/Standard 2.0.
/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class configuration
{

    private configurationMySettings mySettingsField;

    /// <remarks/>
    public configurationMySettings MySettings
    {
        get
        {
            return this.mySettingsField;
        }
        set
        {
            this.mySettingsField = value;
        }
    }
}

/// <remarks/>
[System.SerializableAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public partial class configurationMySettings
{

    private string basicSettingField;

    /// <remarks/>
    public string basicSetting
    {
        get
        {
            return this.basicSettingField;
        }
        set
        {
            this.basicSettingField = value;
        }
    }
}

When runing this, I get the JSON settings object populated, as expected, but not the Xml. I have a feeling that the structure of my Xml class isn't correct.

Is what I want to do possible at all, and if so, what am I doing wrong?

mercredi 29 juillet 2020

Can we set values to interface methods from class A and get values from class B in java

I have a Events interface contains two methods

Interface Events{
      public Event save(Event event);
      public search(int a, int b);
}
class A implements Events(){
      implementing methos and set values;
}
class B implements Events{
Getting values from already set through class A to ClassB
}

Is it possible, if it is please show me one simple example.

Thanks in advance

ansible how do i search for a directory/subdirectory like 'home/ansible'

In Ansible v2.8.2, how do I search for a subset of a directory tree, like 'home/ansible'?

I have attempted using the find module:

    - name: Find ansible directory
      become: true
      find:
          paths: /
          recurse: yes
          file_type: directory
          use_regex: yes
          patterns: 'home/ansible'
      register: ansible_dirs

    - name: post ansible dirs
      debug:
          msg:
              - ""

I get the error: /proc/20828/task/20828/fd/6 was skipped as it does not seem to be a valid file or it cannot be accessed

If I change patterns to 'home' or 'ansible' it works, but gives me more results then I need.

I suppose I could take this larger result set and whittle it down to what I need, but I was hoping there was an out-of-the-box method to use.

Any help is greatly appreciated, thanks!

Abstract builder

So I have an abstract Transaction class, which has multiple implementations (Payment, File).

I would like to have a builder for the Transaction (abstract) + the implementor.

I did this:

public abstract class TransactionBuilder
{
    protected final Transaction transaction;
    
    public TransactionBuilder(Transaction transaction)
    {
        this.transaction = transaction;
    }
    
    public TransactionBuilder setSignature(byte[] signature)
    {
        this.transaction.setSignature(signature);
        return this;
    }
    
    public TransactionBuilder setPreviousHash(String previousHash)
    {
        this.transaction.setPreviousHash(previousHash);
        return this;
    }
    
    public abstract Transaction build();
}

Example for the PaymentBuilder class:

public class PaymentBuilder extends TransactionBuilder
{
    public PaymentBuilder(String from, String to, double amount)
    {
        super(new Payment(from, to, amount));
    }
    
    public PaymentBuilder addAmount(double amount)
    {
        ((Payment) this.transaction).amount += amount;
    }
    
    @Override
    public Payment build()
    {
        return (Payment) this.transaction;
    }
}

Every field has a getter/setter, Transaction:

public abstract class Transaction
{
    //Used for serialization
    private String type;
    
    private String previousTransactionHash;
    private String hash;
    private String signature;
    
    private String fromAddress;
    private String toAddress;
    
    private Instant timeStamp;
    
    public Transaction(String type, String from, String to)
    {
        this.type = type;
        this.fromAddress = from;
        this.toAddress = to;
        this.timeStamp = Instant.now();

        setHash();
    }

How I use:

Payment payment = new PaymentBuilder(from, to, amount)
                .setPreviousHash(previousHash)
                .build();

But when I call setSignature() I get "Type mismatch: cannot convert from Transaction to Payment" so I need to cast it to a Payment, how can I avoid that? Can I?

Declaration not compatible with interface (PHP)

Let's say I have one parent class with two child classes like this

abstract class Vehicle {
    public function setManufacturer(string $manufacturer) { ... }
}

class Bicycle extends Vehicle {
    public function addSaddle() { ... }
}

class Car extends Vehicle {
    public function setSpeedLimit(float $limit) { ... }
}

Now I want to use these objects with an interface like this

interface VehicleInterface {
    public function create(Vehicle $vehicle);
}

class BicycleService implements VehicleInterface {
    public function create(Bicycle $bicycle) {
        $bicycle->setManufacturer('Some company'); // Common for all Vehicle objects
        $bicycle->addSaddle(); // Common only for Bicycle objects
    }
}

It seems that this is not possible since BicycleService create(...) is not compatible with the interface. Is there any way around this other than removing type hints?

This is a question where I'm supposed to get a door mat design as shown in the body. I'm not able to get "-" for every line

So I'm actually supposed to get a design as following:

------------.|.------------
---------.|..|..|.---------
------.|..|..|..|..|.------
---.|..|..|..|..|..|..|.---
----------WELCOME----------
---.|..|..|..|..|..|..|.---
------.|..|..|..|..|.------
---------.|..|..|.---------
------------.|.------------

which it's an N*M mat size. where N is an odd number and M is 3*N. for which I wrote this:

N,M=map(int,input().split())
for i in range(1,N,2):
     pattern=".|."*i
     var=pattern.center((m-len(pattern))/2,"-")
     print(var)

and when I execute this I don't get "-" for every line. I want to know where did I go wrong. I know that there's much more to do apart from this but can anyone please help me with this.

Printing a butterfly pattern including numbers [closed]

How to print this pattern??

5       9
2 5   9 4
4 5 5 6 8
6 9   5 12
9       5

I have made a program but I think it’s more specific and long please help

React.js and DevExtreme library - singleton pattern problem/solution


At the beginning I want to point out that this question is specific and maybe dumb - and I know it but I really need to know every positive (if exists) and negative aspect of that solution.

To the point: I am developing huge React.js appliaction on top of DevExtreme library. There are tons of limitations due to this library. One of the biggest: editing forms cannot be controlled - setState/dispatch/selector causes multi-rerender etc - it's just impossible and official reply from support also says that with this component it is just impossible.

So if saving to any kind of React state is impossible I've came up with an idea of "singleton-like" solution that looks like this:

class Singleton {
  constructor() {
    this.data = []
  }

  setData(data) {
    this.data = data; 
  }

  getData() {
    return this.data; 
  }
}

const singletonDataInstance = new Singleton(); 
export default singletonDataInstance;

React doesn't recognize that this is some global state (I have access to those methods and fields anywhere where I import its instance) and thanks to this React doesn't re-render my Form DevExtreme component (i need this data only to send some info to backend).

BUT I feel like this is massive anti-pattern in React so if someone can explain why this is such a bad practice (or not) I would be greatfull.

Thanks!

How to append to a decorator in Python

How do I extend an existing decorator of a third party library without changing the third-party source?

Suppose I have a decorator that follows this pattern:

@xy.dummy("ab")
def hello():
    print("hello")

Now I want to extend the decorator from @xy.dummy("ab") to @xy.dummy("ab", "cd") without modifying the third party source?

How to avoid DTO Models replication Pattern?

C# SOLUTION-1

  • Project-1: CodeFirstEntityFramework (Models are defined within this)
  • Project-2: WebAPIs referenced the CodeFirstEntityFramework Models are available
  • Project-3: Web Application Core Referenced the CodeFirstEntityFramework Model Definitions are available and used Web APIs with Authentication

Is this a good Pattern? OR C# SOLUTION-2

  • Project-1: Class Library ModelsClassLib Define Models Only
  • Project-2: CodeFirstEntityFramework refrence ModelsClassLib
  • Project-3: WebAPIs referenced the CodeFirstEntityFramework
  • Project-4: Web Application Core UI uses the WebAPIs

Wherever Models are needed I will reference ModelsClassLib instead of replicating the Models in place of DTOModel Objects. Question: Is this recommended? Is this a Good Practice?

mardi 28 juillet 2020

What will be the best approach to read environment variables and JSON requests, responses

I have environment variables that need to be used in anywhere of the code. (And I can store theses environment variables in JSON format-if needed). Also, I have JSON requests and responses in separate JSON files which we used to validate in REST requests in my program. What will be the best approach to read config data and Use? Language: Java. Can Read conf data using Jackson or basic file reader...

i need xml design guideline

required design its a scrollable screen with 3 to 4 almost similar blocks

this is what i been trying

<?xml version="1.0" encoding="utf-8"?>
<androidx.core.widget.NestedScrollView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    xmlns:custom="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    android:background="@color/colorWhite"
    tools:context=".MainActivity">
       <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.santalu.diagonalimageview.DiagonalImageView
            android:id="@+id/image"
            android:layout_width="match_parent"
            android:layout_height="350dp"
            android:scaleType="centerCrop"
            android:src="@drawable/demo"
            app:di_borderColor="#FF5722"
            app:di_borderEnabled="false"
            app:di_direction="left"
            app:di_overlap="60dp"
            app:di_position="bottom" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_margin="16dp"
            android:text="Maternity care plan"
            android:textColor="#040303"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/tv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="240dp"
            android:text="Maternity care plan"
            android:textColor="#050505"
            android:textSize="20sp" />

        <com.example.diagnalimageview.DividerView
            android:id="@+id/line1"
            android:layout_width="4dp"
            android:layout_height="150dp"
            android:layout_below="@+id/tv2"
            android:layout_centerHorizontal="true"
            android:layerType="software"
            custom:color="#050505"
            custom:dashGap="2dp"
            custom:dashLength="5dp"
            custom:dashThickness="1dp"
            custom:orientation="vertical" />

       
        <!-- A CardView that contains a TextView -->


        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/pregnancy_plane_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/line1"
            android:layout_centerHorizontal="true"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp">
            <RelativeLayout
                android:id="@+id/circle_progress_container"
                android:layout_width="75dp"
                android:layout_height="75dp"
                android:translationZ="90dp"

                custom:layout_constraintEnd_toEndOf="parent"
                custom:layout_constraintStart_toStartOf="parent"
                custom:layout_constraintTop_toTopOf="parent">
                <com.timqi.sectorprogressview.ColorfulRingProgressView
                    android:id="@+id/circle_progress"
                    android:layout_width="75dp"
                    android:layout_height="75dp"
                    app:bgColor="#e1e1e1"
                    app:fgColorEnd="#5900FF"
                    app:fgColorStart="#5900FF"
                    app:percent="0"
                    app:startAngle="0"
                    app:strokeWidth="8dp"
                    android:background="@color/colorWhite"/>
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="0%"
                    android:layout_centerInParent="true"/>

            </RelativeLayout>
            <!--determine center to circular shape-->
            <Button
                android:id="@+id/dummy_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Dummy view"
                android:visibility="gone"
                app:layout_constraintBottom_toBottomOf="@id/circle_progress_container"
                app:layout_constraintEnd_toEndOf="@id/circle_progress_container"
                app:layout_constraintStart_toStartOf="@+id/circle_progress_container"
                app:layout_constraintTop_toTopOf="@id/circle_progress_container"
                tools:ignore="HardcodedText" />



            <androidx.cardview.widget.CardView
                android:id="@+id/pregnancy_plane"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                app:cardElevation="12dp"
                app:cardUseCompatPadding="true"
                android:translationY="-20dp"
                app:layout_constraintTop_toBottomOf="@+id/dummy_view"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                card_view:cardBackgroundColor="@color/colorPrimary"
                card_view:contentPadding="1dp">


    
                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        android:background="@color/colorWhite">

                        <TextView
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:layout_marginTop="48dp"
                            android:gravity="center"
                            android:text="PLAN YOUT PREGNANCY\nTHE WAY YOU WANT"
                            android:textSize="20sp" />

                        <ImageView
                            android:layout_width="100dp"
                            android:layout_height="100dp"
                            android:layout_gravity="center"
                            android:layout_margin="32dp"
                            android:src="@mipmap/ic_launcher" />

                        <Button
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:background="@color/colorPrimary"
                            android:text="PLANNING MY PREGNANCY"
                            android:textSize="20sp" />

                    </LinearLayout>
              
            </androidx.cardview.widget.CardView>





        </androidx.constraintlayout.widget.ConstraintLayout>

        <com.example.diagnalimageview.DividerView
            android:id="@+id/line2"
            android:layout_width="4dp"
            android:layout_height="150dp"
            android:layout_below="@+id/pregnancy_plane_container"
            android:layout_centerHorizontal="true"
            android:translationY="-36dp"
            android:layerType="software"
            custom:color="#050505"
            custom:dashGap="2dp"
            custom:dashLength="5dp"
            custom:dashThickness="1dp"
            custom:orientation="vertical" />

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/line2"
            android:layout_centerHorizontal="true"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp">

            <RelativeLayout
                android:id="@+id/circle_progress_container2"
                android:layout_width="75dp"
                android:layout_height="75dp"
                android:translationZ="90dp"

                custom:layout_constraintEnd_toEndOf="parent"
                custom:layout_constraintStart_toStartOf="parent"
                custom:layout_constraintTop_toTopOf="parent">

                <com.timqi.sectorprogressview.ColorfulRingProgressView
                    android:id="@+id/pregnancy_choices_progress"
                    android:layout_width="75dp"
                    android:layout_height="75dp"
                    android:background="@color/colorWhite"
                    app:bgColor="#e1e1e1"
                    app:fgColorEnd="#5900FF"
                    app:fgColorStart="#5900FF"
                    app:percent="0"
                    app:startAngle="0"
                    app:strokeWidth="8dp" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true"
                    android:text="0%" />

            </RelativeLayout>
            <!--determine center to circular shape-->
            <Button
                android:id="@+id/dummy_view2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Dummy view"
                android:visibility="gone"
                app:layout_constraintBottom_toBottomOf="@id/circle_progress_container2"
                app:layout_constraintEnd_toEndOf="@id/circle_progress_container2"
                app:layout_constraintStart_toStartOf="@+id/circle_progress_container2"
                app:layout_constraintTop_toTopOf="@id/circle_progress_container2"
                tools:ignore="HardcodedText" />


            <androidx.cardview.widget.CardView
                android:id="@+id/pregnancy_choices"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:translationY="-20dp"
                app:cardElevation="12dp"
                app:cardUseCompatPadding="true"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/dummy_view2"
                card_view:cardBackgroundColor="@color/colorPrimary"
                card_view:contentPadding="1dp">


                <!--<androidx.cardview.widget.CardView

                    android:id="@+id/card_view"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    app:layout_constraintTop_toBottomOf="@+id/dummy_view">-->

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@color/colorWhite"
                    android:orientation="vertical">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="48dp"
                        android:gravity="center"
                        android:text="PLAN YOUT PREGNANCY\nTHE WAY YOU WANT"
                        android:textSize="20sp" />

                    <ImageView
                        android:layout_width="100dp"
                        android:layout_height="100dp"
                        android:layout_gravity="center"
                        android:layout_margin="32dp"
                        android:src="@mipmap/ic_launcher" />

                    <Button
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:background="@color/colorPrimary"
                        android:text="PLANNING MY PREGNANCY"
                        android:textSize="20sp" />

                </LinearLayout>
                <!-- </androidx.cardview.widget.CardView>-->
            </androidx.cardview.widget.CardView>


        </androidx.constraintlayout.widget.ConstraintLayout>


    </RelativeLayout>

</androidx.core.widget.NestedScrollView>

now the problems is for blocks view hierarchy is ConstraintLayout RelativeLayout. -for progress chart Button(dummyview) -to determine center of progress chart cardview -to give elevated look i used compact padding 12dp that padding make bottom space between constraint layout and cardview. so when i tried to draw vertical line between first block and second block. line top was 12dp down from the block than i used translationY= -12dp to fix it but now vertical line is touching second block. my output myoutput

How to build a java object from multiple data sources when data is not available in all sources during the creation time?

I've this design question that I'm trying to solve, and I hope to hear back from you, if you have any suggestions.

Let's say that we have a queue that you are listening to, the queue receives a message, the listener in your application grabs it, and builds an object, and pushes it to the cache, the object information at this moment has the data that it has received from the queue only, but it's still waiting on other data that's not available in other data sources (assume it's a DB) yet, what's the best approach to update the object when data becomes available in other data sources?

  • Should I've a thread running in the background to fetch data periodically?
  • I'm thinking of using decorator design pattern to build the object, Is that a good approach?
  • Any suggestions are welcome.

Flutter: Do I have to create a bloc for each part on my app? What it the best practices?

I'm developing an E-commerce Mobile app, using flutter with Bloc as a Design pattern and flutter_bloc package for simplifying things.

My question is: do I have to create a bloc of each part of my app? is this the best practice for using the BLOC as a design pattern?

For example, at my App on the Home Screen there are some sections like best sellers and offers ...etc, do I have to create a separate bloc for each section? as I guess that way will be there a lot of repeated code as well a lot of files and still can't do it all at once using the same bloc logically.

Does this XSD follow the Venetian Blind design pattern?

I'm just wondering if this XSD follows Venetian Blind so that all complex and simple types are global? From my understanding, in order to follow Venetian Blind design pattern, elements must be declared separately and then built together using 'types'. But since I have so many nested types in this doc, I'm not sure how to figure out if it follows VB. How do I determine if all the types are global and if they are not, what would be the best way to convert it?

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema" xmlns:presentations="http://www.example.com/presentations" xmlns:topics="http://www.example.com/topics" targetNamespace="http://www.example.com/presentations" elementFormDefault="qualified">
  <import namespace="http://www.example.com/topics" schemaLocation="topics.xsd"/>
  <attributeGroup name="PresentationAttributes">
    <attribute name="date" type="date" use="required"/>
    <attribute name="length" type="duration" use="required"/>
  </attributeGroup>
  <element name="presentations">
    <complexType>
      <sequence>
        <element name="presentation" minOccurs="0" maxOccurs="unbounded">
          <complexType>
            <sequence>
              <element name="topic" type="topics:TopicsType"/>
              <element name="presenters" type="presentations:PresentersType"/>
            </sequence>
            <attributeGroup ref="presentations:PresentationAttributes"/>
          </complexType>
        </element>
      </sequence>
    </complexType>
  </element>
  <complexType name="PresentersType">
    <sequence>
      <element name="name" minOccurs="1" maxOccurs="unbounded">
        <complexType>
          <group ref="presentations:NameGroup"/>
          <attribute name="id">
            <simpleType>
              <restriction base="ID">
                <pattern value="[XY][0-9][0-9][0-9]"/>
              </restriction>
            </simpleType>
          </attribute>
          <attribute name="title">
            <simpleType>
              <restriction base="string">
                <enumeration value="Mr."/>
                <enumeration value="Mrs."/>
                <enumeration value="Ms."/>
                <enumeration value="Miss"/>
              </restriction>
            </simpleType>
          </attribute>
        </complexType>
      </element>
    </sequence>
  </complexType>
  <group name="NameGroup">
    <sequence>
      <element name="first" type="string" minOccurs="1" maxOccurs="unbounded"/>
      <element name="middle" type="string" minOccurs="0" maxOccurs="1"/>
      <element name="last" type="string"/>
    </sequence>
  </group>
</schema>

How to store one from among three forms or formsets in Django?

enter image description here It will remain the owner of the copyright application, the owner may again be private or joint or institutional. How can this problem be solved once? #Thanks

django

enter image description here

how to avoid creating the duplicate microservice when there is an need of same functionality in layer A/ layer B

i have single microservice , which is deployed in layer A , we copied the code and deployed it in Layer B to utilize the same, how i can achieve this with single microservice without duplicating, what type of pattern i have to use?

How to handling error in decorate function?

I'm trying to decorate my function that has an error handling like this.

// Target function 

async function update(){
  try{
   await someAsyncFunction()
  }
  catch(err){
   return Promise.reject(err)
  }
}

// Decorate function 

async function notify(fn){
 try{
  await fn()
  await publish()
 }
 catch(err){
  return err
 }

So, we can call the function like this

notify(update)

But the problem comes when the publish method throwing an error, it should break the function of notifying. The goal of this method the notify should be logging error only and if the update method throwing an error, it should fail to publish.

Thank you.

lundi 27 juillet 2020

Object calisthenics. Limiting of instance variables

I was wondering why instance variables should be limited to two in object callisthenics? Why not three, or four? I understand it is to lower coupling, I was just wondering if there is rationale behind the number two?

Properly use adapter pattern in Spring Boot

I am trying to implement an adapter to connect with multiple vendors. The issue is the spring dependencies are becoming unwieldy. I find myself having to edit the adapter class, each adapter sub class, and each controller class that uses the adapter methods. This is how I am using the adapter:

public interface IAdapterBuilder {
  public IAdapterBuilder withMyString(String myString);
  public IAdapter build();
}
public abstract class BaseAdapter {

  final String myString;

 public static IAdapterBuilder getBuilder(){
    return SubAdapter.getBuilder();
}

void myAdapterMethod(){
System.out.println("baseAdapter running myAdapterMethod")
}

void setMyString(String myString) {
    this.myString = myString;
  }
}

public class SubAdapter extends BaseAdapter implements IAdapter {

protected SubAdapter(UUID SubAdapterId) {
    super(SubAdapterId);
  }

public static Builder builder() {
    return new Builder();
  }

public static final class Builder implements IAdapterBuilder {

String myString = null;

    @Override
    public IAdapterBuilder withMyString(String myString) {
      this.myString = myString;
      return this;
    }

public SubAdapter build() {
      if (SubAdapterObject == null) {
        throw new IllegalStateException(
            "Unable to create an adapter without a Synchronization record.");
      }


      SubAdapter adapter = new SubAdapter(SubAdapterObject.getId());
      if (myString != null) {
        adapter.setMyString(myString);
      }
   }
}

@RestController
public class MyController {

private final myString;

@Autowired
  public MyController(@Value("${io.org.service.myString}") String myString){
    this.myString = myString;
}

@GetMapping
public void test(){
IAdapterBuilder adapterBuilder =
        BaseAdapter.getBuilder(provider).withMyString(myString);
    }
}

Basically anytime I want to add a dependency to the SubAdapter I need to modify all of these files. There has to be a better way to do this. I would appreciate any help.

Is it right to use extend and implement in the same class

interface A {void someMethod();}

class B implements A {
 void someMethod(){
  //do something
 }
}

class C extends B implements A {
 void someMethod() {
  super.someMethod();
  //do something
 }
}

I'm using the above design in one of my codes. It is working fine. My whole purpose here is to use the default implementation of class B and do something extra in class C. Is this the correct way to use the implementation? Is there any better design patter to be looked at?

Because If I define my class C as below, still everything works fine. But this neglects the whole purpose of using implementation (to force class C to implement methods of interface A).

class C extends B implements A {}

Which design pattern is suitable for this case

I'm writing Java code and here is the code:

public static void main(String[] args) {
    String type = args[0];
    if (type.equals("TYPE1")) {
        // do something
    } else if (type.equals("TYPE2")) {
        // do something
    }
    ...
    func1(type);
    func2(type);
    func3(type);
}

public static void func1(String type) {
    if (type.equals("TYPE1")) {
        // do something
    } else if (type.equals("TYPE2")) {
        // do something
    }
    ...
}

public static void func2(String type) {
    if (type.equals("TYPE1")) {
        // do something
    } else if (type.equals("TYPE2")) {
        // do something
    }
    ...
}

public static void func3(String type) {
    if (type.equals("TYPE1")) {
        // do something
    } else if (type.equals("TYPE2")) {
        // do something
    }
    ...
}

As you see, I have to do if...else... in each function, I believe I can use some design pattern but I don't know which design pattern is the best for this case.

Dealing with many parameters/class attributes in Python

I'm creating a Python class that will use its parameters to define two other classes within this class. For example, ClassA contains ClassB and ClassC. Because of this, ClassA has a lot of parameters.

I'm currently solving this using **kwargs for classB and classC arguments, and saving only the input parameters for classA parameters. For example:

class A:
    def __init__(self, a1, a2, a3, **kwargs):
        self.a1 = a1
        self.a2 = a2
        self.a3 = a3

        # Get B and C kwargs
        default_params = {
            'b1': kwargs.get('b1', 1),
            'b2': kwargs.get('b1', 2),
            'c1': kwargs.get('c1', 1),
            'c2': kwargs.get('c1', 2),          
        }
        for param in default_params:
            self.__dict__[param] = default_params[param]

        B = classB(a1=self.a1, b1=self.b1, b2=self.b2)
        C = classC(a2=self.a2, c1=self.c1, c2=self.c2)

Is this a worse solution compared to the below?

class A:
    def __init__(
        self,
        a1, a2, a3,
        b1, b2, c1, c2):
        self.a1 = a1
        self.a2 = a2
        self.a3 = a3
        self.b1 = b1
        self.b2 = b2
        self.c1 = c1
        self.c2 = c2

My concern is if arguments for class B and C are super numerous, then class A's attributes seems too many. On the other hand, the first approach seems to take up more lines anyway.

Another way is if I pass only kwargs to classB and classC, but this will have an error when there are some parameters not present in one of the classes.

Is there a pythonic way I'm failing to see here for classes with many attributes and utilising this kind of design pattern?

dimanche 26 juillet 2020

How to identify patterns in a column in R and give an identity to said patterns

I have a dataset of dives (captured by time-depth recorder attached to a diving bird), which consists of among many other variables, dive depths, dive duration, and post dive duration (time spent resting before starting another dive). What I have been trying to do (unsuccessfully) is identify dive bouts, which are multiple dives that occur within a set period of time, with a certain amount of time between. As an example, 5 sequential dives would be considered a diving bout if the first 4 have a post dive duration of <300s, and the 5th has one greater than >300s. The 6th dive would be considered the start of a new bout, and the end would be the next dive that has a post dive duration >300s. I'm sure there is a simple solution to identify patterns like this, but I don't really know how to approach this in R. I would also like to have each bout numbered and placed in a new column labeled "BoutID" if possible. Can anyone make any suggestions? See example of what the output I am looking for.

Thanks!

divedepth <- c(10, 11, 13, 12, 15, 25, 30, 5, 7, 3, 10)
divetime <- c(60, 50, 45, 45, 30, 50, 25, 10, 50, 30, 33)
postdivetime <- c(5, 10, 3, 5, 301, 1, 4, 7, 305, 10, 301)
boutID <- c(1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3)
dives <- data.frame(divedepth, divetime, postdivetime, boutID)

dives
   divedepth divetime postdivetime boutID
1         10       60            5      1
2         11       50           10      1
3         13       45            3      1
4         12       45            5      1
5         15       30          301      1
6         25       50            1      2
7         30       25            4      2
8          5       10            7      2
9          7       50          305      2
10         3       30           10      3
11        10       33          301      3

One view across multiple view controllers

Not sure how to go about adding a UIView that is permanent across multiple view controllers. I have a music app that has a UITabBarController and currently, each view controller uses their own UIView instance "audioPlayer with options" to play music. I've been asked to make this view static across each VC. Similar to Spotify. Have no code to share as I need to know my options and where to start. I'm not using storyboards.

Thanks

Java built-in Observable push notifications

I am trying to understand how to implement push vs pull notifications using Java built-in Observer.

the Observable class has 2 methods notifyObservers() and notifyObservers(Object arg) I want to understand the differnce between them.

so I tried this

@Override
    public void update(Observable o, Object arg) {
        /*
        if (o instanceof WeatherData) {
            WeatherData weatherData = (WeatherData) o;
            this.temperature = weatherData.getTemperature();
            this.humidity = weatherData.getHumidity();
        }*/

        if (arg instanceof WeatherData) {
        WeatherData weatherData = (WeatherData) arg;
        this.temperature = weatherData.getTemperature();
        this.humidity = weatherData.getHumidity();
        }

        display();
    }

and in my observable class

setChanged();
        //notifyObservers();
        notifyObservers(this);

both objects can be cast down to WeatherData(the Observer) and then get the data from them.

using both methods seem like push notification-type for me, so what is the difference? and how can I implement pull notification-type using it?

Best design for a messaging app with sqlite (sqlCipher)

I am working on a messaging app and was wondering if anyone could suggest the best design to use with SQL cipher. Currently, I open and close the database on each update (messages sent and received). I have had a couple of crashes that I cannot reproduce at all times and I am thinking it's because of access to the database from multiple files, not to mention I am using background queues whenever accessing the database.

Just to give you an idea why I am using SQL cipher - I need to store all messages on the device as server will hold no data and I need to back up all messages to iCloud periodically. Thus I thought using SQL cipher could provide secure storage.

I would like to know whether it's better to carry on this way or I should keep a local copy and only update the database before the app changes state.

Any suggestion is very much appreciated. Also I am on the path of learning so please don't vote down and let me edit my question if it doesn't sound clear enough. Thank you so much.

How should I transfer object with sesitive data from view to Hibernate ORM?

To create new account user must to complete the form with some more or less sensitive data like e-mail, password, username, PGP public key. Data is validate and if everything is correct on their basis app creates entities with: user acc data, his public key and verification token which be send to him by email as part of the account confirmation.

  1. How should I transfer user informations from view to Hibernate ORM? Is DTO object a good solution? Can password be transfer in plain text?
  2. What design patterns should I use to create all of there objects based on DTO?

Is there another way than using patterns to manage state ? (Flutter)

I have been developping a small "days left before an event" Flutter app for myself.

The main page consists of a list of "Events" widgets and infos about them. Main page

On the right side of any "Event" there is a bin icon that simply sends an SQL query to delete the event from the DB on tap.

Unfortunately I have been encountering troubles refreshing the main page after the tap on the bin icon because I have no reference of the state of the main page in the "Event" widget.

I have resolved the problem by creating a refresh function in my main page state :

void refresh() {
  setState(() {});
}

and sending a reference --> "var hp" of the state of my main page to the "Event" widget:

class Event extends StatefulWidget {
  String title;
  DateTime date;
  int id;
  String daysLeft;
  Color daysColor;
  var hp;

Event(this.hp, this.title, this.date, this.daysLeft, this.daysColor,
      [this.id]) {
    if (this.title == null) {
      this.title = "No title";
    }
  }
...

thus, I can refresh my main page when tapping on the bin icon :

GestureDetector(
                onTap: () {
                  db.deleteEvent(widget.id);
                  log("refreshing page inc...");
                  widget.hp.refresh();
                  log("refreshed");
                },
                child: Container(
                    margin: EdgeInsets.only(right: 15),
                    child: Icon(
                      Icons.delete,
                      size: 30,
                    )))

I am aware that this looks super ugly. Moreover, the state of the main page being a private class, I had to store it in a "var" which I do not like.

Is there any other way to do that kind of things ? This all looks super complicated and not really smooth to implement.

I have done some researches and it seems there are a few state management patterns (https://flutter.dev/docs/development/data-and-backend/state-mgmt/options?fbclid=IwAR2yiPjh_jPQKb9s3-2nBYRQwbQmhyv_6tjnZTqbpRbdJOZJdyDFy9HZ07E)

But is there no other way than implementing pattern to do this ?

Thanks :)

std::vector with type known at runtime

I am writing a small C++ library to process audio files. The file header tells me the number of bits per sample (8 bits, 16 bits, etc.). Ideally, I'd like to store that in a std::vector<T>, where T=std::uint8_t for 8 bits, std::uint16_t for 16 bits, etc.

  1. One approach would be to just store everything as a bunch of bytes and use type punning all over the place. I am not a huge fan of this method. I'd rather do it once when reading the data and then proceed with a nicely typed vector.

  2. I could also use the largest possible type and call it a day, but this seems rather wasteful and performance would likely take a hit.

  3. Else, I could template my entire codebase on the bits per sample type, explicitly instantiate all the valid widths and have some factory function pick the appropriate implementation. Is that a reasonable thing to do in audio engineering?

BigQuery: split string with repetitive pattern to separate rows

I have a string with repetitive pattern like: timestampField: <SOME_INT_VALUE> url: <SOME_STRING_VALUE>. As you can see in the example, this pattern returns multiple (4 in this example) times.

SELECT my_string
FROM (SELECT 'timestampField: 1595351350 url: domainZ/aaaabbbbccccdddd timestampField: 1595351355 url: domainZ/eeeeffffgggghhhh timestampField: 1595351355 url: domainZ/iiiijjjjkkkkllll timestampField: 1595351356 url: domainZ/mmmmnnnnppppoooo' as my_string)

I want to break this big string into 4 (in this example) different rows, each row will have a string value

  1. timestampField: 1595351350 url: domainZ/aaaabbbbccccdddd
  2. timestampField: 1595351355 url: domainZ/eeeeffffgggghhhh
  3. timestampField: 1595351355 url: domainZ/iiiijjjjkkkkllll
  4. timestampField: 1595351356 url: domainZ/mmmmnnnnppppoooo

samedi 25 juillet 2020

Do we count depending interfaces while calculating Effernet Coupling value for a package

I don't know if we count interfaces while counting Effernet coupling value for a package?

Is it possible to use socket.io server in a scalable way, in terms of software design?

the context:

I am currently working on a web application, which needs a lot of interactions through real-time data, when on my server made in nodejs, I try to maintain an mvc architecture, I realize that I cannot use socket out of 1 single file, because whenever I call it somewhere else it is not possible to obtain the connection object, to be used within my models.

it is normal to see a socket.io server with this structure (using nodejs):

io.on('connection', function(socket) {
  console.log('Alguien se ha conectado con Sockets');
  socket.emit('messages', messages);

  socket.on('new-message', function(data) {
    messages.push(data);

    io.sockets.emit('messages', messages);
  });
});

the object variable socket that comes within the connection channel is the one that serves socket clients, but outside of that connection I cannot serve it, I have tried that I assign that variable in a sychronic way outside that callback and it is not possible for me, it always arrives null, nor can I use it outside other model files.

Question: Is there a way to be able to make a kind of a singlenton pattern to be able to use this socket object in multiple files?

catching and re throwing same custom exception

I have a Spring JobRunner Component that has a run() method which throws my custom exception:

public Response run(final Request request, final String id) {
    try {
        execution = jobLauncher.run(job, parameters);
    } catch (JobExecutionAlreadyRunningException e) {
        throw new MyCustomException("already running ", e);
    } catch (JobRestartException e) {         
        throw new MyCustomException("Restart Exception", e);
    } 
    return generateResponse(request, id, execution);
}

In my service class, I call this run() method inside process()

  protected Response process(final Request request, final String id) {
      //get entity
      //save
      //bla bla
    Response response;
    try {
        response = jobRunner.run(request, id);
        updateStatus(entity, response.getStatus(), "");
    } catch (MyCustomException ex) {
        updateStatus(entity, FAILED);
        throw new MyCustomException(ex.getMessage(), ex);
    }
}

You will notice I am catching MyCustomException and rethrowing again. I have to catch because I need to update the status accordingly here in the service class as it has a repository dependency to update status in db for tracking purpose.

I am also rethrowing because attached to this custom exception is a ControllerAdvice for api requests so it responds accordingly.

What I would like to know, is this a good design or a bad practice ? What could I change if anything ?

Architecture Patterns for User-Specific Login Content

Been watching a lot of system design videos and a concept isn't clicking.

Consider a system like Twitter in which a User's feed displays 20 recent tweets from their friends. These tweets are actually pre-computed and ready when the user comes online, thus the feed page loads quickly.

My question: how can each of twitter's 330 million users have a personalized queue ready? At first, I thought maybe like a literal amazon SQS existed for every twitter user, but seems that this many SQS queues is not feasible/possible (although maybe through virtual queues...?}). Then I figured, well maybe page is actuallying reading from some optimized DB... unlikely.

So what are some patterns to queueing user-specific messages in a distributed system? The same applies for example to Gmail, What's App, Facebook feed etc... anything that, when user logs in, they have predetermiend content waiting. Where specifically do these messages live? Are they in a KV store for example? Are they in a literal queue somewhere?

I do understand this is part of the fanout pattern, but am more so interested on where the content lives after it's been fanned out.

Here's a really great tutorial on Twitter Architecture where KV store is used, and wondering if this is industry-standard? If not, what else?

removing duplicate code shared between sync and async implementations

Given that I have an Processor interface:

public interface Processor {
    PBResponse process(PBEntity pbEntity);
}

And I have two implementation in my framework project, one synchronous:

@Service("Synchronous")
public class SyncProcessor implements Processor {

    private final PBRepository pbRepository;
    private final JobRunner jobRunner;

    public SyncProcessor(PBRepository pbRepository, JobRunner jobRunner) {
        this.pbRepository = pbRepository;
        this.jobRunner = jobRunner;
    }

    @Override
    public PBResponse process(PBEntity pbEntity) {
       pbRepository.save(pbEntity);
       //other business logic and run job
        jobRunner.runJob(pbEntity);
    }
}

The Other Async:

public class AsyncProcessor implements Processor {

    private final PBRepository pbRepository;
    private final JobRunner jobRunner;

    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    public SyncProcessor(PBRepository pbRepository, JobRunner jobRunner) {
        this.pbRepository = pbRepository;
        this.jobRunner = jobRunner;
    }

    @Override
    public PBResponse process(PBEntity pbEntity) {
        pbRepository.save(pbEntity);
        executorService.execute(new PBJobRunTask(pbRepository, jobRunner, pbEntity));
        return new PBResponse(...) //initial incomplete Response
    }

    private class PBJobRunTask implements Runnable {
        private final PBSFeedRepository pbsFeedRepository;
        private final JobRunner jobRunner;
        private final PBEntity pbEntity;

        public PBJobRunTask(PBRepository pbRepository, JobRunner jobRunner, PBEntity pbEntity) {
            //initialise
        }

        @Override
        public void run() {
            //other business logic and run job
            jobRunner.runJob(pbEntity);
        }
    }
}

Processing of a request is identical between both sync and async implementations. The only difference is the logic is executed with an ExecutorService with async implementation.

The processing logic is repeated in both Synchronous and Asynchronous implementations within the Runnable run() method:

   //duplicated
   pbRepository.save(pbEntity);
        //other business logic and run job
        jobRunner.runJob(pbEntity);

I need some help remove this duplicated where both these implementation can share. I am not sure whether inject Synchronous class into Async in a good practice as they are both implementations of Processor.

What would be ideal and a good pattern to share the business logic between two classes. We have the repository and JobRunner which also sits in both implementations and perhaps they can move also?

Thanks in advance

Which design-patterns is Koa framework built upon?

I was reading Addy Osmani's book Learning Javascript Design Patterns, which I think is a great book on design patterns. When I came upon the Flyweight design pattern, I found it pretty familiar. It seemed like I've seen this pattern getting used in any project.

The project I was thinking about was node-oidc provider, an oidc-provider package written in node.js using Koa framework.

In the package, an instance constant is created which embodies properties and methods to it and is shared all across the application. The instance is created using WeakMap collection in file weak_cache.js and is first imported into the file provider.js.

Now, why I think this is very much similar to flyweight design pattern is because of the statements in the pattern's description.

It aims to minimize the use of memory in an application by sharing as much data as possible with related objects (e.g application configuration, state and so on).

In practice, Flyweight data sharing can involve taking several similar objects or data constructs used by a number of objects and placing this data into a single external object.

Albeit, I understand it isn't exactly flyweight pattern(and I might be wrong on this), but the instance constant pretty much resembles the external object in the above statements.

Upon further speculations, I started to think about what other patterns are involved in a simple Koa application. Though the application built on top of Koa will use its own design patterns, but for simplicity & brevity let's consider a simple Koa application as our model for this question.

The key statements in Koa documentation which I think may help us in understanding the design patterns employed are:

A Koa application is an object containing an array of middleware functions which are composed and executed in a stack-like manner upon request.

const http = require('http');
const https = require('https');
const Koa = require('koa');
const app = new Koa();
http.createServer(app.callback()).listen(3000);
https.createServer(app.callback()).listen(3001);

From the use of new operator, one can think of Constructor pattern. All the imported packages tell us the usage of the Module pattern.

I know the question is too broad and might be subjective in nature, but I'm trying to see the practical use-cases/scenarios of the patterns I studied in the book.

vendredi 24 juillet 2020

Best endpoint design approach [closed]

I'm trying to optimize a call that is taking ~6 seconds to load a page. It's set up like this: frontend -> backend service -> further backend services -> database.

The gist of the call is to return 3 counts, a user count, a team count, and a roles count. To the DB, teams and roles are considered the same, the only difference is the value in a column (TEAM, ROLE).

The problem lies somewhere in the backend service, because it has to make 2 other calls where one gets filtered once (i.e. linear iteration) and the other response gets filtered twice.

This is kind of how it goes:

  • The frontend calls one endpoint: /getCounts.
  • The backend has to make 2 calls to other backend services.
    • one to a user service to get the user list.
      • user list is then filtered to remove a subset of the users and we get the resulting subset count.
    • one request to the roles service that gets the list of teams and roles (combined).
      • The roles call response is filtered twice, once to filter out the teams (and get subset count) and once to filter out roles (and get subset count). O(2n).

My initial thought is to separate the team and roles call into two requests to the role service and let the database do the filtering. In theory, the DB should be able to filter faster than iterating the list through code.

The thought that followed was having an algorithm that separates the teams and roles in a single iteration of that list. O(n).

Another thing that I considered was to have 3 separate endpoints in the backend service, one for each count. And to help with render times, have the frontend do those calls asynchronously so the rest of the page can load without having to wait for the values. But this raises the question of:

Don't we want to have endpoints return resources instead of hyper-specific values?

Which of these would be the better approach:

  1. Make three calls from the backend endpoint and let the DB do the filtering.
  2. Make two calls and filter once.
  3. Have 3 separate endpoints.
  4. Something else.

Object oriented Design: Scalable and maintainable car store system

I had an interview yesterday and had asked an OOD question:

Race-Car Store System:

The system stores information about cars available for players.

  • Two types of gear changing strategies: manual/automatic.
  • Two types of fuel: gasoline/diesel.

Design a system that can produce cars requested by players (If the player wants a car with manual gear changing and burn diesel, your system should provide one instance of the car meets the requirements). The system should have good scalability and maintainability.

My thoughts and solution:

My thought is the requirement contains two attributes: gear and fuel. I plan to make an abstract class contains the attributes and corresponding behaviors. Considering scalability would have an interface Movable which contains behaviors what a car can do.

If any new attribute is added in the future, either create a new abstract class contains the new attribute or add the attribute into the existing abstract class, if there's new behaviors are required, I would either create new interface or add the behavior into existing interface.

Here's what I have done: An interface contains general behaviors, currently has showSpecs() only.

public interface Movable {
    public String showSpecs();
}

An abstract class contains attributes fuel and gear

public abstract class Car implements Movable {
    String gear;
    String fuel;

    abstract void setFuel(String fuel);

    abstract String getFuel();

    abstract void setGear(String gear);

    abstract String getGear();
}

Now the race car class implementaion:

public class RaceCar extends Car {
    public RaceCar(String fuel, String gear) {
        this.fuel = fuel;
        this.gear = gear;
    }

    public void setFuel(String fuel) {
        this.fuel = fuel;
    }

    public String getFuel() {
        return this.fuel;
    }

    public void setGear(String gear) {
        this.gear = gear;
    }

    public String getGear() {
        return this.gear;
    }

    public String showSpecs() {
        StringBuilder sb = new StringBuilder();
        sb.append("Gear:").append(this.gear);
        sb.append("Fuel:").append(this.fuel);
        return sb.toString();
    }
}

Below is the main class I have:

public class Main {
    public static void main(String[] args) {
        System.out.println("get started...");
        Car car = new RaceCar("diseal", "automatic");
        System.out.println(car.showSpecs());
    }
}

The interviewer replied that the solution I provided is not scalable and hard to maintain but didn't provide details so I am still confused about what mistakes I made and how to improve it.

Can anyone help share your thoughts and point out what am I supposed to improve?

Thanks!

dynamically alter function args within class method

I am looking for some kind of design pattern, pattern in general, or preferably a pythonic way to handle the following issue. Suppose we have a SuperCalculator class that performs some very complex calculations and then validates it with some metrics that defaultvalidator handles by default.

class SuperCalculator:

    validator = defaultvalidator

    def do_complex_calculation(self):
        # here we do some static but complex calculations

        # arg1 and arg2 are baked into `do_complex_calculation`'s
        # call of `self.validator`
        if self.validator(arg1, arg2):
            return calculation 
        else:
            raise SuperCalculatorExc()

Now assume the client wants to dynamically change the validator to use completely different metrics, including different args passed into the validation process. Or even if the client wanted to extend SuperCalculator, how can they make similar changes without making them override do_complex_calculations?

sc = SuperCalculator()
sc.validator = customvalidator
sc.do_complex_calculation()

The issue here is that do_complex_calculation has arg1, arg2 baked into its call of self.validator. Is there a design pattern that will help solve this issue? I've had trouble researching this and would appreciate any feedback. Thank you.

Best practices in structuring Node.js & Socket.io app?

Currently I'm developing a node server which uses websockets for communication. I'm used to applying MVC (or MC) pattern in my apps. I'd like to structure my socket.io in similiar way and my question is how to do this in the best way?

For now I have something like this:

utils/socket.ts:

type IO = null | SocketIO.Server;
let io: IO;

export function init(ioServer: IO) {
  io = ioServer;
}

export function getIO(): IO {
  return io;
}

app.ts:

import express from 'express';
...

import { init } from './utils/socket';
import startSockets from './controllers';

const app = express();


...

const server = app.listen(process.env.PORT || 5000);

const io = socketio.listen(server);

if (io) {
  init(io);
  io.on('connect', startSockets);
}

controllers/index.ts:

import { onConnect } from './connect';
import { getIO } from '../utils/socket';

export default function (socket: SocketIO.Socket) {
  const io = getIO();
  socket.on('connect-player', onConnect);
}

controllers/connect.ts:

 import Player from '../models/Player';

  export const onConnect = async function (this: SocketIO.Socket, name: string) {
  const player = await Player.create({ name });

  this.broadcast.emit('player-connected', `Player ${name} joined the game!`);
  this.emit(
    'player-connected',
    `Congratulations ${name}, you successfully joined our game!`,
    player,
  );

  this.on('disconnect', onDisconnect.bind(this, player.id));
};

const onDisconnect = async function (this: SocketIO.Socket, playerId: string) {
  const player = await Player.findById(playerId);
  await player?.remove();
  this.broadcast.emit(
    'player-connected',
    `Player ${player?.name} left our game!`,
  );
};

I'm not sure about using 'this' in my controller and about that singleton pattern in utils/socket.ts. Is that proper? The most important for me is to keep the app clear and extensible.

I'm using express and typescript. Player.ts is my moongoose schema of player.

How do I instantiate a child class in a default method of an immutable abstract base class?

How do I instantiate a child class in a default method of an immutable abstract base class e.g. return a new instance with modified properties?

I have an abstract document class with a few properties which is immutable. When calling the createDocument or updateDocument methods, a new instance should be returned with the fields set to the new values. I don't want to override the methods in each child class since the logic will remain the same => duplicate code. Is there a way / pattern to get around this problem or am i simply missing something here?

abstract class Document extends Model {
    final Version version;
    final Id id;
    final DateTime createdAt;
    final DateTime modifiedAt;

    Document(this.version, {this.id, this.createdAt, this.modifiedAt})

    Document createDocument(Id id, DateTime timestamp) {
        // some validation logic here
        // TODO 
        // Instantiate a new document and set the id, createdAt fields 
    }

    Document updateDocument(DateTime timestamp) {
        // some validation logic here
        // TODO 
        // Instantiate a new document and set modified at field
    }
}

class User extends Document {
    static const Version VERSION = Version(1,0,0);
    final int someProperty;
    User(this.someProperty) : super(VERSION)

}

One idea of mine was to implement an abstract copyWith method

  Document copyWith({Id id, DateTime modifiedAt, DateTime createdAt});

but that would mean that other classes can access the copy method and set arbitrary values which would defeat the whole purpose of the validation logic in the methods and it would inflate the code. Furthermore since I'm using Dart I can not really use protected methods.

Any help would be highly appreciated!

Is there a name for this type of object pool?

I've recently implemented the same data structure for the 2nd time in 3 years, in two unrelated projects.

I feel it may be a common pattern?

Pattern description:

I have a central object pool, and many downstream object pools.

The downstream object pools acquire from the central object pool.

The central object pool can issue the same resource to different downstream object pools, but never the same resource twice to the same pool.

The central pool is therefore the universal set of resources in the downstream resource pools.

enter image description here

Is this strategy pattern

To move from one http client to another (same concept can be applied to log libs, db's) I implemented this solution but I am not sure if it's a pattern in OOP world. After looking at some it kinda looks like strategy pattern or repository pattern. But what I understood from repository pattern it is only restricted to data access functionality. However same concept can be applied logging libs, http clients or email client etc.

Here is my implementation of something that I don't know the name: ( =D )

const fetch = require('node-fetch');
const axios = require('axios');
class MyHttpAxios {
  constructor(axios) {
    this.axios = axios;
  }

  async get(url) {
    const response = await this.axios.get(url);
    return response.data;
  }
}

class MyHttpFetch {
  constructor(fetch) {
    this.fetch = fetch;
  }
  async get(url) {
    const response = await this.fetch(url);
    return response.json();
  }
}

const httpClients = {
  axios: new MyHttpAxios(axios),
  fetch: new MyHttpFetch(fetch),
};

const client = httpClients['axios'];
client
  .get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response)
  .then(json => console.log(json));

jeudi 23 juillet 2020

Java swing re-using listeners

I've noticed that I'm making a new listener for every component in my app. Is this good design or would it be better to reuse my listeners? If I reuse my listeners what's a good pattern I should use to check which component is calling the event without having to check it with a ton of if statements

Dynamic binding for two arguments

This question concerns design patterns, and in particular dynamic binding, in statically typed languages (I use Kotlin here, but it could also be C++ or Java). The problem is as follows: I have an interface Node (representing nodes in an Ast) and concatenation of multiple elements (there are multiple such classes).

interface Node {
    fun concat(next: Node): Node {
        return Concat(listOf(this, next))
    }
}

class Concat(val nodes: List<Node>): Node {
}

I now want to make sure, that Concat is always flattened, ie, none of the nodes is a concatenation. This would be easy with some if(next is Concat) type check, but I would like to use dynamic binding and avoid such type checks. My first failing solution attempt would be the following:

interface Node {
    fun concat(next: Node): Node {
        return next.reverseConcat(this)
    }

    fun reverseConcat(prev: Node): Node {
        return Concat(prev, this)
    }
}

class Concat(val nodes: List<Node>): Node {
    override fun concat(next: Node): Node {
        // TODO what if next is a Concat?
        return Concat(nodes + next)
    }

    override fun reverseConcat(prev: Node): Node {
        // TODO what if prev is a Concat?
        return Concat(listOf(prev) + nodes) 
    }
}

but this fails if both nodes are instances of Concat. Another solution attempt would be to add reverseConcat-methods with Concat as parameters.

interface Node {
    // ...
    fun reverseConcatWithConcat(nextNodes: List<Node>): Node {
        return Concat(listOf(this) + nextNodes)
    }
}

class Concat(val nodes: List<Node>): Node {
    override fun concat(next: Node): Node {
        return next.reverseConcatWithConcat(nodes)
    }

    override fun reverseConcat(prev: Node): Node {
        // TODO what if prev is a Concat?
        return Concat(listOf(prev) + nodes) 
    }

    fun reverseConcatWithConcat(nextNodes: List<Node>): Node {
        return Concat(nodes + nextNodes)
    }
}

This would work but it clutters the interface (consider that there are other nodes, similar to Concat) and it also leaves the problem that there are no protected methods in interfaces so that reverseConcat is still dangerous.

Is there a more satisfying approach using dynamic binding that does not clutter the code unnecessarily?

Why can't we achieve deep cloning through getters in java why we need prototype design pattern with Cloneable interface?

I need to know in a case of we need to clone an instance deeply why can't we achieve that using the getter method of our original object why we need any specific design pattern or interface like Cloneable ?

Is an abstract class without any implementation and variables effectively interface?

I'm reviewing the concepts of OOP, reading .

Here the book defines interface as

The set of all signatures defined by an object’s operations is called the interface to the object. (p.39)

And the abstract class as

An abstract class is one whose main purpose is to define a common interface for its subclasses. An abstract class will defer some or all of its implementation to operations defined in subclasses; hence an abstract class cannot be instantiated. The operations that an abstract class declares but doesn’t implement are called abstract operations. Classes that aren’t abstract are called concrete classes. (p.43)

And I wonder, if I define an abstract class without any internal data (variables) and concrete operations, just some abstract operations, isn't it effectively just a set of signatures? Isn't it then just an interface?

So this is my first question:

  1. Can I say an abstract class with only abstract functions is "effectively (or theoretically)" an interface?

Then I thought, the book also says something about types and classes.

An object’s class defines how the object is implemented. The class defines the object’s internal state and the implementation of its operations. In contrast, an object’s type only refers to its interface—the set of requests to which it can respond. An object can have many types, and objects of different classes can have the same type. (p.44)

Then I remembered that some languages, like Java, does not allow multiple inheritance while it allows multiple implementation. So I guess for some languages (like Java), abstract class with only abstract operations != interfaces.

So this is my second question:

  1. Can I say an abstract class with only abstract functions is "generally equivalent to" an interface in languages that support multiple inheritance?

My first question was like checking definitions, and the second one is about how other languages work. I mainly use Java and Kotlin so I'm not so sure about other languages that support multiple inheritance. I do not expect a general, comprehensive review on current OOP languages, but just a little hint on single language (maybe python?) will be very helpful.

Thank you for spending your time on reading this question! Have a great, safe day.

Repository pattern: how do I accurate the signature (return type) of a function?

I'm using the repository pattern to fetch my data from the database.

Here is my base class:

class BaseRepository implements EloquentRepositoryInterface
{
 
  protected $model;

  public function __construct(Model $model)
  {
    $this->model = $model;
  }

  
  public function findOrFail($id): Model
  {
    try {
      return $this->model->findOrFail($id);
    } catch (\Exception $e) {
      throw new \Exception($e);
    }
  }

}

which implements this interface:

interface EloquentRepositoryInterface
{
  public function findOrFail($id): Model;
}

Then I have one entity called Item, which extends Model:

class Item extends Model
{
  // ... 
}

And what I want to do is create an ItemRepositoryInterface:

interface ItemRepositoryInterface extends EloquentRepositoryInterface
{
  public function findOrFail($id): Item;
}

But I can't change the interface signature... PhpStorm is telling me that is incompatible so I had to remove the public function findOrFail($id): Item from the interface. So that my $itemRepository->findOrFail() respects the signature of EloquentRepositoryInterface.

Here my ItemRepository :

class ItemRepository extends BaseRepository implements ItemRepositoryInterface
{
   // ...
}

The problem

is that when I use $itemRepository->findOrFail() the specs tells me it's returning a Model

What I want

is that when I call $itemRepository->findOrFail() the specs should tell me that it's returning an Item

Is there a way to have this behaviour ? Like keeping the signature of findOrFail() inside EloquentRepositoryInterface and 'overwrite' the return type of it, without having to rewrite the whole function ?

mercredi 22 juillet 2020

Designing data source agnostic models

I'm working on a full stack Typescript app, and am trying to

  1. Keep all of the models and services logic separated from any backing data source
  2. Keep data and behavior separated (i.e. method-less models)

But I'm having a hard time figuring out how to design these models when it comes to relationships.

Right now I have a core package, that exports some interfaces

interface Item {
  id: string;
  text: string;
  idProject: string;
}

interface Project {
  id: string;
  name: string;
  idSource: string;
}

interface Source {
  type: 'rss' | 'api';
  name: string;
}

interface ItemService {
  get(id: string): Promise<Item>
}

interface ProjectService {
  get(id: string): Promise<Project>
}

interface SourceService {
  get(id: string): Promise<Source>
}

interface ProjectItemLoaderService {
  constructor();
  loadItems(project: Project, source: Source): Promise<Item[]>;
}

and then in my server package, I use them like this

get('/project/:idProject/items', ({ idProject }) => {
  const project = projectService.get(idProject);
  const source = sourceService.get(project.idSource);
  const items = projectItemLoaderService.loadItems(project, source);
  ...
})

But from what I've been reading on this topic of well-abstracted models (DDD, hexagonal architecture), my models shouldn't be referring to relationships via ID, but should include the actual model, since things like ID are a storage-concept, and not a domain concept.

interface Item {
  id: string;
  text: string;
  project: Project
}

interface Project {
  id: string;
  name: string;
  source: Source
}

interface Source {
  type: 'rss' | 'api';
  name: string;
}

...

interface ProjectItemLoaderService {
  constructor();
  loadItems(project: Project): Promise<Item[]>;
}

...

get('/project/:idProject/items', ({ idProject }) => {
  const project = projectService.get(idProject);
  // Project already includes the Source model, not need to load it
  const items = projectItemLoaderService.loadItems(project);
  ...
})

This is more convenient to not have to constantly be loading nested models, but seems like it could get out of handle easily as the nesting gets deeper and deeper. The Project model should actually have a items: Item[] property, which could take a quite a long time to populate based on the backing storage. And it would then be cyclical, which is a whole other issue.

I'm basically looking for any advice on making data-agnostic models, and how services that handle those models should be given access its relationships. Maybe doing this sort of thing without going full DDD (use cases, commands, all that) is just not very feasible, and I should just be using source-couple ORM objects, but I really do like the idea of having the business logic layer being decoupled from the underlying data source.

Java DAO Pattern - Separate Database Communication Responsibility Without Using Multiple Classes

Hoping to leverage the knowledge of the community to help me answer a question on the DAO pattern in Java Programming.

Searching google for examples of implementing the DAO pattern give results like this:Example DAO Pattern

  public class DaoPatternDemo {
   public static void main(String[] args) {
      StudentDao studentDao = new StudentDaoImpl();

      //print all students
      for (Student student : studentDao.getAllStudents()) {
         System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");
      }


      //update student
      Student student =studentDao.getAllStudents().get(0);
      student.setName("Michael");
      studentDao.updateStudent(student);

      //get the student
      studentDao.getStudent(0);
      System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " + student.getName() + " ]");     
   }
}

My question is this: Is there a clean way to utilize just the Student model/class to communicate with the database on behalf of students rather than implement a "StudentDao" class as well? I would much rather do something like this:

student.setName("Michael");

and have the Student class handle all the database communication to set the name of the student upon calling the setName() method rather than have to do this:

student.setName("Michael");
studentDao.updateStudent(student);

It seems like if you follow the DAO pattern you have to do everything twice: Update the Student Object and the Student Table in the Database. Wouldn't it be easier to just have the methods in the Student Class take care of updating the database as well? What would be the drawbacks of a design like that?

(Example code and image taken from: https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm)