How can I insert something different than the selected item with Closure Autocompleter? - google-closure-library

I would like to use the ui.Autocomplete.Basic. I have some values and additional information to these values. I would like the additional information to be displayed, but it should not be inserted. Is this possible? How can I do so?

At a glance, there doesn't seem to be an easy way to do this. You'd have to construct the base goog.ui.AutoComplete yourself (much like the goog.ui.AutoComplete.Basic constructor does), then provide a custom implementation (subclass) of goog.ui.AutoComplete.InputHandler. Specifically, you'd want to override the selectRow function to do what you want with the row parameter. The default implementation is as follows:
...selectRow = function(row,opt_multi) {
this.setTokenText(row.toString(), opt_multi);
return false;
};
This would be quite a bit more straightforward if the goog.ui.AutoComplete.Basic constructor took an optional input handler. That might be a reasonable thing to request at http://code.google.com/p/closure-library/issues/list if this strategy works.

Related

what's the best way to use "isSomething"?

Hey guys,
I'm not having a problem, I was just wondering what's the best way of implementing isSomthing in OOP paradigm?
Take this example: we want to know if the user was temporarily (like 10 minutes) banned. Here are the two options:
Implementing isTempBanned() method in the User class. Then whenever we want to check if user is banned, we just call this method. no change to the other parts of the code is required.
Adding a isTempBanned property to the User class. Then whenever the state of user's ban changes, we update this property accordingly. Then when we need to know, we just use this property.
Can you explain Pros and Cons of each way? from these standpoints:
performance
code maintainability
clean code
readability
etc...
Keep in mind that there is no better way. I'm just asking to know when should I use the first method and when to use the second one.
Ultimately you have to use both of them!
based on Encapsulation principle , think of your example as a getter/setter scenario, to keep bugs as low as possible,
getter is User.isBanned method, setter is User.banUser method.
class User{
banned_until : Date = null
isBanned(){
if(this.banned_until){
return this.banned_until.valueOf() > new Date().valueOf();
}
return false;
}
banUser(){
this.banned_until = new Date() ///any date in future ....
}
}
isSomthing is usually used for boolean. no matter what data type you use. all differences are method and property differences.
I suggest you read this:
Properties vs Methods

How are request parameters mapped into RenderingModel of magnolia?

Im using Magnolia RenderingModel in combination with Freemarker.
I have URLs like the following:
http://anyPath/context?productTypes=XXXXX&productTypes=YYYYY
my rendering model class looks like:
class MyModel extends RenderingModelImpl {
...
private String[] productTypes;
...
}
However the mentioned array contains only the first value, but not the second.
I checked the behaviour of template directives like ctx.getParameters(). This shows the same behaviour, I get only the first value returned. But if im using ctx.getParameterValues(paramName), it returns both values.
This leads me to following questions:
How would I go, if I want to lookup how the request parameters are mapped into the rendering model, or better:
How can i change the behaviour of that ?
Can anyone acknowledge, that this behaviour is wrong ?
It used to be mentioned in documentation and I believe it still is - if you use .getParameters() you get only first value for multivalue parameter. If you want to get all the values, you need to use .getParameterValues(String param).
From what I understand reasons for that were backward compatibility.
As for changing the behavior, you would need to write your own renderer (e.g. by extending default FreemarkerRenderer and override info.magnolia.rendering.renderer.AbstractRenderer.newModel(Class<T>, Node, RenderableDefinition, RenderingModel<?>) method which instantiates and populates the model class.
Alternatively you can provide fix for above set population method and submit it to Magnolia as a patch. While the .getParameters() behavior is iirc on purpose, the model param population might not be, so you have high chance of getting that changed.

Should controller methods take arguments?

Given that there is file selection widget on the view and controller need to handle event of selecting file, should I rather write controller method:
public void fileSelected(String filePath){
//process filePath
}
or
public void fileSelected(){
String filePath = view.getSelectedFilePath();
//process filePath
}
The first approach seems to introduce less coupling between C and V: C don't know what exactly data does C need while handling given event.
But it requires creating a lot of verbose methods similar to getSelectedFile on V side.
On the other hand, second approach may lead to cluttered controller methods in more complex cases than in example (much more data to pass than just filePath).
From your own experience, which approach do you prefer?
The first approach is my favourite. The only difference is I would rather use an object (like Mario suggested) to pass arguments to the method. This way method's signature will not change when you add or remove some of the arguments. Less coupling is always good :)
One more thing:
If You want to try the second solution I recommend using a ViewFactory to remove view logic from the controller.
The first approach is the way to go;
public void fileSelected(String filePath){
//process filePath
}
The Controller should not care about how the View looks like or how it's implemented. It gets much clearer for the developer as well, when creating/updating the view, to know what an action in the controller wants. Also it makes it easier for method overloading.
Though, I don't know really how String filePath = view.getSelectedFilePath(); would work. Are we talking about parsing the View code/markup?
On the other hand, second approach may lead to cluttered controller methods in more complex cases than in example (much more data to pass than just filePath).
That's when you would create a View Model class (let's say we name it MyViewModel) to store all the properties that you need to send (may it be 10 properties) and then pass that in the action: fileSelected(MyViewModel model). That's how it's intended to be used and what the *ModelBinder's in asp.net mvc are there to help you with.
I think you need to look at this from a step back.
Worry less about how it gets in, and be more concerned with validation and error raising.
Tomorrow, your requirements could change and demand that you source the information via a different architectural approach. You could refactor the setup of [inputs / an input object] into a base controller class - or one of several classes for different controller domains.
If you focus on proper validation, whether within the controller (scrubbing) or outside of it (unit tests), then you perform more thorough decoupling though duck typing.
I would go with the first approach. It's reusable and separates concerns. Even if the method of getting the filePath in the future were to change, it won't affect your method's functionality.

