I have a bunch of questions regarding Java 8 and SDN4. I created a model in Neo4j v3.0, played a bit with Cypher queries, and now moved to creating a Spring Boot application. As i started coding classes in Java, I've begun to rethink some of my model as well. Here's some questions in my mind (and I haven't found an example explaining this):
Do you need to use Interfaces in Java, with SDN?For eg. I'd code a Product interface and then have my products implement it, but is that how it's done when working with labels?
This is somewhat tied to my question on inheritance - I'd usually have a ProductFamily that my Product would inherit from. At the database level its modeled as (:Product)-[PartOf]->(:ProductFamily), but in the code these would not be super/sub class.
Any examples of using Generics in a graph context?
Is there a way to define constraints on what relationships a node can have and their direction in Java?
I understand there is probably not one right answer, but there's precious little on the web, so hope to get enlightened here!
If you had a Product interface annotated with #NodeEntity, then the you'll have the Product label in addition to the label on your implementing class, which I assume is what you want. If your interface isn't annotated, then your implementing classes will not inherit a label from it.
Not sure what you mean- if you say you have a ProductFamily that Product inherits from, but in the code it would not be a super/sub class?
Based on your graph model, if you want (:Product)-[PartOf]->(:ProductFamily) then you will have a Product class that maintains a reference to a ProductFamily class, and that reference annotated with #Relationship. If the Product class inherits from ProductFamily then persisting the Product will result in two labels- Product and ProductFamily because a Product IS-A ProductFamily.
How do you see yourself using generics- the answer really depends on that. Some cases are supported, some are not (an example of something not supported right now is equivalent of template.createRelationBetween in SDN4)
Yes, via the #Relationship annotation which accepts a type and direction. Note that this annotation only constrains your domain model, but you could very well flout this by creating relationships in another direction via a custom query.
If for example I've this ActiveRecord model:
app/models/order.rb
class Order < ActiveRecord::Base
# model logic
end
require "lib/someclass.rb"
lib/somelass.rb
class Order
before_save :something
# more logic here
end
Is that a good way to refactor/extract logic from model?
Or maybe use concern class, service class or something else?
Like someone told me a long time ago:
Code refactoring is not a matter of randomly moving code around.
In your example that is exactly what you are doing: moving code into another file
Why is it bad?
By moving code around like this, you are making your original class more complicated since the logic is randomly split into several other classes. Of course it looks better, less code in one file is visually better but that's all.
Prefer composition to inheritance. Using mixins like this is asking to "cleaning" a messy room by dumping the clutter into six separate junk drawers and slamming them shut. Sure, it looks cleaner at the surface, but the junk drawers actually make it harder to identify and implement the decompositions and extractions necessary to clarify the domain model.
What should I do then?
You should ask yourself:
Which code goes together and could be part of a new class / module ?
Where does it makes sense to extract code to somewhere else ?
Do I have some piece of code that is shared across my application ?
Can I extract recurrent patterns in my code base ?
Extract Service Object
I reach for Service Objects when an action meets one or more of these criteria:
The action is complex
The action reaches across multiple models
The action interacts with an external service
The action is not a core concern of the underlying model
There are multiple ways of performing the action
Extract Form Objects
When multiple model can be updated by a a single form submission, you might want to create a Form Object.
This enable to put all the form logic (name conventions, validations and so on) into one place.
Extract Query Objects
You should extract complex SQL/NoSQL queries into their own class. Each Query Object is responsible for returning a result set based on the criterias / business rules.
Extract Presenters / Decorators
Extract views logic into presenters. Your model should not deal with specific views logic. Moreover, it will enable you to use your presenter in multiple views.
More on decorators
Thanks to this blog post to help me putting these together.
Keeping the code in the same class moves logic, it doesn't extract it.
Externalizing callback declaration is misleading and potentially dangerous. Callbacks are abused enough; forcing readers to hunt down related files is cruel.
There's no general way to answer the question as asked; the "best" refactors depends on what's actually being refactoried. Lifecycle information should be obvious and precise, though.
Concerns, services, decorators, facades, etc. are good mechanisms that support refactoring. Without knowing what's being refactored it's impossible to provide meaningful advice regarding what's "best".
It's a fairly common scenario for an application to pull data from a server (usually a JSON string). This data is then parsed and converted into native classes like NSString, NSArray, NSDictionary, etc.
Most of the time, however, we want to use custom models to represent this remote data.
For example if we're pulling a JSON array of blog posts we'd want to map those into BlogPost model objects for example:
// BlogPost.h
#interface BlogPost: NSObject
#property NSString *title;
#property NSString *body;
#property NSDate *dateCreated;
#property NSArray *comments;
#end
What's your approach for decoupling the "JSON" model from the native model?
I often find myself writing a custom initializer in the model itself which takes a dictionary (which typically comes from the JSON feed).
For example:
// BlogPost.h
+ (BlogPost *)blogPostWithJSON:(NSDictionary *)jsonDictionary;
Then I have to keep track of the keys used on the server and map those to my properties.
I always feel a little uneasy doing this because the model in the application shouldn't really have to know what keys are used on the server.
Should I instead move this JSON-to-Object mapping in another class? Perhaps a Factory? Or should my network manager be creating and returning ready made objects to me directly?
Perhaps something like:
// NetworkManager.h
- (void)getBlogPostWithCompletion:(void (^)(BlogPost *blogPost))completionBlock;
(Of course I'm omitting lots of details here like which blog post to get but it's just to demonstrate an approach).
Any other approaches? How do you decouple your server data from your local models?
I have faced this problem a couple of times and got pretty much the same questions as you. In the end what I find works for me is:
Create an OO representation of the original model. In your case this would mean decoding the JSON array into whatever it uses as an underlying model (a dictionary?). Depending on how is modeled the service that you are using, you may end up with some "record classes" (i.e. classes without behavior). I generally prefer to have these type of classes instead of arrays or dictionaries, since as your software evolves this allows to add behavior to them if you need. If, on the other hand, you use arrays or dictionaries you can't do that.
Once you have a low-level OO model, create an OO domain model. In this new model you design things as your domain requires and not tied to the service provider's model. Many times you will find a 1 to 1 mapping between your domain classes and the provider's one, but that is not mandatory. The point here is that you should abstract your domain and design it as you feel is right.
The mapping between this two models can be done in different ways, according to its complexity. I generally like to pick one of these three approaches and stick to it in order to have an homogeneous approach in the project:
Write a class method (class)HighLevelObject>>from(aLowLevelObject) in your domain model. This takes a low level object and configures itself. You do this for all your high-level objects that have a low-level counterpart.
The opposite to the previous one: write an instance method LowLevelObject>>createHighLevelObject() in the low level object that creates an instance of your domain model. Here you a re shifting the responsibility of creating a new object to the lower layer.
Create a factory or builder (depending on the complexities of your models) that takes care of the whole creation process.
If you have simple models with many 1 to 1 mappings between them I would go for options 1 or 2. Which one to choose depends pretty much on your tastes; the option 1) has the advantage that the object knows how to construct itself but places the transformation process burden in the domain model. The second approach leaves a "cleaner" domain model, but forces the lower layer to know the details of the upper one and may force you to break encapsulation. I don't think that there is a silver bullet here; IMHO you should choose the approach that best fits your needs and programming tastes.
HTH
Want to improve this post? Provide detailed answers to this question, including citations and an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I have a drop down list that displays values from a table to the end user. I would like to have these values be sorted alphabetically.
According to proper MVC design, at what layer should I place my sorting logic: the model, the view, or the controller?
EDIT: In response to LarsH's question, "Do you mean code that determines what sort order is desired? or code that performs the sort?", I was originally referring to the code that determines what sort order is desired.
Who controls the sort order?
(From Wikipedia)
1) Natural order within the data itself:
The order is part of the Model, so it should go there. A raw pull of "all data" would return the data in the sorted order, and there is no interface to choose the sort order.
2) The user should control how they see the data:
The View would provide an interface (such as ascending/descending arrows) that interact with the Controller, and the Model understands the data well enough to do the requested sort on the data. However, a raw pull of the data doesn't necessarily have to be sorted, unlike in (1).
In either case,
The View doesn't understand that there's a sort going on, other that the ability to show which sort direction has been chosen. Don't put the logic there.
Small caveat
The sorting functionality could go purely in the View, under one circumstance (that I can think of offhand; there may be more):
A "dumb" sort where all the data is already in the view and it doesn't have to use any domain knowledge to do the sort. Very simple string or number comparison, for example. This is not possible in, for example, search results on a webpage when results are likely to be split across multiple pages.
(Note: this quote and citation is taken from #dasblinkenlight's answer, but we disagree on our interpretation of it. read his post and make up your own mind).
According to MVC description,
A controller can send commands to its associated view to change the view's presentation of the model (for example, by scrolling through a document). It can send commands to the model to update the model's state (e.g. editing a document).
Sorting logic (e.g., the sorting comparator/sorting algorithm) belongs in the model since it contains business rules and state data. Since altering the way the model data is sorted falls squarely into the "change the view's presentation of the model" category, the controller is responsible for "doing the sorting" by calling the model.changeSortedState() method.
According to MVC description,
A controller can send commands to its associated view to change the view's presentation of the model (for example, by scrolling through a document). It can send commands to the model to update the model's state (e.g. editing a document).
According to this, sorting logic belongs in the controller, because altering the way the model data is sorted falls squarely into the "change the view's presentation of the model" category.
EDIT: To clarify multiple misunderstandings voiced in the comments, the "sorting logic" is not the code that performs the sort; it is the code that defines the sort. The sorting logic compares individual items to each other to establish an order (e.g through an instance of IComparator<T>) or contains logic that constructs an object to be used for ordering by an external system (e.g. through an instance of IOrderedQueryable<T>). This logic belongs in your controller, because it needs knowledge related to the "business" side of your application. It is entirely sufficient to perform the sort, but it is separate from the code that actually performs it. The code that sorts may be in your view, in your model, or even in the persistence layer that backs your model (e.g. your SQL database).
None of the above. Sorting is business logic, and business logic doesn't belong in any of the three. Not every piece of code in your application will be a model, view, or controller.
What I generally do in my MVC apps is I have a service layer that performs all the business logic. The methods in the service layer should have a clean, simple API with well named parameters. You can then invoke those methods from your controller to manipulate the data in the models.
In that sense, the sorting is "in the controller", but the code itself that does the sorting should not be implemented in the controller, only invoked from there.
Definetly not the controller: It sends messages to view and model but should do as little work as possible. If the user can change the sorting that request gets handled by the controller by informing the model or the view about it.
Maybe the View if it is a pure View thing. If the Application works just as well without sorting then the sorting is just part of the representation and should go in the view.
If the ordering is inherent part of the domain it should go in the model.
Views are the part of MVC which is supposed to contain presentation logic.
Model layer is where business logic is contained.
Controllers only change the state of both, based on user input.
So the choice is - do you think that this is part of the domain business logic or presentation logic.
If you were implementing a proper MVC Model2 or classical MVC pattern, then I would say that the ordering of data provided by the model layer should be triggered by the view's request to the model layer. View asks for ordered data, model layer provides it.
But, since you are using ASP.NET MVC's interpretation of MVC pattern, which is a bit different then your standard MVC - the ViewModel instance should request ordered information from the model layer (for some reason ASP.NET framework thinks that templates should be called "views" and views should be called "viewmodels" .. it's strange).
I would usually do it in the controller to remain in line with the pattern as per the other answers. See below for reasoning.
I've been mulling this over and reading the answers and related material and pragmatically speaking I would say it would depend on your application for instance:
Is it a medium/large application and/or has multiple UI's associated with it (i.e. a Windows App, Web interface and Phone interface).
In this case I would probably construct a service layer and put it in
the business object and then call the appropriate method from the
controller.
If its a well defined single UI website and you're using something like EF Code First and you do not have or have no intention of creating a service layer and plan on using a simple out of the box Extension method to acheive it:
In this case I'd probably put it in the controller as pragmatically
its the best fit with regard to time/budget.
If its the same as the above BUT cannot be implemented with an out of the box extension method.
I may well choose to pop it in the Model class (if its truely bespoke
to that single type) as it would be more appropriate here than in a
controller. If the sort could be applied to more than one class then
I'd implement it in an extension method and then call it in the
controller.
To sum up:
Dogmatic answer: Service Layer
Pragmatic answer: Usually the controller
I would suggest sorting data from a table-data that is small enough to be useful in a dropdown list-should come from the DB already sorted via the query. To me, that makes the model the place the sort is applied.
If you are determined to do the sort by hand, I think there are good arguments for using either the model or controller as your preferred spot for logic. The limitation would be your particular framework. I prefer to manage data solely in the model. I use the controller to marry data(model) and presentation(view) as I've been (self)taught.
Whilst I agree in principle with the idea that sorting is Business Logic because by breaking it down to it's origin you would end up with something like "The client would like the Product page to display with the images sorted by date" then it becomes clear that the sort order for data is typically not arbitrary - even if there is no sorting as that's still a business decision by omission (an empty list is still a list).
BUT... These answer don't seem to take into account the advances in ORM technology, I can only talk in relation to the Entity Framework (let's avoid an argument about whether this is true ORM, that's not the point) from Microsoft as that's what I use, but I'm sure other ORMs offer similar functionality.
If I create a Strongly Typed view for a Product class using MS MVC and the Entity Framework and there is a foreign key relationship between the Product and Image table (e.g. FK_Product_Image_ProductId) then I would out-of-the-box be able to quickly sort the images during their display using something like this in the view:
#foreach(Image i in Model.Image.OrderBy(e => e.DisplayOrder)){ //etc etc... }
There was mention of a specific Business Logic layer, which I also use to perform 80% of my business logic, but I'm not going to write sort functionality into my Business Logic layer that mimics something that comes out-of-the-box from the Entity Framework.
I don't think there's a correct answer to this question, other than to say that; you should abstract complex business logic where possible but not at the cost of reinventing the wheel.
Assume that you have MVC website, WebForms website and a mobile application.
If you want sorting to be consistent between these presentation layers, then I'd say sort outside of the presentation layer. Service would be a good candidate.
Otherwise, I would store that logic in a view model. Why? Because it'll be reusable and easily testable.
Out of the three you have listed, I would say that it belongs in the controller. I don't really like placing this sort of logic in the controller, though. I usually create a service layer that the controller communicates with that will be responsible for communicating with the data store and handling sorting logic. For small applications it is fine sitting in the controller, though.
This is a question asked with the asp.net in mind, but since somebody did mention Rails, I thought it would be interesting to consider the problem in that context. In Rails, it is natural and pretty common to perform the sorting along with the retrieval as a controller action, since the framework and ActiveRecord/ActiveQuery api provisions for it. On the other hand, it is possible to define some sort of custom sort order for static items and put that in the model to be used by the controller, so the model can play a part in the sorting logic even though it does not carry out the operation directly. Whatever it is, it can be safe to say that putting the sort logic in the view is generally frown upon.
I'm slightly amused that some answers are absolutely against putting the sort in either the controller or the model, and I find them too pedantic for my taste, but I suppose it depends on the nature of the framework used and the usual conventions associated with it. I also agree with Bill K's comment that having the separation in the first place is more important.
This is possibly a bit of a stupid question, but I am getting confused due to the ASP.NET MVC book I am currently reading...
Working with Linq-To-SQL it seems to say that it is not good practice to pass the Linq-to-SQL objects straight to the controller, but that each object should be modelled separately first and this should be passed between the controller and the repository.
Say, I have a database of products. Linq-to-SQl creates a product class for me with Name, Price and Whatnotelse properties. I could pass that straight from repository to controller and then view, but instead it seems to recommend that I use and third class, say Product_Entity, with also Name, Price etc. properties and pass that to the controller.
I fail to see the benefit of this approach, except possibly for adding attributes to the properties... But apart from that it seems to have more drawbacks than benefits. Say each product has manufacturer information as well, I don't see how I can model that easily in my third class.
Is this approach really best practice? Or did I misunderstand all that? If so, why is it bad to work straight off the linq-to-sql generated objects? And how do you deal with relationships between objects in y
The huge benefit to this other class you create is that, to use your example, it doesn't necessarily map to either a product or a manufacturer. Think about it like this:
Your Linq to SQL classes are meant for talking in the "data" domain.
Your "data" classes (the ones you're having trouble with) are meant for talking in the "application" domain.
Let's take an example. Suppose in your MVC application you wanted to show a grid of information about products. You want to see their Name, Price (from the Product table) and their Country of Manufacture and Manufacturer name (from the Manufacturer table). What would you name this class? Product_Manufacturer? What if later on you wanted to add properties from yet a third table such as product discounts? Instead of thinking about these objects in purely the data domain, think about them with regard to your application.
So instead of Product_Manufacturer, what about calling it ProductSummaryItem? Each property of the ProductSummaryItem class would map 1:1 with a field shown in your grid on the UI. Your controller would perform the mapping between the information in the data domain (Product, Manufacturer) with the custom class you'd created in the application domain (ProductSummaryItem).
By doing this, you get some awesome benefits:
1) Writing your views becomes really, really simple. All you have to do to display your data is loop through the ProductSummaryItems and wrap them in and tags, and you're done. It also allows for simple aggregation. Say for example you wanted to add a field called ProductsSoldLastYear to your ProductSummaryItem class. You could do that very simply in your views because all it is to them is another property.
2) Since the view is trivial and there's mapping logic in the controller, it becomes much easier to test the controller's output because it's customized to what the view is going to see.
3) Since the ProductSummaryItem class only has the data it needs, your queries can potentially become much faster because they only need to query for the fields that would populate your ProductSummaryItem object, and nothing else. This overhead can become overbearing the more data-domain objects make up your ProductSummaryItem object.
This pattern is called Model View ViewModel (MVVM) and is hugely popular with MVC as well as in frameworks like WPF.
The argument against MVVM is that you have to somewhat reimplement simple classes for CRUD operations. Fair enough, I guess, but you can use a tool like automapper to help out with things like that. I think you'll find fairly quickly, though, that using the MVVM pattern even for CRUD pays dividends, because before you know it, even with simple classes, you'll start wishing you had extra fields which can easily drive your views.