samedi 4 mai 2019

multiple data storage (database and json) for the same model, how to do it?

Ok, so am having multiple data storage for some models in my project, database storage which ganna save the user data, and a json storage which has a fixed data to compare with the user data.

so, am currently saving the json data in a property in the model after converting it to array, but it is so ANNOYING cause every model now is having a about 500 - 1000 line !

Am wondering, is there a design pattern or something like this which make it easier to relate these data to a model from another file ?

like having model which goal is to fetch the data from the database, and having entity which is related to this model and have this fixed json data on it.

BTW, am using Laravel framework, and my models are Eloquent ORM.

Example:

  class Building {
  protected $table = "buildings";

  //this data is so huge, but i need it to be related to this model so that i can access it from here.
  static $buildings = [
      'Castle' =>
            [
                'name' => 'Castle',
                'objectPath' => '/storage/3D/Land/models/Castle/CastleLevel1.fbx',
                'renderPath' => '/storage/3D/Land/models/Castle/Castle.png',
                'price' => 1000,
                'type' => 'castle',
                'levels' =>[
                    [
                        'upgradeTime' => 100,
                        'upgradeCost' => 100,
                        'requirements' => null
                    ],
                    [
                        'upgradeTime' => 100,
                        'upgradeCost' => 100,
                        'requirements' => null
                    ],
                ]
            ],
      // and so on ..
      ]

    function coordinates()
    {
        return $this->morphOne(Coordinates::class, 'objectable');
    }

    //some functions here which relate this model to another models
}

vendredi 3 mai 2019

Is Chain of Responsibility pattern just an overkill ? A List of Handlers can accomplish the same

In the 'Chain of Responsibility(COR)' pattern, we create a chain of handlers. Pass the request to the first in the chain. It tries to handle it. If it cannot, it forwards the request to the next in the chain and so on. Eg. Handler1 = new ConcreteHandler1(); handler1.handle

public class ConcreteHandler1 public void handle() { if(can handle) handle the request else concreteHandler2.handle(); }

Can't we simply create a list of handlers and accomplish the same in a for loop?

for(Handler handler : handlers) { if(handler can handle the request) handle. } We will create handlers list in the same way we create the chain. 1. In what way is this for loop inferior to COR? Is n't COR just an overkill? 2. Are there scenarios where this for loop is better and others where COR is better? In your answer - it will be great if you can first answer these questions with Yes/No before going into the detailed explanation.

I know there is a post on this already - What are the advantages of chain-of-responsibility vs. lists of classes? but it does n't clarify my doubts.

how to design storage for transactions involving multiple tables in dynamodb?

I am trying to add transaction support to an existing dynamodb storage which looks like this:

public interface Storage<T>{
T put(T entity);
...
}

public abstract class AbstractDynamoStorage<T> implements Storage<T> {
@Override
public T put(T entity) {
...
}
}

public class DynamoOrderStorage extends AbstractDynamoStorage<CoreOrder> {
...
}

public class DynamoCustomerStorage extends AbstractDynamoStorage<CoreCustomer> {
...
}

Now, I want to add transaction support to this using the newly launched DDB transactions to be able to commit multiple operations(put, write, update..) across multiple tables.

Here's my approach:

interface TransactDAO{
void commitWriteTransaction(TransactWriteRequest writeReq);
}

class DynamoTransactImpl implements TransactDAO{
@Override:
commitWriteTransaction(TransactWriteRequest request){
//dynamodb.transactWriteItems();
}
}

class DynamoDBTransactWriteItem implements TransactWriteRequest{
List<DynamoTransactWriteItem<T>> transactWriteItems;
}

class DynamoTransactWritePutItem<T> implements DynamoTransactionWriteItem<T>{
String tableName;
String data;
...
}

My worry is that the concrete storage classes(DynamoOrderStorage and DynamoCustomerStorage) are of different type and my approach might not work here. Is there any other better way to achieve this?

Whether virtual function coverage violates LSP?

I am learning design patterns, but I think C++ virtual function rewriting violates LSP.

1.Subclasses must implement abstract methods of the parent class, but must not override (override) the non-abstract (implemented) methods of the parent class.

But in order to achieve polymorphism, I have to rewrite(override). Is it that I understand it wrong?

class Animal;
class Cat;

void fun(Animal *xyz) { xyz->eat(); }

class Animal
{
 public:
    virtual void eat() { ::std::cout << "I'm eating generic food."; }
};

class Cat : public Animal
{
  public:
    // override.
    // Whether it violates the principle?
    void eat() { ::std::cout << "I'm eating a rat."; }
};

Creating a collection in a mapper class using an adapter in PHP

I have UserMapper and UserAdapter classes. Also a UserInterface and User class.

I get some data from a 3rd party service. UserAdapter class implements the UserInterface to match the 3rd party data to my own User class.

