Tapestry: When should a Session State Object be preferred to a Session Attribute? - session

From the Tapestry doc I seem to understand that a field annotated with #SessionAttribute and a field annotated with #SessionState work in the same way, except that #SessionAttribute stores the value by name (and the name can be specified), which means that different instances of the same class can be stored, while #SessionState stores the value by type so storing different instances of the same class will not work, the new instance will always overwrite the old one (even if the two are different fields with different name and from different classes).
So it seems that #SessionState doesn't offer any advantage over #SessionAttribute, only limitations, but I'm probably missing something. I'm not able to figure out any case where using #SessionState could be more advisable than #SessionAttribute for any reason.
Are there such cases ?

#SessionAttribute is largely intended for some interop cases, where some other, non-Tapestry code (another servlet) is expecting the data to be stored using an explicitly specified name.
#SessionState's advantage is that the name is automatically determined from the type ... one less thing to care about, and more amenable to refactoring.

Related

What is the best way to write appropriate validations for domain models in DDD?

I've heard about different ways to write validation for domain models, So I want to know which of them is better in the domain-driven-design.
Some people say that it's better to validate the domain model's data before initializing it (it means that validations should be run on the related DTOs).
Some people say that it's better to validate the domain model's data after initializing it (it means that validations should be run on the initialized entity or domain model).
Also, some people say that all the validations should be run inside of the entity (exactly in setters or constructors)
Indeed, I was used to writing a combination of the above validations, but now I'm not sure about that. Which of them is common and basically more sensible?
In domain driven design, what you are most likely to see are "value objects" that guarantee certain constraints are met during initialization, therefore in the constructor of the value object itself. Since values are (by convention) immutable over their lifetime, you wouldn't normally include setters in their interface.
DTOs serve a different purpose, but are mechanically similar to value objects in many ways. So you might see validation in the DTO in addition to validation within the domain model.
You don't normally have value validation in your entities. An entity is typically holds references to values (which validate themselves) or other local entities (validated elsewhere), so checking that the references are correct is in bounds (ie, check for null).

Read null as empty set in springdata-cassandra