method name for a long method

The good style (Clean Code book) says that a method's name should describe what the method does. So for example if I have a method that verifies an address, stores it in a database, and sends an email, should the name be something such as verifyAddressAndStoreToDatabaseAndSendEmail(address);
or
verifyAddress_StoreToDatabase_SendEmail(address);
although I can divide that functionality in 3 methods, I'll still need a method to call these 3 methods. So a large method name is inevitable.
Having And named methods certainly describes what the method does, but IMO it's not very readable as names can be very very large. How would you solve it?
EDIT: Maybe I could use fluent style to decompose the method name such as:
verifyAddress(address).storeToDatabase().sendEmail();
but I need a way to ensure the order of invocation. Maybe by using the state pattern, but this causes the code to grow.
How I approach this is to make the 3 smaller methods as you mentioned and then in the higher method that calls the 3 smaller ones, I name it after the "why" I need to do those three things.
Try to define why you need to do those steps and use that as the basis of the method name.
A single method should not do 3 things. Thus divide the work into 3 methods:
verifyAddress
storeAddress
sendEmail
I'm following up on my previous comment, but I've got more here than would fit reasonably in a comment so I'm answering.
The details of the method belong in the documentation not in the name of the method (in my opinion). Think of it this way... By putting SendEmail in the name of the method, you're committing implementation details to the method name. What if a decision is made down the road to send notification via SMS or twitter or something else instead of email? Do you change the name of the method and break your API, or do you have a method name that misleads the consumers of the API? Something to consider.
If you insist on keeping the functionality of the method in its name, I'd urge you to find something more generic. Perhaps something along the lines of VerifySaveAndNotify(Address address). That way, the method name tells you what it's doing without specifying how it does it. The parameter of type Address let's you know what is being verified and saved. All of that works together to make your method name informative, flexible, and terse.
EDIT: Maybe I could use fluent style to decompose the method name such as:
verifyAddress(address).storeToDatabase().sendEmail();
but I need a way to ensure the order of invocation. Maybe by using the state pattern, but this causes the code to grow.
To ensure ordering of commands in a fluent style, each result would be an object that exposes only the functionality required by the next step. For example:
public class Verifier
{
public DataStorer VerifyAddress(string address)
{
...
return new DataStorer(address);
}
}
public class DataStorer
{
public Emailer StoreToDataBase()
{
...
return new Emailer(...);
}
}
public class Emailer
{
public void SendEmail()
{
...
}
}
This is handy if you need to create a very granular design and want to optimise your classes for reuseability, but is likely to be design overkill under most circumstances. Better probably as others have said to choose a name that represents what the whole process is supposed to represent. You could simply call it "StoreAndEmail", making an assumption that verification is something you do routinely before committing data to any destination. The alternative if you don't mind names being long is to simply describe it in full and accept that a long name is necessary. In the end, it really doesn't cost you anything, but can certainly make you code more specific in its intent.

Is it possible to create eventlisteners for string, int, bool at all?

Is it possible at all to create eventlisteners (i.e. when the value changes) for a variable of type string, int, bool, etc.?
I haven't seen this in any programming language so far, except for some Collections (like ArrayCollection in Flex), which use events to detect changes in the collection.
If not possible at all, why not? What's the reason for this? Are there any best practices to achieve the same sort of functionality? And what about extending functionality with databinding?
I don't think there is anything by default, however, you can create a custom event and raise it on the set of the method. Something like...
C# example
public delegate void MyValueChangedEventHandler(bool oldValue, bool newValue);
public event MyValueChangedEventHandler MyValueChanged;
private bool myValue;
...
public bool MyValue
{
get { return myValue; }
set
{
if (myValue != value)
{
var old = myValue;
myValue = value;
MyValueChanged(old, myValue);
}
}
}
I guess this sort of functionality is not added in any framework/runtime since it would create a big overhead (think on how many times you modify a variable holding a primitive type within the average application) while being not used under normal circunstances.
Anyway, in .NET at least (and I guess that in other OO environments as well), you can define properties, which are accessed as normal variables but can have associated code that reacts when its value is read or modified.
It is possible if you wrap your variables in getters and setters and fire the event when the setter is called.
How about using setter methods and having them register events when changing the value of the variable?
In general, no. The reason is that primitive types are simply bits and bytes stored in some memory location: changing the data in that memory location does just that, and nothing else. Firing events would require calling some methods/functions. So the functionality can be achieved by wrapping the primitive types in some kind of wrapper objects - but of course, they're not 100 % interchangeable: for instance Java's primitive wrapper types (Integer etc.) are marked final, so it's not possible to extend them with event-firing versions to take advantage of auto(un)boxing.
Another approach is to poll the variable frequently and fire appropriate events if it has changed. This is a "dirty" approach with obvious disadvantages (performance overhead, not immediate reaction), but could regardless be useful in some situations. If you do this from another thread in Java, be sure to mark the variable volatile.
It is possible to create listeners, as some of ther others have mentioned, by making a class that fires an event whenever a property changes. This is obviously a lot less efficient than just assigning a value, but there are cases where it could be useful.
Some languages (VB6 and some others) have the ability in debug mode to stop execution when the value of a variable changes. I haven't seen this in .net, but it's liable to be in there somewhere. :-)
It seems to me that using an event to signal a simple variable change could be accomplished with if statements at each assignment, unless the value that variable is being changed externally, in which case you could use a class to handle it.

Resources