is there a better way of initializing correctly scoped variables inside if statements - scope

I'm curious to know if there is there a prettier way of correctly scoping objects that are initialised inside of if statements
say you have the following script:
if (x){
create object_A
}
print(object_A)
the above will fail because object A is out of scope for the print so the obvious thing to do is initialise a null variable before the if statement like this:
variable_to_reference_object_A = null
if (x){
variable_to_reference_object_A = create object_A
}
print(variable_to_reference_object_A)
This just always makes me feel like a silly billy because I'm basically saying is:
variable_to_reference_object_A = i haven't a clue because i haven't created it yet
very curious to see what you guys have to say about this, as id love to know if I'm completely doing things wrong (and possibly why it seems to show up in almost all languages). TIA

Related

How to define and call a function in Jenkinsfile?

I've seen a bunch of questions related to this subject, but none of them offers anything that would be an acceptable solution (please, no loading external Groovy scripts, no calling to sh step etc.)
The operation I need to perform is a oneliner, but pipeline limitations made it impossible to write anything useful in that unter-language...
So, here's minimal example:
#NonCPS
def encodeProperties(Map properties) {
properties.collect { k, v -> "$k=$v" }.join('|')
}
node('dockerized') {
stage('Whatever') {
properties = [foo: 123, bar: "foo"]
echo encodeProperties(properties)
}
}
Depending on whether I add or remove #NonCPS annotation, or type declaration of the argument, the error changes, but it never gives any reason for what happened. It's basically random noise, that contradicts the reality of the situation (at times it would claim that some irrelevant object doesn't have a method encodeProperties, other times it would say that it cannot find a method encodeProperties with a signature that nobody was trying to call it with (like two arguments instead of one) and so on.
From reading the documentation, which is of disastrous quality, I sort of understood that maybe functions in general aren't serializable, and that is why you need to explain this explicitly to the Groovy interpreter... I'm sorry, this makes no sense, but this is roughly what documentation says.
Obviously, trying to use collect inside stage creates a load of new errors... Which are, at least understandable in that the author confesses that their version of Groovy doesn't implement most of the Groovy standard...
It's just a typo. You defined encodeProperties but called encodeProprties.

Putting a method with arguments into a variable, in JavaScript

Sometimes I have difficulty in understanding the logic behind JavaScript and this is one example of something I often see. Here is a simple function that will be passed to a timer:
function myCounter() {
//do something...
}
You can just pass it like this:
setInterval(myCounter, 1000);
But, often we need to have the means to stop it so we assign it to a variable:
var t = setInterval(myCounter, 1000);
This allows it to be cleared later like this:
clearInterval(t);
I use this all the time but it bothers me that I don't understand exactly what I am putting into the variable, and why typeof t returns a number. What exactly have I put in t? Can anyone explain the logic behind this?
When you assign an interval to a variable, you are actually assigning an ID. That ID is then used when you use clearInterval to select which timer to clear. The reason typeof returns a number, is because an ID is a number.
Here is a detailed explanation.
MDN is a fantastic resource for this sort of thing, I highly recommend it

How to avoid creating objects to check or get content from Maps in Java

I am implementing my own Map in Java, using a custom class I made.
I already implemented the hashCode and equals without any problem.
I just have a question more related into performance and stuff like that.
So I will check many times in my application if a specific value is inside the map, for that, for that I have to create a object and then use the methods containsKey of Map.
My question is...
Is there any other way? without being always creating the object???
I cant have all the objects in my context universe, so that isn't a way...
I know I can just point the object to 'null' after using it, but still, it's not so elegant, creating objects just to check if there is the same object inside =S
Are there any other conventions?
Thank you very much in advance!
EDIT:
Stuff typed = new Stuff(stuff1, stuff2, (char) stuff3);
if(StuffWarehouse.containsKey(typed))
{
//do stuff
}
//after this I won't want to use that object again so...
typed = null;

Naming Vars with strings

Can a variable be named with a string or character array, in any language? Basically I want something like:
Var_String = "varname"
Var_String as double
And then I could fill the double varname.
If it helps im trying to make a program that can declare variables on the fly, while running. Even if thats not possible, I am open to workarounds even if they're impractical, although I would prefer that workarounds be in VB6, C++, or PHP, because I know those languages already, but they dont have to be.
Javascript is completely capable of declaring variable names on the fly. A javascript object can be treated "associatively" as a dictionary. Observe:
var testyObject = function()
{
Awesome = "hello";
};
var myObject = new testyObject();
alert(myObject.Awesome); // creates an alert window that says hello
alert(myObject['Awesome']); // the same as above
myObject[myObject.Awesome] = "woo!"; // We just created a property on the object with the name "hello"
alert(myObject.hello); // creates an alert window that says "woo!"
I also believe you can add them to your immediate scope rather than as properties on other objects by using this["whatever you want it named"] = "woo!"; but I'm not certain, someone can correct me on that if such does not work.
You can read more about associative arrays at http://www.quirksmode.org/js/associative.html
The usual way to do something like this is called a hash. You store name/value pairs and given the name, can look up its value. You can generally define them to store any sort of object. In fact, in some languages, objects themselves are essentially hashes with a few extra properties.
You can find more information on wikipedia: http://en.wikipedia.org/wiki/Hash_table

Remove Single Metaclass Method

I've been starting to learn Groovy and am currently looking at the metaclass functionality. I have seen the examples of adding a new method, and removing all methods, but nothing about removing a single method. For example:
String.metaClass.foo = {delegate.toUpperCase()}
String.metaClass.bar = {delegate.toLowerCase()}
with the obvious side-effects. Now I have seen that you can say
String.metaClass = null
To remove all of the methods. I would expect one could say something along the lines of
String.metaClass.foo = null
to remove String.foo(), but have String.bar() remain, however this statement does not seem to have any effect. Is there a way to say method foo() should no longer be defined, without effecting bar() or any other added methods?
If you search this webpage for "remove method" it says that you should be able to remove a method using the exact syntax you've proposed above. But I tested it, and you're right, it doesn't seem to work.
A workaround is to assign a closure that throws MissingMethodException, which is what happens by default when you call a method that doesn't exist, e.g.
// Add method
String.metaClass.foo = {delegate.toUpperCase()}
// Remove method
def removeMethod = {throw new MissingMethodException()}
String.metaClass.foo = removeMethod
Admittedly, this is not the most pleasing solution.
As a followup, I posted a bug report here:
https://issues.apache.org/jira/browse/GROOVY-4189
And the documentation has been changed now
See the bug report for the reason this was never implemented
Don's answer is the best way around this

Resources