I use spring-data-cassandra, and have entity like this:
#Table("users")
public class User {
#Column("permissions")
#CassandraType(type = DataType.Name.SET, typeArguments = {DataType.Name.TEXT})
public Set<String> permissions = new HashSet<>();
}
In cassandra I have table users with field permissions of type Set. It works fine when I store some values in the set, but when I try to store empty set, it becomes null when I read such entity from the repository.
Is there a way to force spring-data-cassandra to change null to empty HashSet? Or can I somehow add custom reader for this specific property of the entity?
TL;DR;
That's Cassandra's default behavior to return null for empty Collection and Map-typed columns.
Further Read
Cassandra returns null values for lists, sets, and maps, which do not contain any items. This is especially unfortunate when using classes with pre-initialized fields as seen in your question. There's an open ticket (DATACASS-266 - Loading empty collection-typed properties overwrites pre-initialized fields) in the issue tracker - as of now, without comments or votes.
We're not exactly sure whether it's a good idea to skip setting properties or apply some sort of defaulting when dealing with empty (null) collections as this raises follow-up questions what to do when:
Creating an instance through constructor creation: A value is required in such case. For property access, we could omit to set the property, for constructor creation we must provide a value.
The pre-initialized collection contains items but the one received from Cassandra is null.
We assume, the change would be applied, what will happen with already existing code that assumes empty collections default to null.
A possibility to address this behavior could be configuration on MappingCassandraConverter or an extension point to override so users can apply their own empty collection behavior.
I've been trying to eliminate the null collections in my model objects as well, and while it may not be possible to do that at the Spring Data level currently (version 2.1.x), there are some options you can consider:
Use property access for the field in question (i.e. use the annotation #AccessType(PROPERTY)), and in the setter method, set the field to an empty collection when the argument is null.
Define a compatible (see below) constructor that sets the field to an empty collection when a null is provided (and if the model is mutable, you may still want to provide the setter as above).
There are some caveats to ensure Spring Data Cassandra uses the desired constructor (e.g. don't provide a no argument constructor), so it's critical to review the "Object Mapping Fundamentals" section of the reference guide (https://docs.spring.io/spring-data/cassandra/docs/current/reference/html/#mapping.fundamentals).
Among the recommendations in that reference guide (as of version 2.1 at least) is to use an all argument constructor and make model objects immutable, which would work well with the constructor-based approach to handling nulls. Though it does mean writing and maintaining the constructor to handle the nulls rather than relying on Lombok's #AllArgsConstructor.
I have used the property access approach in one case, but not the constructor approach. However I do intend go the constructor route when adding new or model classes (I'm a fan of immutable objects, and will explore that route even without any collection fields)
I believe Spring Data Cassandra 2.0 also added persistence lifecycle callbacks which is another possible option I suppose, but I ruled that out, mainly because the logic would not reside in the model class itself (as well as going against the recommendations from the creators of the framework)

Parse.Query("_User") vs Parse.Query("User") vs Parse.Query(Parse.User)

It seems as though
Parse.Query("_User")
is canonical, but Parse.Query("User") and Parse.Query(Parse.User) work too. Are there differences in behaviour between these? Any reason besides consistency to stick to one over the other?
Parse.User seems nicest, since it doesn't rely on a string literal, but it's not what I've seen in the docs.
Using Parse.Query(Parse.User) is the preferred method, the actual class name for the internal User/Role/Installation classes are _User/_Role/_Installation, so you can use them.
Using Parse.Query("User") will not actually query the internal User class, and will instead look for your own User class. You can try by creating a new User object using "User" as the class name, and you'll see two User classes in your Data Browser, one with the special icon and one without.

How do I represent multiple DTOs for a domain object in .NET Web API?

I'm writing a set of REST services and have come upon a problem that I'm sure has an appropriate solution/pattern that's just eluding me.
For instance /api/People/1 will return a serialized representation of PersonDto (which is a pared down representation of the Person domain object created by Entity Framework. I'm using AutoMapper to hydrate PersonDto.
However a second controller (say, /api/Classes/) is going to return different complex object, which may contain one or more Persons, however I want to represent each person in a different way than simply using an existing PersonDto (e.g. I might require more or less fields).
Do I need to define a ClassPersonDto? I'm not sure what the "proper" thing is to do here.
If the model of "person" being passed back in "Classes" is different then the "PersonDto" model, then yes, create a different model. You don't need to, but it's almost always better to keep your classes, including entities, as specific as possible.

Is there a reason why the default modelbinder doesn't bind to fields?

I'm using ASP.NET MVC3 and i'm wondering that the default modelbinder binds to public properties but not to public fields.
Normally i just define the model classes with properties but sometimes i use some predefined classes which contains some fields. And everytime i have to debug and remember that the modelbinder just don't like fields.
The question: Whats the reason behind it?
but sometimes i use some predefined classes which contains some fields
While I cannot answer your question about the exact reason why the default model binder works only with properties (my guess is that it respects better encapsulation this way and avoids modifying internal state of the object which is what fields represent) I can say that what you call predefined classes should normally be view models. You should always use view models to and from your controller actions. Those view models are classes that are specifically defined to meet the requirements of the given view.
So back to the main point: fields are supposed to be modified only from within the given class. They should not be accessed directly from the outside. They represent and hold internal state of the class. Properties on the other hand is what should be exposed to the outside world. Imagine that in the property getter/setter you had some custom logic. By modifying directly the field this custom logic would be broken and potentially bring the object into an inconsistent state.
Maybe the reason for ignoring fields is to increase performance of the binder. Instead of searching all the Fields and properties. The Model Binder search for Properties only.
Though I think the Model Binder use cache to improve performance.
DefaultModelBinder exposes a public method:
DefaultModelBinder.BindModel, and a number of protected method available for overriding. All of them listed here.
Besides the model, these method refer to properties only, not fields, like
GetModelProperties,
GetFilteredModelProperties,
GetPropertyValue,
OnXYZValidating,
OnXYZValidated,
OnXYZUpdating,
OnXYZUpdated,
GetXYZValue,
where XYZ stands for either Model, or Property/ies, or both, and so on.
As you can see there is no Fields mentioned with these names whatsoever. As Darin explained no direct changes to Model's state are tolerated by the Binder. Hence no Field in its methods.
And also, you may wish to take a look at another important class: ModelBindingContext. An instance of this class gets passed to the BindModel, and subsequently to BindSimpleModel, and BindComplexModel, depending on model type (string, int,... are considered simple, everything else is complex).
So, this context has the following properties:
ModelXYZ, and
PropertyXYZ.
In other words you have no means to reference the fields in your ViewModel unless you do not override these classes and undertake special actions to do so.
But again, beware of fighting the framework, its always easier to follow it instead.
EDIT: The ModelMetadata class holds all the data needed to bind the model. Its code however, shows no sign of fields, field names, etc. Only properties are referenced and accessed. So, even if you try to inherit and override DefaultModelBinder and ModelBinderContext, you still won't be able to access fiellds, nevermind what their access modifier is: public, private, etc.
Hope this explains most of it.

Resources