void example(Can you put anything in here?) - void

As it says in the title. Can you put anything in the part with () in the void thing
void game(Can i put anything here?) {
}

void game(Can i put anything here?) {
}
is a function definition.
void means that the function does not return a value. Remember in math class when you had functions like sin(x) and they returned a value (like sin(pi) = 0, the 0 is what the function sin computed and returned to you).
In your case, the void part means no value gets returned (the functions execute and then just finish. The (Can i put anything here?) part of the function call is where the arguments (or parameters) go. You cannot put anything there, you have to put the arguments to the function there, such as int i:
void game(int i) {
}
now you can call the function and pass it an integer game(5) and inside the function you can gain access to the value 5 via the variable i. The function can perform the tasks you tell it to (in the case of sin it would take i and compute and return the sine value).

Related

a "return" vs "System.out.println"?

I am a beginner in learning Java,
I Know this method is working,
public static double max(double num1, double num2) {
return Math.max(num1, num2);
}
I am asking why not using directly something like that:
public static double max(double num1, double num2) {
System.out.println (Math.max(num1, num2));
It is not working as far as I know
How could we know and predetermin that the method we write would need a "return" or
"System.out.println" ?
In fact, the second piece of code won't run at all. This is because the function isn't returning anything despite the fact that in the function header it says it will return a double. It should actually be this (note the void):
public static void max(double num1, double num2) {
System.out.println (Math.max(num1, num2));
}
Besides that, the point of the first one is that it only does what it says it does. It returns the max of the two numbers; nothing else. The second one is called max but for some reason it writes to the console. With the first one, you can do anything you like with the max value. With the second, you can only print it to console.

refactor lambda to be called by another class: while keeping caller's code to be still short

How to professionally refactor lambda function to be called by another class WHILE make caller's code still short?
My attempt shows that for changing a lambda function to a normal function, I have to capture variables manually, thus the new normal function requires more parameters (to compensate automatic capture ability).
As a result, the new function is more tedious to use, and can cause more bug.
Example
Here is my original code, using lambda.
void Turret::registerFullversion(int gameObjectId, PhysicObject* phyO){//utility
//.... something a bit complex .......
}
void Turret::createTurret(int typeOfTurret){
int gameObjectId=createNewGameObjectId();
auto registerEasy=[&]( PhysicObject* phyO){
//^ served as a short hand version of "registerFullversion"
// 1 parameter is more comfortable than 2
registerFullversion(gameObjectId,phyO);
}
switch(typeOfTurret){
case 1:{ //this part will be moved into another class (###)
PhysicObject* phy=PhysicSystem::createNewPhysicObject();
registerEasy( phy);
//^ equivalent to "registerFullversion(gameObjectId,phy)"
// but it is very concise (1 parameter), nice!
};break;
//..... a lot of case ....
}
//... do something about "gameObjectId"
}
I want to move a part of function (###) from Turret into another class (TurretLaser).
It works, but the result is that caller have to capture gameObjectId and pass it manually :-
void Turret::createTurret(int typeOfTurret){
int gameObjectId=createNewGameObjectId();
switch(typeOfTurret){
case 1:{ //this part have to be move into another class
TurretLaser::createTurret(gameObjectId)
};break;
//..... a lot of case ....
}
}
void TurretLaser::createTurret(int gameObjectId){ //(###)
PhysicObject* phy=PhysicSystem::createNewPhysicObject();
Turret:registerFullversion(gameObjectId,phy);
//^ it is not as short as before (now = 2 parameters)
}
Note
In real case, all above functions are non-static function, and all functions are far more complex.
Performance is the first priority. Thus, std::bind and std::function are not allowed.
This question asks about how to omit the captured parameters rather than "Please fix my code", so a valid solution can also just provide a new example with its own fix instead of showing modification of my code.
My attempt
I will manually capture the related data (gameObjectId) and cache it (using a new variable CACHE_gameObjectId):-
void Turret::registerEasy(PhysicObject* physicO){
registerFullversion(CACHE_gameObjectId,physicO);
//int "CACHE_gameObjectId" is a new field of "Turret"
};
void Turret::createTurret(int typeOfTurret){
int gameObjectId=createNewGameObjectId();
Turret::CACHE_gameObjectId=gameObjectId;
switch(typeOfTurret){
case 1:{ //this part have to be move into another class
TurretLaser::createTurret(gameObjectId)
};break;
//..... a lot of case ....
}
}
void TurretLaser::createTurret(int gameObjectId){ //(###)
PhysicObject* phy=PhysicSystem::createNewPhysicObject();
Turret:registerEasy(phy);
//^ short as before, nice
}
Disadvantage of my solution: dirty, look dangerous (not so automatic, thus can cause more bug) , seem to be less thread-safe (?)

Convert: "preg_replace" -> "preg_replace_callback"

I'm trying to update my code but I'm stuck at this codeline.
How do I proceed to convert this to preg_replace_callback?
$buffer = preg_replace("#§([a-z0-9-_]+)\.?([a-z0-9-_]+)?#ie","\$templ->\\1(\\2)",$buffer);
Here is the process of converting preg_replace (with the e modifier) to preg_replace_callback. You create a function that will act on all of the matches that it finds. Normally this is pretty simple, however with your case it is a little more complex as the function returns the value of an object. To accommodate this, you can use an anonymous function (a function without a name) and attach the USE keyword with your object to it. This can be done inline, however for the sake of clarity, I have made it its own variable.
Take a look at this portion of the complete code below:
$callback_function = function($m) use ($templ) {
I created a variable named callback_function that will be used in the preg_replace_callback function. This function will be fed each match as the variable $m automatically. So within the function you can use $m[1] and $m[2] to access the parts of the expression that it matched. Also note that I've attached the $templ variable with the USE keyword so that $templ will be available within the function.
Hopefully that makes sense. Anyway, here is the complete code:
<?php
// SET THE TEXT OF THE BUFFER STRING
$buffer = 'There are a bunch of §guns.roses growing along the side of the §guns.road.';
// THIS IS JUST A SAMPLE CLASS SINCE I DO NOT KNOW WHAT YOUR CLASS REALLY LOOKS LIKE
class Test {
// FUNCTION NAMED 'guns' WITH A SPACE FOR A PARAMETER
public function guns($info) {
return '<b>BLUE '.strtoupper($info).'</b>';
}
}
// INSTANTIATE A NEW 'Test' CLASS
$templ = new Test();
// THIS IS THE FUNCTION THAT YOUR CALLBACK WILL USE
// NOTICE THAT IT IS AN ANONYMOUS FUNCTION (THERE IS NO FUNCTION NAME)
$callback_function = function($m) use ($templ) {
return $templ->$m[1]($m[2]);
};
// THIS USES PREG_REPLACE_CALLBACK TO SUBSTITUTE OUT THE MATCHED TEXT WITH THE CALLBACK FUNCTION
$buffer = preg_replace_callback('/§([a-z0-9-_]+)\.?([a-z0-9-_]+)?/i', $callback_function, $buffer);
// PRINT OUT THE FINAL VERSION OF THE STRING
print $buffer;
This outputs the following:
There are a bunch of <b>BLUE ROSES</b> growing along the side of the <b>BLUE ROAD</b>.

Do I need to use std::move again?

For below code, I want to use the std::move to improve the efficiency. I have two functions, the first function uses std::move, and the second function just calls the first function. So, do I need to use std::move again in the function "vector convertToString()"? Why and why not? Thank you.
class Entity_PortBreakMeasure
{
public:
Entity_PortBreakMeasure(){}
int portfolioId;
string portfolioName;
int businessDate;
string assetType;
string currency;
string country;
string industry;
string indicator;
double value;
inline double operator()()
{
return value;
}
static vector<string> convertToString(Entity_PortBreakMeasure& pbm)
{
//PORTFOLIOID INDUSTRY CURRENCY COUNTRY BUSINESSDATE ASSETTYPE INDICATOR VALUE PORTFOLIONAME
vector<string> result;
result.push_back(boost::lexical_cast<string>(pbm.portfolioId));
result.push_back(pbm.industry);
result.push_back(pbm.currency);
result.push_back(pbm.country);
result.push_back(Date(pbm.businessDate).ToString());
result.push_back(pbm.assetType);
result.push_back(pbm.indicator);
result.push_back(boost::lexical_cast<string>(pbm.value));
result.push_back(pbm.portfolioName);
return std::move(result);
}
vector<string> convertToString()
{
return convertToString(*this);
}
move() shouldn't be used for either of these functions.
In the first function, you're returning a local variable. Without move(), most (all?) compilers will perform NRVO and you won't get a copy or a move -- the returned variable will be constructed directly in the returned value for the caller. Even if the compiler is, for some reason, unable to do NRVO, local variables become r-values when used as the argument to a return, so you'll get a move anyway. Using move() here serves only to inhibit NRVO and force the compiler to do a move (or a copy in the event that the move isn't viable).
In the second function, you're returning an r-value already, since the first function returns by value. move() here doesn't add anything but complexity (which might possibly confuse an optimizer into producing suboptimal code or failing to do copy elision).

What are nested functions? What are they for?

I've never used nested functions, but have seen references to them in several languages (as well as nested classes, which I assume are related).
What is a nested function?
Why?!?
What can you do with a nested function that you cannot do any other way?
What can you do with a nested function this is difficult or inelegant without nested functions?
I assume nested functions are simply an artifact of treating everything as an object, and if objects can contain other objects then it follows.
Do nested functions have scope (in general, I suppose languages differ on this) just as variables inside a function have scope?
Please add the language you are referencing if you're not certain that your answer is language agnostic.
-Adam
One popular use of nested functions is closures. In a lexically scoped language with first-class functions it's possible to use functions to store data. A simple example in Scheme is a counter:
(define (make-counter)
(let ((count 0)) ; used to store the count
(define (counter) ; this is the counter we're creating
(set! count (+ count 1)) ; increment the count
count) ; return the new count
counter)) ; return the new counter function
(define mycounter (make-counter)) ; create a counter called mycounter
(mycounter) ; returns 1
(mycounter) ; returns 2
In this example, we nest the function counter inside the function make-counter, and by returning this internal function we are able to access the data available to counter when it was defined. This information is private to this instance of mycounter - if we were to create another counter, it would use a different spot to store the internal count. Continuing from the previous example:
(define mycounter2 (make-counter))
(mycounter2) ; returns 1
(mycounter) ; returns 3
It's useful for recursion when there is only 1 method that will ever call it
string[] GetFiles(string path)
{
void NestedGetFiles(string path, List<string> result)
{
result.AddRange( files in the current path);
foreach(string subPath in FoldersInTheCurrentPath)
NestedGetFiles(subPath, result);
}
List<string> result = new List<string>();
NestedGetFiles(path, result);
return result.ToArray();
}
The above code is completely made up but is based on C# to give the idea of what I mean. The only method that can call NestedGetFiles is the GetFiles method.
Nested functions allow you to encapsulate code that is only relevant to the inner workings of one function within that function, while still allowing you to separate that code out for readability or generalization. In some implementations, they also allow access to outer scope. In D:
int doStuff() {
int result;
void cleanUpReturn() {
myResource1.release();
myResource2.release();
return result * 2 + 1;
}
auto myResource1 = getSomeResource();
auto myResource2 = getSomeOtherResource();
if(someCondition) {
return cleanUpReturn();
} else {
doSomeOtherStuff();
return cleanUpReturn();
}
}
Of course, in this case this could also be handled with RAII, but it's just a simple example.
A nested function is simply a function defined within the body of another function. Why? About the only reason I could think of off the top of my head is a helper or utility function.
This is a contrived example but bear with me. Let's say you had a function that had to act on the results two queries and fill an object with values from one of the queries. You could do something like the following.
function process(qryResult q1, qryResult q2) {
object o;
if (q1.someprop == "useme") {
o.prop1 = q1.prop1;
o.prop2 = q1.prop2;
o.prop3 = q1.prop3;
} else if (q2.someprop == "useme") {
o.prop1 = q2.prop1;
o.prop2 = q2.prop2;
o.prop3 = q2.prop3;
}
return o;
}
If you had 20 properties, you're duplicating the code to set the object over and over leading to a huge function. You could add a simple nested function to do the copy of the properties from the query to the object. Like this:
function process(qryResult q1, qryResult q2) {
object o;
if (q1.someprop == "useme") {
fillObject(o,q1);
} else if (q2.someprop == "useme") {
fillObject(o,q2);
}
return o;
function fillObject(object o, qryResult q) {
o.prop1 = q.prop1;
o.prop2 = q.prop2;
o.prop3 = q.prop3;
}
}
It keeps things a little cleaner. Does it have to be a nested function? No, but you may want to do it this way if the process function is the only one that would have to do this copy.
(C#) :
I use that to simplify the Object Browser view, and to structure my classes better.
As class Wheel nested in Truck class.
Don't forget this detail :
"Nested types can access private and protected members of the containing type, including any inherited private or protected members."
They can also be useful if you need to pass a function to another function as an argument. They can also be useful for making factory functions for factory functions (in Python):
>>> def GetIntMaker(x):
... def GetInt():
... return x
... return GetInt
...
>>> GetInt = GetIntMaker(1)
>>> GetInt()
1
A nested function is just a function inside another function.
Yes, it is a result of everything being an object. Since you can have variables only visible in the function's scope and variables can point to functions you can have a function that is referenced by a local variable.
I don't think there is anything that you can do with a nested function that you absolutely couldn't do without. A lot of the times it makes sense, though. Namely, whenever a function is a "sub-function" of some other function.
A common use-case for me is when a function performs a lot of complicated logic but what the function computes/returns is easy to abstract for all the cases dictated by the logic.

Resources