Answer the question
In order to leave comments, you need to log in
A couple of questions. Is it worth it to use functions like this? What's the best way to terminate a function?
1) Let's say there are 3 sections in the code that require the same code, consisting of 5-10 lines. Moreover, the result of executing this code is a number.
What is better, copy the same fragment to 3 places, or create a function and return a number? What if there are a lot of such functions?
2) Is it possible to complete the execution of a function with returns?
if(a == b) return print("test");
// код, если a != b
return 1;
// vs
if(a != b)
{
// действие
}
else print("test");
Answer the question
In order to leave comments, you need to log in
1) It's better to create a function. Even better is to study the architecture of the problem well.
2) return - regular way to exit the function. This is slightly better than kilometers of nested conditions.
I advise you to ask a question more specifically.
1. If you adhere to the OOP paradigm, then copying the text is in any case worthless. Especially if the result of the function does not depend on class variables. Write a static class, implement the method you need there, and call it anywhere without creating instances.
2. Also not entirely clear. In the first case, your function returns a function, in the second, nothing is returned to you, but just a set of instructions. It is logical to compare these 2 options:
public string Func(int a, int b) {
if (a == b) return "test";
return "error";
}
public string Func2(int a, int b) {
string text = (a == b) ? text = "test" : text = "eroor";
return text;
}
If you want to get "self-documenting" code, move complex and non-obvious checks into functions.
function checkUser(user) {
return (user != null && user.name != null && user.role == 'admin')
}
function checkSetupConfig(params) {
var isValid = false;
if (checkUser(params.user) || params.installationPath != null) {
isValid = true;
}
/// тут могут быть еще проверки ...
return isValid;
}
function setup(params)
{
if (checkSetupConfig(params)) {
//
}
}
var validationResult = {
isValid : fale,
errorMessage : 'User not logged in',
// errorCode : 'UE001', // лучше коды делать строками, и читабельными, но можно и 1
errorCode : 1
}
If a and b are global, then it's better to make one global function that will look at them:
and put it next to the variables. Then drag and drop other appeals to them there. You look, and a class with some meaningful properties will be assembled.
return is a good thing, but if you return a value, then it should make sense. For the sake of reducing a pair of parentheses, it is not worth inventing a return type. So that
if(a == b){
print("test");
return;
}
// код, если a != b
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question