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

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.

Related

ReSharper functionheader code formating

I'm using ReSharper with VS2015. I want to do some changes in the code formatin settings, but I don't get exactly what I want.
For example I use a function like this:
public static MyFunction(int one, string two, double three)
{
....
}
when I hit save and the line is to long the code will be formatted like this.
public static MyFunction(
int one,
string two,
double three)
{
....
}
But what I want is this.
public static MyFunction(
int one,
string two,
double three)
{
....
}
I would like to format it also like this when I call a function.
So is there a possibility to format it like the last one? Could find the correct settings in the ReSharper options.
Thanks for your help
I'd like to strongly discourage you from trying to format the code like this. There is no resharper setting that would allow this. Stay with the second option:
`public static MyFunction(
int one,
string two,
double three)
{
....
}`
This is totally fine, I see no added value when you format the code like you want to.
But if you really really really want it you can create your own Custom code inspection which is not exactly what you are looking for since you won't get your results on formatting but when invoking resharper's code inspection.

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 (?)

void example(Can you put anything in here?)

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).

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).

KeyTyped key not showing key

I am trying to convert from processing to processingjs and have something I just can't understand.
In processing the following code returns whichever letter you type in, though in processingjs it just comes back with the keycode value but I need the letter not the code.
String name="";
void setup(){
size(200,200);
}
void draw(){
}
void keyPressed() {
if(key==ENTER) {
name="";
}
else {
name+=key;
println(name);
}
}
After hours of searching and the above answer I've found the answer here peepproject.com/forums/thread/266/view more eloquently than I. Basically the solution is to convert the int to a char() before constructing a String and putting it into an array.
Instead of name += key, try name += key.toString().
Processing's println automatically does type conversion for you, so the char value of PApplet.key gets printed as a letter. JavaScript string concatenation works differently; the integer value of PApplet.key will be appended to the string as an integer and will not automatically be converted to a string. You have to do it manually.
You need to use the char conversion function in Processing and Processing.js:
http://processingjs.org/reference/char_/
The reason why it's displaying as a number is this line:
char x = 97; //supposed to be an 'a'
Does a cast in Java (may require char x = (char)97).
However in processing.js it is executed as:
var x = 97;
Since javascript has dynamic typing. You therefore need to explicitly force type casts such as from int->char.

Resources