How to avoid implementation of a wrong domain concept - software-design

We have the following concept in our application (composed of a UI and a REST backend):
Container is-a-parent-of lineItems
a lineItem cannot be created without having a valid Container and both of these entities are persisted in DB via spring data.
The UI lists the lineItems in two pages
list view: the lineItems of a single Container are displayed
search page: the lineItems of different Containers are displayed
We have a single source of data for both of these UI pages. The data comes from a common REST backend which returns a list of lineItems wrapped in a POJOview object (along with other information) - current state.
Change needed - On the search page, now, we need to show some information from the Container of a lineItem. So, now we need to make available the data of a Container associated with a lineItem on the search page. We are currently discussing two possible approaches for doing it:
Approach 1:
POJOview {
List<LineItem>
List<Container>
}
This approach avoids implementation of a wrong concept(described below) which gets implemented in approach 2.
List<LineItem> and List<Container> are sent separately, so, less data gets transferred to the UI. If 20 lineItems belonging to 1 Container are sent, then there is only one object of the Container as compared to 20 Objects of Container in approach 2.
The code is easier to understand and maintain
A disadvantage is that it requires some extra logic in the search page for the UI to map the lineItem to its Container in the other list
Approach 2:
POJOview {
List<LineItem> //insert Container of a lineItem as a member variable in the lineItem itself. Container instance is annotated with #Transient to avoid persistence in DB.
}
This approach implements a wrong concept in the backend in the sense that lineItem now contains the Container which is opposite of the domain concept (Container is-a-parent-of lineItems) and hence it is not intuitive and makes the code difficult to understand and maintain.
Each lineItem now contains Container, so, if we have 20 lineItems on the page belonging to the same Container, then the Container data which is now a part of lineItem gets loaded 20 times (performance hit)
This has an advantage of a quick fix
The problem is that despite all these facts, my colleague still maintains that Approach 2 is the optimal way since it is a quick fix and he sees nothing wrong in it. Am I missing something here?

As per my opinion, one of the good ways to implement would be as below:
The REST service can return data in following format:
a) A list of LineItem objects where each LineItem object contains just the ID of its container (note: it is not a wrong approach because the child objects can very well contain the reference to its parent as long as the parent data is not repeated in every child).
b) A list of container objects. Obviously only those containers should be returned that are referenced by the line items.
The front end logic can go over the list of line items and look up the container details in the container list.
The data items a) and b) can be sent via separate calls or a single call. Ideally if the REST principles are to be followed strictly and making two calls is not impacting performance, then two separate calls should be made and thus as per the REST principles LineItem Resource is retrieved in one call and Container Resource in another call.
By using this approach, the container information is not repeated, only the container IDs are repeated in the line item objects which should be okay in most cases.
Thus this approach is essentially similar to Approach 1) that you have described except for the fact that lineitems can contain the ID of their parents (container).
As per what I understand, Approach 2 mentioned in the question repeats the full container information for each lineitem object which is definitely wrong. Ids can be repeated but not the full object whether the data is being retrieved from DB or being passed around in the backend or is being sent to front end.
Hope this provides some clarity.

Related

What's the RESTful way of attaching one resource to another?

