Should we save clean architecture entities in DB?

I’m a little confused about how to store the entities in DB. According to Uncle Bob, entities encapsulate Enterprise wide business rules. This mean that they can has methods for example.

But it’s correct pass my entity as a parameter to the GatewayInterface / Repository?

I’m been reading some comments here, and some of them tell that is not recommend pass entities to outer layers. Because you are passing Enterprise business logic.

Should I pass a DTO to my Repository only? Something that the repository can map and then save.

Thanks

Immutable entities and Domain Events

I want to know if it’s a good idea modeling the Domain this way:

  • Entities are immutable
  • When a method of the Entity (Command) is issued, it check the actual state to return the right Domain Event or throw an error if it’s the case
  • It doesn’t change any property of the actual instance
  • Then in the application layer the events are sent to the Repository to be stored

    public abstract class UserEvent {     public string userID { get; set; }     public ulong version { get; set; } } public class UserPasswordChangedEvent : UserEvent {     public string password { get; set; } }  public class User {     public string userID { get; set; }     public ulong version { get; set; }     public string password { get; set; }     public bool deleted { get; set; }      public UserEvent ChangePassword(string newPassword)     {         if(!isValidPassword(newPassword)) throw new SomeException("Invalid Password");         if(deleted) throw new SomeException("User deleted");          return new UserPasswordChangedEvent(){ userID = userID, version = version + 1, password = newPassword };     } } 
  • And the unit tests should be this way:

    public class UnitTest1         {             public void Test1(){                 User us = new User(){ userID = "User1", version = 1, password = "", deleted = true};                 UserEvent ev = us.ChangePassword("NuevaPass");                 Assert.Same(new UserPasswordChangedEvent(){ userID = "User1", version = 2, password = "NuevaPass"}, ev);      }  

    }

  • Is this a valid aproach?

  • What are the drawbacks?

  • Are these cosindered integration tests or unit tests?

Problem of making entities agree on some wavelength

I remember seeing this problem somewhere before, but don’t remember what it’s called and can’t find it again.

It was presented as two guys having $ n$ phones each that don’t ring when called. Each phone from one person is connected to one phone of the other person, in some random permutation. They can each test one phone every “round”, to check if they are using a connected pair of phones and thus able to communicate (this is in some way a consensus problem). They had to devise some strategy beforehand to be able to communicate (and minimize the amount of rounds necessary). Of course, the application behind this would be to make two entities connect on some same wavelength at the same time.

What is this problem called, also what are the best strategies?

Which creatures count as “entities from the shadowfell” for the purpose of a Shadow Magic Sorcerer’s origin?

The description of the sorcerer subclass “Shadow Magic” (XGtE, p. 50) starts off with the following paragraph (emphasis mine):

You are a creature of shadow, for your innate magic comes from the Shadowfell itself. You might trace your lineage to an entity from that place, or perhaps you were exposed to its fell energy and transformed by it.

Off the top of my head, I can only think of Shadar-Kai (MToF, p. 62). Other than that, I can’t think of suitable creatures – Darkmantles or Skull Lords among those not even humanoid, and it’s hard to imagine Meazels (MToF, p. 214) or Skulks (MToF, p. 227) having any offspring.

Are there any entities in the Shadowfell known from 5e or previous versions, aside from the Shadar-Kai, that are known to reproduce with other humanoids?
Or does “entity” include an immaculate conception from the Raven Queen? 😀

Is it better to have a single query that returns all related entities, or separate queries for each case?


Summary

When writing methods to query for related entities, is it better to have a single method for all related entities or separate methods for each combination?

Full Problem

I’m writing repository classes for a .NET MVC project where each repository is responsible for querying for a specific entity type. I’m using Dapper, so all of the queries are written by hand. The repositories all implement an IRepository<TEntity> interface, which has method TEntity FindById(id).

Fetching just the entity is obviously very straightforward, but I’m faced with a dilemma when it comes to fetching the entity’s children and grandchildren and so forth. Often times, for an entity to be usable, it needs some or all of its descendants. I initially wrote FindById to return the entity with all descendants, which satisfies all use cases, but is also wasteful in many where I only need several descendants.

I wrote out individual methods for fetching various combinations. FindByIdWithChildA or FindByIdWithChildBAndGrandChildC and such. The problem here is that the method names keep getting longer and longer, which makes them a pain to read, and also wastes a lot of space in code.

My next idea was to accept various enum flag values designating which descendants to return. This worked fine for the immediate children, but by the time I got to grandchildren and beyond I had so many possible combinations to implement, and many of them didn’t make sense or wouldn’t be used.

By the time I have all this boilerplate written out, it almost feels like I’m writing a bad ORM instead of repositories. This has certainly slowed down development dramatically, and it has taken focus away from actually implementing new features.

