Connecting domain and application logic to present entities in the UI - react-native

For the first i want to sorry for my english. I'm learning domain driven design and trying to implement some concepts in an application i'm working on. My task is not so complex to fully implement DDD on all the levels but i really like it's principles and the core idea and try to use it.
Lets say app is selling books. So i have a Book entity and BooksCollection or BooksRepository. I'm working on frontend and that collection or updates to it is coming from server. And i want to represent it on BooksScreen in BooksList which consists of BookCard. Press on that card for the first calls something like selectBook which changes the selectedBookId in collection and for the second navigates user to BookDetails screen where the data of selected book is represented and the user can do some actions related to domain logic.
The first question is where do i put the loading state of that BooksCollection and according actions to change it ? Loading state is not a domain logic as i understand, it's not an entity status like "todo done" or something. But i need to show a loading indicator in the UI list when the collection updates, error for loading error and success respectively.
And the second is where do i put the the same loading state for single Book ?
I separate it cause for collection i may store that state in some application related class e.g. "BooksScreenState" or something with less stupid name. But what if i decide to show state for each specific card in the UI e.g. that specific card failed to load. Or i have a single User in app and his data can be loading, he can be authorized or not et cetera.
So i can summarize that to something like "how to connect domain and application logic to present a UI".

An interesting question. I don't usually think to apply DDD to the UI level because for the most part, the UI isn't full of business rules and also because I mostly use reactjs and UI frameworks are usually very prescriptive and don't allow much in the way of flexibility.
To answer your question though: If you did want to get a "loading" status in your UI (that's designed using DDD), it'd have to be attached to a "View" object or some representation of the "view"; because that fits the UL (ubiquitous language) better. Think of how you have described it in a little snippet of your question:
But what if i decide to show state for each specific card in the UI
That means your card is an object (entity or value object) that has a enumerable state of loading, loaded, error. You can queue on that object in your UI to display a desired representation of that field.
So, both your questions have essentially the same answer. Since you are loading the UI, your state is only relevant to UI objects and not entities that are in the domain model like "Books" that are represented in the backend. Even if you had a front-end representation of "Books" - like in javascript for example - having a loading state still makes more sense in the view object in the view layer.
Note that there's some simplification/flexibility to this answer because it's also valid for your design to have a View that's an aggregate that contains a Books. Those Book objects could have a "loading" state on them. All of this is still restricted to the UI layer though and such an aggregate and it's specific design will depend on the flexibility your UI-framework allows.

Related

Where to persistently store basic component-specific state

I'm very new to React + Electron. I'm wondering where most people store basic, component-specific state.
Scenario: I have created a custom component. Basically a type of table. The relevant bit of this table to the question is that I allow users to show/hide columns, or even modify the column order.
I'd like these 'column settings' to persist even if the user closes and reopens the application.
No other part of the application is interested in the column settings. They simply affect what is shown in the custom table component.
The underlying data model is not affected by these settings.
I've looked around at a bunch of solutions. Most will probably work, but not sure which is appropriate.
Redux: I could store these bits of component state there. However, the Redux docs give the impression that it is more targeted towards storing global app state. No other component in my application cares which columns the user chose to hide in this table. Thus, it would seem like a gratuitous use of Redux, when this probably should be something handled locally in the component irrespective of whether Redux is present or not.
Localstorage: This would probably work. Main concern is if the user decides to run multiple instances of the app. There could be a vanishingly rare race condition if both instances decide to save the column state at the same time. I don't consider restricting app instancing a proportionate solution just for something as trivial as these columns settings.
electron-store: Says it does atomic writes. But what if I want to use this component one day outside of electron (say in a web app nb: this is very low priority consideration - i'm very unlikely to use it outside of electron)? Should I tie the component to electron just for this? Also, is using ipc (since e-s lives in the main proc) to save trivial settings like this overkill?
What do people do for this?

DDD Request & Activity Tracking

I have a question about tracking activity and where it belongs.
With a lot of my domain commands, you also might want to track the activity and modifications made by users to a particular context or object.
For example:
lets say we have a items domain/context where we can create and edit items. Users are going to make requests to the api to do this. We might want to track who created an item and an modifications made to it.
In a typical CRUD model, you'd probably find the created by field in the domain object/table
Something doesn't feel right when using DDD to have the activity in the domain object. The activity log feels like a general service that would cross many boundaries? Is it right to have the activity log of who changed what in the domain object. It would feel quite clean and focused without it. The activity logging seems specific to the applications case, not the domain?
So:
Should the activity tracking be in the domain object?
If it shouldn't how do you go about handling this in one command/request. I keep hearing people saying about you should only touch 1 boundary in a command/request.
I would think of this activity log as any other piece of data. You would put it together with the business logic around it. Why do you need this information in the first place? Is your items context going to implement business logic that needs the activity log? If not, then I'd say it doesn't belong in that context.
If what you are trying to achieve with this log is some data analysis that needs the activity from several contexts, then I would say publish events from your business operations (every time a user does something with one of the contexts) and have your activity tracking context listen to them and store the activity in a way that serves this purpose.
If, instead, your items context needs to apply some sort of logic, based on the past activity, then keep it in that context in a format that allows you to implement this business logic.
It's also possible that you actually need both. Some context might just publish the events and not store the activity, while others will publish the events and also track the activity for their own internal needs.

In SOA architecture should single API do everything or API should be split as multiple action

We have an app which is exposing a RESTful API to a UI for purchasing an item. I have a question regarding API design. Lets say the following action should be taken in order
Item to be chosen for purchase
Next give the address to be delivered to
My question is: should we design a single API which gets both data perform both? Or should we design two API calls - one that creates a purchase record and second that update the address to be delivered to?
The recommended SOA approach is to choose coarse-grained services, which would seem to argue the minimum amount of API calls.
However, from a business point of view, item selection and purchase and item delivery are two very different concerns that should be separate components in your architecture. For item selection, you need to consider things like inventory and pricing. For delivery address, you need to consider user address lists, address validation, shipping, and taxation.
Those two components are not likely to interact much except maybe some external association between an item id and address id. For this reason, I'd recommend two API calls. Functionally, this would also allow your API users do things like update the delivery address without re-purchasing an item, send the bill to one address and the item to another address, etc.
As you state that you design a RESTful API you usually start by designing resources instead of the intended calls. Later on, resource representations can be chosen that include other resources for optimised HTTP request counts.
You might want to choose to proceed the following way:
Model the item list resource (GET - lists all items, POST - allows item creation) /items/
Model the address list resource /addresses/
Model the item instance resource /items/item/resourceId
Model the address instance resource /addresses/address/resourceId
Now all of your resources are available you can think about usage patterns. All your resources are generically available and can be mashed up.
Possible approaches to answer your questions would be:
Extend the item instance resource with the needed address details (coarse grained as lreeder stated)
Model a resource /deliverydetails/ as list and instance resource containing item(s) and address, make the deliverydetails to be queried by item id or whatever your use case fits best
Hope that helps!
Btw. you are automatically following SOA approaches with a Resource Oriented Design. Interfaces will be naturally fitting your business requirements and generic enough to support more advanced use cases.
Here is a good example

Basic design for rich (multi-step) search in Rails

A core piece of the application I'm working on is allowing the user to explore a complex dataset by progressively add search terms. For example, you might start with a free-text search, then progressively add (or remove) some facetted search terms, move a slider to constrain some dimension of the returned results, etc.
Conceptually, it seems to me that the user is incrementally defining a set of constraints. These constraints are used to search the dataset, and the rendering of the results provides the UI affordances to add further search refinements. So building this in Rails, I'm thinking of having one of the models be the current set of search constraints, and controller actions add to or remove constraint terms from this model.
Assuming this is a sensible approach (which is part of my question!), I'm not sure how to approach this in Rails, since the search is an ephemeral, not persistent, object. I could keep the constraints model in the session store, but it seems rather a complex object to be marshalled into a cookie. On the other hand, I could put store the constraints model in a database, but then I'll have a GC problem as the database fills up with constraint models from previous sessions.
So: how best to build up a complex interaction state in Rails?
Here's some pointers
create a class XxxSearch with accessors for all the search facets: keywords, category, tags, whatever. This class should be ActiveModel compatible, and it's instances are going to be used in conjunction with form_for #xxx_search. This class is not meant for persistence only for temporaryly holding search params and any associated logic. It may even act as a presenter for data: #xxx_search.results, or implement search data validations for each faceting step.
incrementaly resubmit the form via wizard technique, or even ad-hoc data insertion on a large form.
allways submit the search via GET, as such:
the search is bookmarkable
you can chain the params to pagination links easily like: params_for(params[:search].merge(:page => 3))
you need NOT use the session, the data is forwarded via GET params, as such:
can keep using cookie session store
escapes you from a lot of headaches when the last search is persisted and the user expects a new search context (I say this from experience)
I had to solve this problem for several apps so I wrote a small gem with a DSL to describe these searches:
https://github.com/fortytools/forty_facets

OOP design - validation when validation means hitting the database to check

Let's pretend we're talking about an HTML complaint form, one field of which is a product list from the company catalog.
I gather that validation usually (always?) goes in its own class.
I also gather that it's good practice to have gateway classes which can handle all the database queries internally, so when I save my complaint from my complaint form I don't have to worry about the database details.
But what about validation that requires accessing the database - for example checking that the product is actually a product we have (and not someone tampering with the form). This can only be done by finding a match in the database... but my database is abstracted behind my gateway.
Do I add validation logic to my gateway? Do I create validator gateway classes? Do I empower my validator with database logic?
EDIT - attempt to clarify...
customer clicks link to complaint form
HTML complaint form is built with a <select><item></item></select> dropdown with X products from our fictional company catalog
Customer completes form and Submits // Wiseguy alters HTML so product is "Schweddy Balls" and submits
Form class validates simple things like date, all required fields have data, email address, etc.
at step 4, in order to validate that the product being complained about is legit, you'd have to hit the database's product table to see if it's still a valid datapoint. Should that logic go in the form class, the gateway class, or somewhere else? putting it in the form class breeds dependencies, does it not?
Validation should, oddly enough, not be done directly through a Validation class. A model object's class (in this case probably Complaint) should include the Validation class and the validations should be done in there. Since the Complaint has access to all Complaints, validation methods can use the methods of the Complaint class, or call another model class if needed.
When you say "gateway" to the database, I believe you're talking about on Object Relational Mapping (ORM), which allows model objects, like a Complaint, to abstractly talk to the database. The ORM should have no knowledge of the structure or specifics of the application, it should only be an abstract API for objects to communicate to the database or other backend.
Surely my response does not cover everything, so further questions/clarifications welcome.
It's usually good practice to store valid data, only. So, one necessarily writes a validator on the server-side to ensure that requests are valid and only valid data gets put into the database, and as an optimization one typically validates on the client side (e.g. in JavaScript) so that the user is informed of invalid input without needing to submit the form and without needing to make a roundtrip. Doing the validation as part of the database write, allows subsequent reads to be done trivially with no checks.
I don't know the specifics of what counts as "valid" for you, but you can probably save a lot of database lookups with caching. Perhaps you could give some more information about your requirements?