this is one of the few moments I couldn't find the same question that I have at this place so I'm trying to describe my problem and hope to get some help an ideas!
Let's say...
I want to design a RESTful API for a domain model, that might have entities/resources like the following:
class Product
{
String id;
String name;
Price price;
Set<Tag> tags;
}
class Price
{
String id;
String currency;
float amount;
}
class Tag
{
String id;
String name;
}
The API might look like:
GET /products
GET /products/<product-id>
PUT /prices/<price-id>?currency=EUR&amount=12.34
PATCH /products/<product-id>?name=updateOnlyName
When it comes to updating references:
PATCH /products/<product-id>?price=<price-id>
PATCH /products/<product-id>?price=
may set the Products' Price-reference to another existing Price, or delete this reference.
But how can I add a new reference of an existing Tag to a Product?
If I wanted to store that reference in a relational database, I needed a relationship table 'products_tags' for that many-to-many-relationship, which brings us to a clear solution:
POST /product_tags [product: <product-id>, tag: <tag-id>]
But a document-based NoSQL database (like MongoDB) could store this as a one-to-many-relationship for each Product, so I don't need to model a 'new resource' that has to be created to save a relationship.
But
POST /products/<product-id>/tags/ [name: ...]
creates a new Tag (in a Product),
PUT /products/<product-id>/tags/<tag-id>?name=
creates a new Tag with <tag-id> or replaces an existing
Tag with the same id (in a Product),
PATCH /products/<product-id>?tags=<tag-id>
sets the Tag-list and doesn't add a new Tag, and
PATCH /products/<product-id>/tags/<tag-id>?name=...
sets a certain attribute of a Tag.
So I might want to say something link this:
ATTACH /products/<product-id>?tags=<tag-id>
ATTACH /products/<product-id>/tags?tag=<tag-id>
So the point is:
I don't want to create a new resource,
I don't want to set the attribute of a resource, but
I want to ADD a resource to another resources attribute, which is a set. ^^
Since everything is about resources, one could say:
I want to ATTACH a resource to another.
My question: Which Method is the right one and how should the URL look like?
Your REST is an application state driver, not aimed to be reflection of your entity relationships.
As such, there's no 'if this was the case in the db' in REST. That said, you have pretty good URIs.
You talk about IDs. What is a tag? Isn't a tag a simple string? Why does it have an id? Why isn't its id its namestring?
Why not have PUT /products/<product-id>/tags/tag_name=?
PUT is idempotent, so you are basically asserting the existance of a tag for the product referred to by product-id. If you send this request multiple times, you'd get 201 Created the first time and 200 OK the next time.
If you are building a simple system with a single concurrent user running on a single web server with no concurrency in requests, you may stop reading now
If someone in between goes and deletes that tag, your next put request would re-create the tag. Is this what you want?
With optimistic concurrency control, you would pass along the ETag a of the document everytime, and return 409 Conflict if you have a newer version b on the server and the diff, a..b cannot be reconciled. In the case of tags, you are just using PUT and DELETE verbs; so you wouldn't have to diff/look at reconciliation.
If you are building a moderately advanced concurrent system, with first-writer-wins semantics, running on a single sever, you can stop reading now
That said, I don't think you have considered your transactional boundaries. What are you modifying? A resource? No, you are modifying value objects of the product resource; its tags. So then, according to your model of resources, you should be using PATCH. Do you care about concurrency? Well, then you have much more to think about with regards to PATCH:
How do you represent the diff of a hierarchial JSON object?
How do you know what PATCH requests that conflict in a semantic way - i.e. we may not care about DELETEs on Tags, but two other properties might interact semantically.
The RFC for HTTP PATCH says this:
With PATCH, however, the enclosed entity contains a set of
instructions describing how a resource currently residing on the
origin server should be modified to produce a new version. The PATCH
method affects the resource identified by the Request-URI, and it also
MAY have side effects on other resources; i.e., new resources may be
created, or existing ones modified, by the application of a PATCH.
PATCH is neither safe nor idempotent as defined by [RFC2616], Section
9.1.
I'm probably going to stop putting strange ideas in your head now. Comment if you want me to continue down this path a bit longer ;). Suffice to say that there are many more considerations that can be done.

EXTJS4: Approch to take for multiple Grids showing data from same store but each grid having different records

Suppose that on single page there are two grids which has same column but different records to display.
There could be two solutions to it:
Use same Model and Store and filter on store before rendering the grid.
Potential Problem in this solution: Since the underlying store is same, when the second grid will be
Rendered the filter on first grid will get wiped off.
Use different Store definition and Model Definition (Keeping proxy and fields same as other store/model definition, but just changing the name):
Problems: I tried this on Pandora application and it started giving strange issue such that the second grid did not display any records.
Which approach is better and how to resolve the corresponding issues.
-Thanks
We faced exactly same problem in our project. I ended up using the following approach:
you define one model and one store class
load store from the server for the first grid
clone store object with all records (you might want to google for how exactly to do this)
at this moment you need to decide whether you need just a local copy or copy that tied to the same data source on the server - both can be implemented based on what you need
I can post some sample code for cloning if you need it.
UPDATE
Here is code sample to clone store object:
cloneStore: function(store, storeClass) {
var new_st = Ext.create(storeClass),
recs = [],
filter;
store.each(function(r) {
recs.push(r.copy)}
);
new_st.add(recs);
return new_st;
},
The approach I took and recommend is not to reference the same instance of the store but create a new instance of your store for each grid:
store: Ext.create('MyStore',{...});

Mixing Google Maps custom overlays with Backbone Views

