I was following a tutorial today that had me scratching my head for an hour. Consider:
public class MyClass {
public int getTotal() {
amount = 100;
return amount;
}
}
and an excerpt from a JSP:
<p>Total: ${objectOfTypeMyClass.total}</p> //object instantiated elsewhere
Nowhere in the code was an instance variable named "total" ever declared or used. The only reference to the word "total" in the whole project (other than in the JSP) was the method getTotal().
So after some desperate last-ditch experimentation, it appears that Expression Language evaluates ${someObject.var} as "call the getVar() method of the someObject object.
I worked with this long tutorial for over a week thinking that ${someObject.var} was saying "directly fetch the saved instance variable "var" from someObject.
Did I have it wrong the whole time and is my observation correct that in order to reference any instance variable using EL, you have to provide a corresponding getter method named getVarname() where "Varname" is the name of the instance variable?
Also, EL seems to be case-insensitive in this regard. In my example above, "total" in ${objectOfTypeMyClass.total} is all lowercase where the method getTotal() has a capital "T".
And while we're at it, why don't we need to instantiate the variable "total"? I guess EL isn't actually referencing an instance variable...just a getter method?
What gives?
Did I have it wrong the whole time and is my observation correct that in order to reference any instance variable using EL, you have to provide a corresponding getter method named getVarname() where "Varname" is the name of the instance variable?
That's correct. EL adheres the JavaBeans specification as described in the EL specification.
Also, EL seems to be case-insensitive in this regard. In my example above, "total" in ${objectOfTypeMyClass.total} is all lowercase where the method getTotal() has a capital "T".
No, it's certainly not case insensitive. It's specified behaviour. ${bean.Total} would not have worked.
And while we're at it, why don't we need to instantiate the variable "total"? I guess EL isn't actually referencing an instance variable...just a getter method?
It's because it's supposed to adhere the Javabean specification.
All with all, read the both specifications and everything will be clear :)
See also:
What are the advantages of Javabeans?
The . in objectOfTypeMyClass.total is the JSTL EL Dot Operator. It can do a few different things. Including:
map.key accessed a value from map stored under key. or
object.property accesses property from object using "JavaBeans" conventions.
This should work:
public class MyClass {
private int total = 100;
public int getTotal() {
return total;
}
...
}
Related
I tried doing this in a class declaration.
public var Thing : Thing = Thing()
It says,
Variable used within its own initial value
If I remove the assignment then it gives.
Thing used within its own type
So no luck. Is it possible to use the same name for the property as the type? Its possible in C# :) At present I have lower cased the property name.
If you conform to the naming convention and declare variable names with a leading lowercase letter, it's possible.
public var thing : Thing = Thing()
If the following doesn't work:
public var thing: Thing = Thing()
There error is likely in the init method of Thing
While reading up on the new features introduced in Java 8, I came across the concept of Predicates. I noticed that most of the examples provided on the internet and in books use static functions to create predicates.
Consider the following Apple class for example :
public class Apple {
private String color;
private int weight;
private static final int SMALL_APPLE_MAX_WEIGHT = 150;
public Apple(String color, int weight) {
this.color = color;
this.weight = weight;
}
public static boolean isGreenApple(Apple apple) {
return null!=apple && null!=apple.getColor() && "green".equals(apple.getColor());
}
public boolean isBigApple() {
return this.getWeight() > SMALL_APPLE_MAX_WEIGHT;
}
}
I can now create a new predicate as follows :
Predicate<Apple> isGreenApple = Apple::isGreenApple;
Predicate<Apple> isBigApple = Apple::isBigApple;
As shown above, I can create a predicate using both a static as well as an instance method. Which approach is the preferred approach then and why?
For a method reference, there is no difference between an instance method A.foo() and a static method foo(A), in fact, the compiler will reject a method reference as ambiguous if both exist.
So the decision whether to use an instance method or a static method does not depend on the question whether you want to create a function via method reference for it.
Rather, you have to apply the same considerations us usual. Should the method be overridable, it has to be an instance method, otherwise, if it represents a fixed algorithm, you may consider a static method, but of course, a final method would do as well.
static methods are obviously unavoidable when you are not the maintainer of the class whose instance you want to process, in other words, when the containing class has to be different than the class of the instance. But even if the class is the same but you feel that it could be placed in another (utility) class as well, declaring it as static might be the better choice.
This holds especially when there are more than one parameter and the first one isn’t special to the operation, e.g. max(Foo,Foo) should be a static method rather than an instance method max(Foo) on Foo.
But in the end there are different programming styles out there and the answer is that method references do not mandate a particular programming style.
Regarding why there are so many examples using static methods; well I don’t know enough examples to decide whether your observation is right or just a subjective view. But maybe some tutorial writers are themselves not aware about the possibility to refer to an instance method as a function taking the method receiver as first argument.
I think, there are examples, like
Predicate<String> empty=String::isEmpty;
Predicate<CharSequence> isHello="hello"::contentEquals;
which are worth to be shown in tutorials to emphasize that you are not required to create methods specially intended to be used as method references, but that in fact there are a lot of already existing methods, static and non-static, to be directly usable with method references.
What I am more interested in knowing is why are all examples on predicates shown using static methods?
The reference appears on the Class as no additional argument is required.
Any specific reason for not using instance methods?
For non-static methods that would make sense. In the case of
Predicate<Apple> isBigApple = Apple::isBigApple;
Predicate needs a argument so it takes this. An example of a non-method call would be something like
List<Apple> bigApples = new ArrayList<>();
apples.stream().filter(Apple::isBigApple).forEach(bigApple::add);
Grails has a bug with regards to databinding in that it throws a cast exception when you're dealing with bad numerical input. JIRA: http://jira.grails.org/browse/GRAILS-6766
To fix this I've written the following code to manually handle the numerical input on the POGO class Foo located in src/groovy
void setPrice(String priceStr)
{
this.priceString = priceStr
// Remove $ and ,
priceStr = priceStr.trim().replaceAll(java.util.regex.Matcher.quoteReplacement('$'),'').replaceAll(',','')
if (!priceStr.isDouble()) {
errors.reject(
'trade.price.invalidformat',
[priceString] as Object[],
'Price:[{0}] is an invalid price.')
errors.rejectValue(
'price',
'trade.price.invalidformat')
} else {
this.price = priceStr.toDouble();
}
}
The following throws a null reference exception on the errors.reject() line.
foo.price = "asdf" // throws null reference on errors.reject()
foo.validate()
However, I can say:
foo.validate()
foo.price = "asdf" // no Null exception
foo.hasErrors() // false
foo.validate()
foo.hasErrors() // true
Where does errors come from when validate() is called?
Is there a way to add the errors property without calling validate() first?
I can't exactly tell you why, but you need to call getErrors() explicitly instead of accessing it as errors like a property. For some reason, Groovy isn't calling the method for it. So change the reject lines in setPrice() to
getErrors().reject(
'trade.price.invalidformat',
[priceString] as Object[],
'Price:[{0}] is an invalid price.')
getErrors().rejectValue(
'price',
'trade.price.invalidformat')
That is the easiest way to make sure the Errors object exists in your method. You can check out the code that adds the validation related methods to your domain class.
The AST transformation handling #Validateable augments the class with, among other things
a field named errors
public methods getErrors, setErrors, clearErrors and hasErrors
The getErrors method lazily sets the errors field if it hasn't yet been set. So it looks like what's happening is that accesses to errors within the same class are treated as field accesses rather than Java Bean property accesses, and bypassing the lazy initialization.
So the fix appears to be to use getErrors() instead of just errors.
The errors are add to your validateable classes (domain classes and classes that have the annotation #Validateable) dinamically.
Allowing the developer to set a String instead of a number doesn't seem a good way to go. Also, your validation will work only for that particular class.
I think that a better approach is to register a custom property editor for numbers. Here's a example with dates, that enable the transform of String (comming from the form) to Date with a format like dd/MM/yyyy. The idea is the same, as you will enforce that your number is parseable (eg. Integer.parseInt() will throw exception).
In your domain class, use the numeric type instead of String, so by code developers will not be allowed to store not number values.
I've been practicing some Ruby meta-programming recently, and was wondering about assigning anonymous classes to constants.
In Ruby, it is possible to create an anonymous class as follows:
anonymous_class = Class.new # => #<Class:0x007f9c5afb21d0>
New instances of this class can be created:
an_instance = anonymous_class.new # => #<#<Class:0x007f9c5afb21d0>:0x007f9c5afb0330>
Now, when the anonymous class is assigned to a constant, the class now has a proper name:
Foo = anonymous_class # => Foo
And the previously created instance is now also an instance of that class:
an_instance # => #<Foo:0x007f9c5afb0330>
My question: Is there a hook method for the moment when an anonymous class is assigned to a constant?
There are many hooks methods in Ruby, but I couldn't find this one.
Let's take a look at how constant assignment works internally. The code that follows is extracted from a source tarball of ruby-1.9.3-p0. First we look at the definition of the VM instruction setconstant (which is used to assign constants):
# /insns.def, line 239
DEFINE_INSN
setconstant
(ID id)
(VALUE val, VALUE cbase)
()
{
vm_check_if_namespace(cbase);
rb_const_set(cbase, id, val);
INC_VM_STATE_VERSION();
}
No chance to place a hook in vm_check_if_namespace or INC_VM_STATE_VERSION here. So we look at rb_const_set (variable.c:1886), the function that is called everytime a constant is assigned:
# /variable.c, line 1886
void
rb_const_set(VALUE klass, ID id, VALUE val)
{
rb_const_entry_t *ce;
VALUE visibility = CONST_PUBLIC;
# ...
check_before_mod_set(klass, id, val, "constant");
if (!RCLASS_CONST_TBL(klass)) {
RCLASS_CONST_TBL(klass) = st_init_numtable();
}
else {
# [snip], won't be called on first assignment
}
rb_vm_change_state();
ce = ALLOC(rb_const_entry_t);
ce->flag = (rb_const_flag_t)visibility;
ce->value = val;
st_insert(RCLASS_CONST_TBL(klass), (st_data_t)id, (st_data_t)ce);
}
I removed all the code that was not even called the first time a constant was assigned inside a module. I then looked into all the functions called by this one and didn't find a single point where we could place a hook from Ruby code. This means the hard truth is, unless I missed something, that there is no way to hook a constant assignment (at least in MRI).
Update
To clarify: The anonymous class does not magically get a new name as soon as it is assigned (as noted correctly in Andrew's answer). Rather, the constant name along with the object ID of the class is stored in Ruby's internal constant lookup table. If, after that, the name of the class is requested, it can now be resolved to a proper name (and not just Class:0xXXXXXXXX...).
So the best you can do to react to this assignment is to check the name of the class in a loop of a background worker thread until it is non-nil (which is a huge waste of resources, IMHO).
Anonymous classes don't actually get their name when they're assigned to a constant. They actually get it when they're next asked what their name is.
I'll try to find a reference for this. Edit: Can't find one, sorry.
Extract Method (a refactoring from Fowler's book) works great if your method doesn't assign any values. If it assigns one value, that becomes the return value of the extracted method. What if it assigns two values?
Some C# code to illustrate:
private void someBigFunction() {
doSomething();
doSomethingElse();
// start extraction here
string first = Database.Select(...);
// ...
// next is dependent on the value of "first"
int next = Database.Select(...);
// ...
// stop extraction here
doMoreUselessStuff();
}
The exact code or values are not important here. The point is extracting this method. (The two values are linked, so it makes sense to have them in the same method -- and not to make two methods.)
Possible answers to this question would be "return both in an array," "return them both in a pair-like data structure," or "use out parameters (pass by reference)" -- but I'm looking for something cleaner. (The actual code is in Delphi, not C#)
Perhaps Sprout Class is what you're looking for. Make the two members instance variables of a new class and extract this method into that class, assigning the instance variables and providing getters for the caller. Or, of course, you could convert the local variables to be instance variables of the original class. That conversion frequently makes Extract Method easier, but you wind up with what is arguably an excess of instance variables. With Sprout class, you have a class whose only purpose is to retrieve and provide those values, so there's no question that they deserve to be instance variables in it.