In UserMapper class, I have getAll, getById, delete, update methods.

In getAll method I want to return a collection of users. I also have an Users array iterator class. getAll methods gets a raw data from 3rd party. With a foreach loop I create User objects and append them to the collection. Finally I return a Users collection.

The problem is creating the User objects is not that elegant. I am looking for a better way to do the same thing. I might be mixed up design patterns, so please fix me if the idea is completely wrong.

Note: The same thing can be easily done with a class and a few methods maybe but the main idea was decoupling 3rd party data and creating a pure domain layer. Also returning proper objects/data types for easier debugging and easy-to-understand code. There are simplified examples. The real business logic is more complex than this.

User implements UserInterface {
  protected $id;
  protected $name;
  protected $age;
  protected $sex;

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

  public function getId() {
     return $this->id;
  }

  public function setName($name) {
     $this->name = $name;
  }

  public function getName() {
     return $this->name;
  }

  public function setAge($age) {
     $this->age = $age;
  }

  public function getAge() {
     return $this->age;
  }

  public function setSex($sex) {
     $this->sex = $sex;
  }

  public function getSex() {
     return $this->sex;
  }
}

UserInterface {
  public function getId();
  public function getName();
  public function getAge();
  public function getSex();
}


UserAdapter implements UserInterface {
  protected $rawData;

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

  public function getId() {
     return $this->rawData['id'];
  }

  public function getName() {
     return $this->rawData['name']
  }

  public function getAge() {
     return $this->rawData['age']
  }

  public function getSex() {
     return $this->rawData['sex']
  }

Users extends IteratorIterator {
   private $iterator;

    public function __construct(ArrayIterator $iterator)
    {
        $this->iterator = $iterator;
        parent::__construct($iterator);
    }

    public function current(): User
    {
        parent::current();
    }

    public function toArray()
    {
        return iterator_to_array($this->iterator, true);
    }
}


UserMapper {
   public function getAll($rawUsers): Users {
      $users = new ArrayIterator();
            foreach ($$rawUsers as $rawUser) {
           $adapter = new UserAdapter($rawUser);
           $user = new User($adapter->getId());
           $user->setName($adapter->getName());
           $user->setAge($adapter->getAge());
           $user->setSex($adapter->getSex());
           $users->append($user);
            }
      $return new Users($users);
   }
}


}

Pattern/structure for classes with the same methods but different parametrs

For example, I develop a grapher, where have two classes:

Function (like 3x+1)

Equation (like x^2+y^2<1)

They have many methods with the same name and same return type, but different input parameters. And also some unique methods. So, I have an array where I store functions and equations together. When I draw its, move, etc I must use if/switch to determine the type. Is there any better solution?

This is example of such code:

interface Grapher {
    //it is empty
}

class GrapherFunction implements Grapher {
    //...some code...

    ArrayList<Point> draw(double left, double right) {...}
    double move(double vx) {...}
}

class GrapherEquation implements Grapher {
    //...some code...

    ArrayList<Point> draw(double left, double right, double bottom, double top) {...}
    double move(double vx, double vy) {...}

    double square() {...}
}


main() {
    //...
    Grapher[] graphs = ...; //store GrapherFunction and GrapherEquation
    for (var graph : graphs)
        if (graph instanceof GrapherFunction)
            graph.draw(0, 1);
        else
            graph.draw(0, 1, 2, 3);
}

PS methods in class Function have completely different realization than in class Equation

Validating model classes in settter methods

Here, I would like to ask your ideas about designing best validation approach for below requirements: we have a User model and depending on it is status we can update some specific fields.

1- if the status of user is ACTIVE then all fields (name, surname, password ....) can be updated 2- if the status of user is INACTIVE only password can be updated 3- if the status of user is BLOCKED then sanme and surname can be updated 4- if the status of user is DELETED then update operation is not allowed for any field.

As you can see, Changeability of model class depends on it's status field. Obviously, it can be done simply by adding UserValidation class and before setting values in setter methods i can call my UserValidator to check if the operation is allowed or not. However, it has a drawback(?) what will happen if there will be new field (let's say martialStatus) and dev who would be adding that field did forget calling UserValidation class before setting martialStatus. Other ways of solving this problem that I can think of: 1- Using custom annotations by extending CustomValidator. However, it won't work as annotation can not know the previous values of object. I mean, isValid Method of CustomValidator won't know if the name field has changed or not(it was john and now dev wants to change it to Jack)

2- Proxy pattern could be useful but not sure if it is good idea to use proxy for model objects

3- I saw on the internet that Decorator pattern can be used for this problem but i can not understand how. I think validating model class is beyond the responsibility of Decorator design

public class User {

private Integer id;
private String name;
private String surname;
private String password;
private Status status;
// setters

}

public enum Status { ACTIVE, DELETED, INACTIVE, BLOCKED }

I Would like to hear your advises. Thanks