TL;DR
Is PinView.prototype = _.extend(PinView.prototype, google.maps.OverlayView.prototype) the "proper" way to have a Backbone View inherit from another "class"?
Long read
We're redoing our site using Backbone and are working on including some mapping functionality.
I've got a Backbone view that handles placing <div>s onto specific points within the browser window; this seems like a natural thing to extend in order have Google's Map API place them on geographical coordinates.
According to the Google API, in order to generate a custom overlay you create a new object and set the prototype for that object to a new instance of google.maps.OverlayView. You then implement three functions on top of that object so that the object responds to:
onAdd
draw
onRemove
Where onAdd is responsible for generating the HTML and then applying it on top of the Map. This subsequently calls draw which positions the element correctly according to the LatLng pairs and bounds you've provided. onRemove gets called when you want to get rid of your layer.
So I've modified my View to include these three methods (which just call render and unrender and are bound to my collection). And then to make "the magic happen" I'm doing:
PinView.prototype = _.extend(PinView.prototype, google.maps.OverlayView.prototype)
Does this look right? I can post the code for the View and the Model on which it's based, but honestly, they're irrelevant to this example -- the code works and I'm able to place custom divs generated through Backbone model, view and controller components on the map without a issue, what I'm asking I guess (and maybe this question is more apropos for programmers.se, so let me know and I'll move it).
This seems to be the easiest way to make my PinView both a Backbone View and a Google Maps OverlayView, but I'm not 100% comfortable with prototypal inheritance to know if I'm doing something "wrong" or breaking something somewhere down the road.
Nice idea! I'm usually a bit sceptical about weather or not you're 'correct' when things work so if you haven't run into a showstopper and the overlays shows up and does what the're supposed to do I'd say you are.
One thing to check out closer, though:
This isn't (and can't) be "real" multiple inheritance - that concept isn't really relevant in a prototype based language: one implementation of a method will inevitable "win" and overwrite the other implementation, at least when using _.extend()
This means that if there are members or methods with the same names in Backbone.View and google.maps.OverlayView the one last in your _.extend() call will be the one that takes over. But when I inspect them using Chrome's Developer Tools I didn't see any obvious collision of this kind.
So my recommendation: continue using this, just test a lot. I'd love to see an example of this technique some time.
Ah! So I've been doing the above, but it's never felt right.
Then I found this discussion on a Backbone group which leads me to the following:
var MyView = (function(){
var view = function(){
Backbone.View.apply(this, arguments);
};
view.extend = Backbone.View.extend;
_.extend(view.prototype, Backbone.View.prototype, google.maps.OverlayView.prototype, [other prototypes...], { [VIEW DEFINITION] });
return view;
}());
This way if we need to override any of the definitions in a class we're extending from, we can since it's earlier in the _.extend chain (later definitions overwrite earlier definitions).
I'm working on 'extending' extend to keep track of the "parent" object's references that would be overridden and providing a method to call them still (like Python's super call). I haven't decided if this should be done through monkey-patching, an intercepter pattern (via underscore's _.tap() method or something else, but I think it'll add a lot of flexibility.
This would allow you to define an initialize view in your "parent" class which could be called by doing something like _.super('ParentClass', 'initialize'); at the end of the "child" class's initialize routine...

Controlling dynamically created containers

Forgive me, I'm new to Flash Builder 4 and Actionscript 3 (actually, to programming as a whole beyond some very simplistic stuff). I have watched / read a bunch of tutorials, and started a project but now seem to have hit a wall. The answer is most likely simple, but seems to be alluding me.
How do I (or What approach should I take) to control visual elements, for instance, BorderContainer's, that I created dynamically?
As is, I have an Application containing a BorderContainer and a DataGrid. At runtime, 3 new BorderContainers (which are dragable, and resizeable) are created based on XML data that contains X & Y co-ordinates, and Height and Width values, and then added to the pre-existing BorderContainer. How would I go about getting the properties of these children BorderContainers to be displayed and remain up-to-date in the DataGrid (such as when they are moved/resized)?
My intentions in the future would be to have a custom component which displays a summary of these items in a separate area (think photoshop "layers" control, but much more simplistic), but wanted to get a better understanding of what's going on first.
Any input, documentation, examples, etc. is all appreciated. Again, I apologize for what may be an incredibly easy solution, or if any of my language is unclear, I'm new to this ^_^;
I would create an ArrayCollection of the BorderContainers with their various properties set (also make sure you call addElement on the parent BorderContainer). Make sure your ArrayCollection is declared as Bindable, then set it as the dataProvider for your DataGrid. Then specify the columns for your DataGrid based on whatever properties you want to display (height, width, etc). Now whenever the properties of the BorderContainers change, the DataGrid will automatically update.
Assuming a pure AS3 project, the best approach is to build a dictionary of your objects.
Let's also assume you've created identifiers for the components, or can easily create them at runtime.
var containers:Dictionary = new Dictionary();
private function _init():void
{
//some loop to create objects
containers[newObject.name] = newObject;
}
Later you can quickly access it by just grabbing the hashed index from the containers dictionary.
Now, assuming a Flex project, we have a few more approaches we can take:
DisplayObjectContainer implements getChildByName()
Group implements getElementAt, and numElements to iterate over, check names, and return value expected.
Personally, I still prefer the dictionary approach...
As for keeping things up to date, you can look into Binding (typically a Flex-only solution) or more appropriately investigate the events dispatched:
Event.RESIZE
Event.MOVE
etc.
In the handlers, just update your UI!
HTH, otherwise post more info and we'll see what we can figure out.

ASP.NET MVC routing based on data store values

How would you tackle this problem:
I have data in my data store. Each item has information about:
URL = an arbitrary number of first route segments that will be used with requests
some item type = display will be related to this type (read on)
title = used for example in navigation around my application
etc.
Since each item can have an arbitrary number of segments, I created a custom route, that allows me to handle these kind of requests without using the default route and having a single greedy route parameter.
Item type will actually define in what way should content of a particular item be displayed to the client. I was thinking of creating just as many controllers to not have too much code in a single controller action.
So how would you do this in ASP.NET MVC or what would you suggest would be the most feasible way of doing this?
Edit: A few more details
My items are stored in a database. Since they can have very different types (not inheritable) I thought of creating just as many controllers. But questions arise:
How should I create these controllers on each request since they are related to some dynamic data? I could create my own Controller factory or Route handler or possibly some other extension points as well, but which one would be best?
I want to use MVC basic functionality of using things like Html.ActionLink(action, controller, linkText) or make my own extension like Html.ActionLink(itemType, linkText) to make it even more flexible, so Action link should create correct routes based on Route data (because that's what's going on in the background - it goes through routes top down and see which one returns a resulting URL).
I was thinking of having a configuration of relation between itemType and route values (controller, action, defaults). Defaults setting may be tricky since defaults should be deserialized from a configuration string into an object (that may as well be complex). So I thought of maybe even having a configurable relation between itemType and class type that implements a certain interface like written in the example below.
My routes can be changed (or some new ones added) in the data store. But new types should not be added. Configuration would provide these scenarios, because they would link types with route defaults.
Example:
Interface definition:
public interface IRouteDefaults
{
object GetRouteDefaults();
}
Interface implementation example:
public class DefaultType : IRouteDefaults
{
public object GetRouteDefaults()
{
return new {
controller = "Default",
action = "Show",
itemComplex = new Person {
Name = "John Doe",
IsAdmin = true
}
}
}
Configuration example:
<customRoutes>
<route name="Cars" type="TypeEnum.Car" defaults="MyApp.Routing.Defaults.Car, MyApp.Routing" />
<route name="Fruits" type="TypeEnum.Fruit" defaults="MyApp.Routing.Defaults.Fruit, MyApp.Routing" />
<route name="Shoes" type="TypeEnum.Shoe" defaults="MyApp.Routing.Defaults.Shoe, MyApp.Routing" />
...
<route name="Others" type="TypeEnum.Other" defaults="MyApp.Routing.Defaults.DefaultType, MyApp.Routing" />
</customRoutes>
To address performance hit I can cache my items and work with in-memory data and avoid accessing the database on each request. These items tend to not change too often. I could cache them for like 60 minutes without degrading application experience.
There is no significant performance issue if you define a complex routing dictionary, or just have one generic routing entry and handle all the cases yourself. Code is code
Even if your data types are not inheritable, most likely you have common display patterns. e.g.
List of titles and summary text
item display, with title, image, description
etc
If you can breakdown your site into a finite number of display patterns, then you only need to make those finite controllers and views
You them provide a services layer which is selected by the routing parameter than uses a data transfer object (DTO) pattern to take the case data and move it into the standard data structure for the view
The general concept you mention is not at all uncommon and there are a few things to consider:
The moment I hear about URL routing taking a dependency on data coming from a database, the first thing I think about is performance. One way to alleviate potentialy performance concerns is to use the built in Route class and have a very generic pattern, such as "somethingStatic/{*everythingElse}". This way if the URL doesn't start with "somethingStatic" it will immediately fail to match and routing will continue to the next route. Then you'll get all the interesting data as the catch-all "everythingElse" parameter.
You can then associate this route with a custom route handler that derives from MvcRouteHandler and overrides GetHttpHandler to go to the database, make sense of the "everythingElse" value, and perhaps dynamically determine which controller and action should be used to handle this request. You can get/set the routing values by accessing requestContext.RouteData.Values.
Whether to use one controller and one action or many of one or many of each is a discussion unto itself. The question boils down to how many different types of data do you have? Are they mostly similar (they're all books, but some are hardcover and some are softcover)? Completely different (some are cars, some are books, and some are houses)? The answer to this should be the same answer you'd have if this were a computer programming class and you had to decide from an OOP perspective whether they all have a base class and their own derives types, or whether they could be easily represented by one common type. If they're all different types then I'd recommend different controllers - especially if each requires a distinct set of actions. For example, for a house you might want to see an inspection report. But for a book you might want to preview the first five pages and read a book review. These items have nothing in common: The actions for one would never be used for the other.
The problem described in #3 can also occur in reverse, though: What if you have 1,000 different object types? Do you want 1,000 different controllers? Without having any more information, I'd say for this scenario 1,000 controllers is a bit too much.
Hopefully these thoughts help guide you to the right solution. If you can provide more information about some of the specific scenarios you have (such as what kind of objects these are and what actions can apply to them) then the answer can be refined as well.

Resources