The obvious wrong solution is to not use SQL joins and have the repositories splice together entities and collections of entities using LINQ. Using LINQ with EntityFramework could be an option, but I don’t think that the solution is to switch to another library.

Should I just simplify and have the single method/query return everything? If not, what is the best way to concisely implement separate methods?

This answer indicated that a FindByIdWithChild type method is normal, but I can’t imagine that being good practice for complex queries.

Clarification

So my entities are Sport, Division, SkillLevel, and TeamType. Each Sport has a list of Divisions, SkillLevels, and TeamTypes. Each Division has a single TeamType and a list of SkillLevels.

Suppose I want a Division with its parent Sport, its TeamType, and all of its SkillLevels. Should I do:

  1. DivisionRepository.FindById(id) which returns all of these properties, ignoring any case where I want just a Division or a Division and Sport, Division and TeamType, etc.

  2. DivisionRepository.FindById(id, BitFlagQueryScope) which has a big mess of an implementation to resolve all the possible flags, some of which might not be needed.

  3. DivisionRepository.FindByIdWithSportAndTeamTypeAndSkillLevels(id) and have one of these methods for every combination I need.

In all three cases, I am making one trip to the database. It’s just a matter of how I structure my code.

Additional example, suppose I want a Sport with just its TeamTypes. Elsewhere I will need a Sport with its SkillLevels, etc. Same questions as above. I’m only making one database trip, but should I use different code for these different queries, or just grab everything and discard/not use the excess?

Additional Clarification

In case there’s something wrong with my design overall, here’s how I’m using the entities:

Action(string id) {     var sport = SportRepository.FindById(id); // This needs to either return everything associated with the entity or be changed to allow specification     var model = new SportDisplayModel(sport);     return View(model); } 

I have two models, $ Entity$ DisplayModel, and $ Entity$ EditModel, and I use them for every view.

Why Would A Web Server Allow Loading XML External Entities?

I’ve been reading up on XXE Injection, and so far every example I’ve seen has involved a webserver voluntarily loading xml external entities (as below).

<?php  libxml_disable_entity_loader (false);  $  xmlfile = file_get_contents('php://input');  $  dom = new DOMDocument();  $  dom->loadXML($  xmlfile, LIBXML_NOENT | LIBXML_DTDLOAD);  $  creds = simplexml_import_dom($  dom);  $  user = $  creds->user;  $  pass = $  creds->pass;  echo "You have logged in as user $  user";?> 

Given the risk of XXE Injection attacks and the possibility for those attacks to a) disclose confidential information and/or b) perform remote code execution (RCE), why would a web server developer/admin decide to enable loading external xml entities in the first place?

So far I haven’t seen any explanation for what the motivation is to enable loading external xml entities. Is it just lazy coding? Ignorance? Convenience?

DDD: Type hierarchy of entities’ property

Say I have an Delivery class which should have a Destination property (among many others). Destination can be an Address (country, city, address line, post code) or a Port (international code, name). As you see these two types do not have any overlapping attributes. The only thing they have in common is Destination string which should be generated from their attributes and displayed in GUI or sent to printer. What is the best way to model this in DDD context? I have considered the following approaches so far but I am not fully satisfied with either of those:

  • Delivery class has two properties for both destination types + discriminator property which specifies which property of the two is not null.

    • Clients of domain entity have to know about this structure and make a decision which of two Destination properties to use based on internal property of Delivery. This seems like domain logic leak to me.
  • Both destination types implement common interface (IDestinaion) with single method GetLabel(). Delivery class holds property of IDestination.
    • Label might be GUI platform dependent (new line in HTML vs console) so I really don’t want to hold this logic in domain object.
  • Two Delivery sub-classes with single repository.
    • This one is similar to the first point: client would have to know which subclass they are dealing with and do a type unsafe cast to form a label.
  • Two Delivery sub-classes with two separate repositories
    • Seems like a lot of boilerplate code. Also services would have to run queries on both of these repositories as delivery subclass objects would have to be used as uniform objects in most of the use cases.

Which one do you think is the best approach? Maybe there are more designs? Any solutions to the disadvantages that I articulated?

Swift MVVM: Repositories – loading entities and dependency injection

I create a lexikon and a navigation for ZOO. I use MVVM architecture supported by ReactiveSwift. I have a few questions about my practises and whether I could write my repositories better and more clearly.

I would like to know whether is it good to create a generic Repository class and inherited class from this class for loading one kind of entities. Is it suitable to create a parent Repository class and create child classes implementing a suitable protocol used for dependency injection for each kind of entity in this case?

I also work with three types of bindings with animal: FoodBinding – binding between an animal and a kind of food which the animal eats, BiotopeBinding – binding between an animal and a biotope in which the animal lives, ContinentBinding – binding between an animal and a continent in which the animal lives.

