I was wondering what the best practice is for model validation when it comes to using getters and setters. Specifically, I have nullable fields in my model that, in some use cases, should not have null values when accessed. In those cases, I would like to throw an exception from the getter, but is that an accepted practice?
This could also be the case if I received a value in a setter that was not valid.
Alternatively from throwing exceptions, I'm aware of MVC attributes that you can use to decorate fields, but have not used them very much for model validation. In the "This value shouldn't be null in my getter" scenario, is there an appropriate attribute I could use?
Also, if throwing exceptions in getters and setters is accepted, is there a recommended exception to throw, i.e. ValueNotValidException (if that were real)?
If you are going to use the object as a ViewModel you can annotate it with a [NotNullValidator] given by the Microsoft's Enterprise Library, as well as a bunch of others that give extra functionality like Regex validation, ranges, IgnoreNulls, type, etc, as shown here. It is also possible using this library to create custom validators, based on this step-by-step guide, which you can use to annotate your ViewModel.
Otherwise you are left with the more traditional MVC Data Annotation Attributes, like [Required].
You should use the standard Data Validation Attributes to validate the model. If the value is required - use [Required].
http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-validation-to-the-model
if (ModelState.IsValid)
{
...
}
Less code maintain and improved readability.
Related
Coming from a Rails background, I don’t really understand what transient means in Grails. I read this, http://www.grails.org/doc/1.3.7/ref/Domain%20Classes/transients.html
So as it says
"...In this case it doesn't make sense to persist this property..."
The guide is referring to String getUpperCaseName() { name.toUpperCase() }
I understand that String name will be picked up when trying to save to the database but why will grails bother with a getter method? It is a method to start with..
The reason why it "bothers" with a method is because of bean naming conventions where properties (in Java) are based on setters and getters. The pattern for identifying a "property" (through reflection) based on these are: getXYZ() and setXYZ() where XYZ is the property name in bean format (name becomes Name and fullName becomes FullName).
The reasoning was the fact these methods are public they can be reflected upon and derive properties from, since actual properties were typically private (for many good reasons). I still recall when this came about. (I'm getting too old)
That's why. Java.
It's not a Grails thing. It's a Java thing. You can read more about the JavaBean specification if you want a deeper understanding of the technologies you are using..
I'm working on the verification of an interface formalised in the OMG's IDL, and am having problems finding a definitive answer on the semantics of getting an attribute value. In an interface, I have an entry...
interface MyInterface {
readonly attribute SomeType someName;
};
I need to know if it is acceptable for someObj.someName != someObj.someName to be true (where someObj is an instance of an object implementing MyInterface).
All I can find in OMG documentation in regards to attributes is...
(5.14) An attribute definition is logically equivalent to declaring a
pair of accessor functions; one to retrieve the value of the attribute
and one to set the value of the attribute.
...
The optional readonly keyword indicates that there is only a single
accessor function—the retrieve value function.
Ergo, I'm forced to conclude that IDL attributes need not be backed by a data member, and are free to return basically any value the interface deems appropriate. Can anyone with more experience in IDL confirm that this is indeed the case?
As we know, IDL interface always will be represented by a remote object. An attribute is no more then a syntatic sugar for getAttributeName() and setAttributeName(). Personally, i don't like to use attribute because it is hardly to understand than a simply get/set method.
CORBA also has valuetypes, object by value structure - better explaned here. They are very usefull because, different from struct, allow us inherit from other valuetypes, abstract interface or abstract valuetype. Usualy, when i'm modeling objects with alot of
get/set methods i prefer to use valuetypes instead of interfaces.
Going back to your question, the best way to understand 'attribute' is looking for C#. IIOP.NET maps 'attribute' to properties. A property simulates a public member but they are a get/set method.
Answering your question, i can't know if someObj.someName != someObj.someName will return true or false without see the someObj implementation. I will add two examples to give an ideia about what we can see.
Example 1) This implementation will always return false for the expression above:
private static i;
public string getSomeName() {
return "myName" i;
}
Example 2) This implementation bellow can return true or false, depending of concurrency or 'race condition' between clients.
public string getSomeName() {
return this.someName;
}
public setSomeName(string name) {
this.someName = name;
}
First client can try to access someObj.someName() != someObj.someName(). A second client could call setSomeName() before de second call from the first client.
It is perfectly acceptable for someObj.someName != someObj.someName to be true, oddly as it may seem.
The reason (as others alluded to) is because attributes map to real RPC functions. In the case of readonly attributes they just map to a setter, and for non-readonly attributes there's a setter and a getter implicitly created for you when the IDL gets compiled. But the important thing to know is that an IDL attribute has a dynamic, server-dictated, RPC-driven value.
IDL specifies a contract for distributed interactions which can be made at runtime between independent, decoupled entities. Almost every interaction with an IDL-based type will lead to an RPC call and any return value will be dependent on what the server decides to return.
If the attribute is, say, currentTime then you'll perhaps get the server's current clock time with each retrieval of the value. In this case, someObj.currentTime != someObj.currentTime will very likely always be true (assuming the time granularity used is smaller than the combined roundtrip time for two RPC calls).
If the attribute is instead currentBankBalance then you can still have someObj.currentBankBalance != someObj.currentBankBalance be true, because there may be other clients running elsewhere who are constantly modifying the attribute via the setter function, so you're dealing with a race condition too.
All that being said, if you take a very formal look at the IDL spec, it contains no language that actually requires that the setting/accessing of an attribute should result in an RPC call to the server. It could be served by the client-side ORB. In fact, that's something which some ORB vendors took advantage of back in the CORBA heyday. I used to work on the Orbix ORB, and we had a feature called Smart Proxies - something which would allow an application developer to overload the ORB-provided default client proxies (which would always forward all attribute calls to the server hosting the target object) with custom functionality (say, to cache the attribute values and return a local copy without incurring network or server overhead).
In summary, you need to be very clear and precise about what you are trying to verify formally. Given the dynamic and non-deterministic nature of the values they can return (and the fact that client ORBs might behave differently from each other and still remain compliant to the CORBA spec) you can only reliably expect IDL attributes to map to getters and setters that can be used to retrieve or set a value. There is simply no predictability surrounding the actual values returned.
Generally, attribute does not need to be backed by any data member on the server, although some language mapping might impose such convention.
So in general case it could happen that someObj.someName != someObj.someName. For instance attribute might be last access time.
I would like to know if it is possible, in Struts2, to map an HTML form's fields to those of an action, automatically, without getters and setters.
It is clear that by getters and setters or the ParameterAware interface and the Map, fields can be set in the action, but I just wanted to know if otherwise there was a way.
First, instead of thinking in terms of "with fields with getters and setters" you are advised to think in terms of "bean properties" here. Struts2 (and most java frameworks) think in that way, they usually don't care (and rightly so) whether those "properties" are real fields or not.
The short answer to your question is: no.
But be aware that Struts2 is very flexible - when I say "no" I mean "using the default interceptors". You could always write your own interceptor instead of the default to do that - bad idea IMO.
The interceptor that does that mapping is (basically) the parameters interceptor. From its documentation:
This interceptor gets all parameters
from ActionContext#getParameters() and
sets them on the value stack by
calling ValueStack#setValue(String, Object)
typically resulting in the values
submitted in a form request being
applied to an action in the value
stack.
And looking into ValueStack.setValue(String,Object) we read:
Attempts to set a property on a
bean in the stack with the given
expression using the default search
order.
So there you have.
ModelDriven was the correct choice :)
This is a word of warning more than a question, if you are using RIAServices with Custom ValidatorAttributes.
Here is the Senario, I was creating a custom DataAnnotation that would validate a property based on whether or not a possible series of other properties had been set, such as; if Prop1 was 100 then Prop2, Prop3, or Prop4 could not be 0 one of them had to be set. I am also using RIA Services so I created the ValidatorAttribute my .shared.cs file. After writing all the tests for the helper CannotBeZeroIf class, I began to add the attributes to the Model Class. This is of course when thing started to go very wrong. RIA Services began to throw up during the CodeGen, with a NullReferenceException.
CreateRiaClientFilesTask -> NullReferenceException
It turns out to be linked to the fact that I was using the validator's constructor to pass in the values to the class. By switching to using ObjectInitialization syntax, everything was fixed.
The Answer appears to be use ObjectInitializer syntax when dealing with RIA Services and Custom DataAnnotation Validators.
The Answer appears to be use ObjectInitializer syntax when dealing with RIA Services and Custom DataAnnotation Validators (that was easier than I thought! ;-)
I am trying to make a taglib to represent an object (to read and display at the UI). When creating an object (save method in the controller), I see the domain class and association are created by the auto assignment of parameter
def Book = new Book(params)
It also maps complex types (for eg: joda time). I wonder about the naming convention necessary to facilitate this mapping. Out of curiosity, can someone also point where in the grails source code I could see how grails handles this mapping. I'm still learning Spring and probably this would be a good exercise.
Thanks,
Babu.
AFAIK the naming conventions are rather straightforward. If there's a field params.foo and the object you are binding to has a field foo, it will bind the value, assuming the type conversion works properly. If there's a params.bar.id set with an Long value and your object has a complex property of type Bar, it will lookup this instance and inject it.
If you need more control over the binding process, you might want to use bindData.
If you are interested into the details of the binding process, have a look at Java's PropertyEditor as this is what is being used in the background. I wrote a blog post on how to create and register PropertyEditors a while ago, maybe it helps you getting started with that stuff.