I would like to ask you whether is it good to create one class for each type of binding or create a parent class for all kinds of bindings. Is it good to create one repository class for all types of bindings or create a class for each kind of binding? If I would create a class for each kind of binding, is it good to have a parent class for all kinds of binding with a generic functions for all kinds of bindings?

Here is the content of the file AppDependency.swift in Service/Dependency directory. The class AppDependency is used for injection of dependencies in whole application (ViewModels, FlowCoordinators etc.). I think that it is a good practice to use protocols for each service which we want to inject. Is it really a good practice in my case, or not?

import UIKit   /**  This class is used for injection of some dependencies (especially repositories and services) to other code (especially ViewModels and ViewControllers)  */ class AppDependency {     private init() {}     /// instance of AppDependency class used for dependency injection     static let shared = AppDependency()      lazy var animalRepository:AnimalRepositoring =  AnimalRepository()     lazy var localityRepository:LocalityRepositoring =  LocalityRepository()     lazy var speechService: SpeechServicing = SpeechService(language: Locale.current.identifier)     lazy var biotopeBindingRepository: BiotopeBindingRepositoring = BiotopeBindingRepository()     lazy var foodBindingRepository: FoodBindingRepositoring = FoodBindingRepository()     lazy var continentBindingRepository: ContinentBindingRepositoring = ContinentBindingRepository() }  extension AppDependency: HasAnimalRepository{} extension AppDependency: HasLocalityRepository{} extension AppDependency: HasSpeechService{} extension AppDependency: HasContinentBindingsRepository{} extension AppDependency: HasBiotopeBindingsRepository{} extension AppDependency: HasFoodBindingsRepository{} 

Here is the content of the file Repository.swift in Service/Repository directory

import UIKit import ReactiveSwift   class Repository<T: LoadedEntity>{     /// array of entities which is used for storing information loaded from the NodeJS server     lazy var entities = MutableProperty<[T]?>([])     /// date of last editation or loading of array of entities     private var lastEdited: Date = Date()       /**      This function ensures loading data from server and      */     func loadAndSaveDataIfNeeded(){         // if data were loaded unsuccessfully after the starting of the application         if (entities.value == nil){             // updating of result in case that data could not be loaded previously             let result: [T]? = APIService.getEntitiesGotByAPICall(relativeUrl: T.relativeUrl)             if (result != nil){                 entities.value = result                 self.lastEdited = Date()             }          // after the starting of the application         } else if (entities.value!.count == 0){             // loading of the data in the beginning             let result: [T]? = APIService.getEntitiesGotByAPICall(relativeUrl: T.relativeUrl)             entities.value = result             self.lastEdited = Date()          // in other cases - data were loaded successfully last time         } else {             // updating of loaded data each 3 hours             let threeHoursAgo:Date = Date(timeIntervalSinceNow: -3*60*60)              // updating of loaded data when data was loaded more than 3 hours ago             if (self.lastEdited < threeHoursAgo){                 let result: [T]? = APIService.getEntitiesGotByAPICall(relativeUrl: T.relativeUrl)                 if (result != nil){                     entities.value = result                     self.lastEdited = Date()                 }             }         }     }  } 

Here is the content of the file BindingRepository.swift in Service/Repository directory

// //  BindingRepository.swift //  courseworkZoo // //  Created by Daniel Šup on 22/06/2019. //  Copyright © 2019 Daniel Šup. All rights reserved. // import UIKit import ReactiveSwift  /**  This protocol is created for the dependency injection. This protocol ensures loading the repository for working with bindings between biotopes and animals.  */ protocol BiotopeBindingRepositoring{     var entities: MutableProperty<[BiotopeBinding]?> { get }     func loadAndSaveDataIfNeeded()     func findBindingsWithAnimal(animal: Int) -> [BiotopeBinding]? }  /**  This protocol is created for the dependency injection. This protocol ensures loading the repository for working with bindings between kinds of food and animals.  */ protocol FoodBindingRepositoring{     var entities: MutableProperty<[FoodBinding]?> { get }     func loadAndSaveDataIfNeeded()     func findBindingsWithAnimal(animal: Int) -> [FoodBinding]?  }  /**  This protocol is created for the dependency injection. This protocol ensures loading the repository for working with bindings between continents and animals.  */ protocol ContinentBindingRepositoring{     var entities: MutableProperty<[ContinentBinding]?> { get }     func loadAndSaveDataIfNeeded()     func findBindingsWithAnimal(animal: Int) -> [ContinentBinding]?  }    /**  This class is a child of Repository class in which it is stored array of entities with the name entities of type MutableProperty. This class ensures finding bindings to the animal given by an identificator.  */ class BindingRepository<B: Bindable> : Repository<B>{      /**      This function finds bindings between the animal given by the identificator.      - Parameters:         - animal: The identificator of the animal which we find bindings for.      - Returns: Array of bindings with the given identificator of the animal or nil if array of bindings is not correctly loaded.      */     func findBindingsWithAnimal(animal: Int) -> [B]?{         if let bindings = self.entities.value as? [B]{             var bindingEntities: [B] = []             for binding in bindings{                 if(binding.getAnimalId() == animal){                     bindingEntities.append(binding)                 }             }             return bindingEntities         } else {             return nil         }     }  }    // These classes created for simpler dependency injection. These classes are childs of parent class BindingRepository for finding bindings between biotopes, kinds of food and continents and animals. class BiotopeBindingRepository: BindingRepository<BiotopeBinding>, BiotopeBindingRepositoring{ }  class FoodBindingRepository: BindingRepository<FoodBinding>, FoodBindingRepositoring{ }  class ContinentBindingRepository: BindingRepository<ContinentBinding>, ContinentBindingRepositoring{ } 

Here is the content of the file AnimalRepository.swift in Service/Repository directory

import UIKit import ReactiveSwift   protocol AnimalRepositoring{     var entities: MutableProperty<[Animal]?> { get }     func loadAndSaveDataIfNeeded()     func findAnimalById(id: Int) -> SignalProducer<Animal?, LoadError>     func findAnimalInCloseness(latitude: Double, longitude: Double) -> SignalProducer<Animal?, LoadError> }   class AnimalRepository: Repository<Animal>, AnimalRepositoring{      func findAnimalById(id: Int) -> SignalProducer<Animal?, LoadError> {         if let animalList = self.entities.value as? [Animal] {             for animal in animalList{                 if(animal.id == id){                     return SignalProducer(value: animal)                 }             }             return SignalProducer(value: nil)         } else {             return SignalProducer(error: .noAnimals)         }     }      func findAnimalInCloseness(latitude: Double, longitude: Double) -> SignalProducer<Animal?, LoadError> {         if let animalList = self.entities.value as? [Animal] {             for animal in animalList{                 if(abs(animal.latitude - latitude) < BaseViewModel.closeDistance && abs(animal.longitude - longitude) < BaseViewModel.closeDistance){                     return SignalProducer(value: animal)                 }             }             return SignalProducer(value: nil)         } else {             return SignalProducer(error: .noAnimals)         }     }   } 

Here is the content of the file LocalityRepository.swift in Service/Repository directory

import UIKit import ReactiveSwift   protocol LocalityRepositoring{     var entities: MutableProperty<[Locality]?> { get }     func loadAndSaveDataIfNeeded()     func findLocalityInCloseness(latitude: Double, longitude: Double) -> SignalProducer<Locality?, LoadError> }   class LocalityRepository: Repository<Locality>, LocalityRepositoring{       func findLocalityInCloseness(latitude: Double, longitude: Double) -> SignalProducer<Locality?, LoadError> {         if let localities = self.entities.value as? [Locality]{             for locality in localities{                 if(abs(locality.latitude - latitude) < BaseViewModel.closeDistance && abs(locality.longitude - longitude) < BaseViewModel.closeDistance){                     return SignalProducer(value: locality)                 }             }             return SignalProducer(value: nil)          } else {             return SignalProducer(error: .noLocalities)         }     }   } 

In my codes you can see that I created protocols for loading each kind of entities and classes implemented these protocols. I would like you to ask it is a problem (for code quality) that method loadAndSaveDataIfNeeded and entities property is implemented only in the parent Repository or method findBindingsWithAnimal only in the BindingRepository (in case of BindingRepositories) class or not. If it would be solved by better and more clear way, I would like to know how to refactor my code.

How to skip migrating certain entities in Drupal 8 Migration?

How do I skip migration for some entities? To simplify, let’s say I have a node type Cow with a field called field_moo. If field_moo is empty, I don’t want to migrate that nodes to the target. What can I put in my migration YAML to check if field_moo is empty, and if so, to skip the migration for that node?

Is there a source plugin that is similar to the process plugin skip_on_empty?

This is for a Drupal 7 to 8 migration.

Safe and elegant way to access nested entities via fields

I’ve seen a variety of approaches to access entity values. The code below is just a simple example using magic methods. It assumes all values are set – if any part of that returns a NULL, then in my experience errors ensue.

$  value = $  node->field_paragraph     ->entity->field_media     ->entity->field_file     ->entity->field_text->value; 

There are methods like ->hasField and ->count() to check things, and i have a variety in my themes. I can get the job done but sometimes it feels ugly. I’m interested the coding patterns that devs use to safely and elegantly drill through entity references.