program tip

if 조건문에 변수 할당, 모범 사례?

radiobox 2020. 8. 22. 08:30
반응형

if 조건문에 변수 할당, 모범 사례? [닫은]


1 년 전에 Java와 같은 고전적인 OO 언어에서 JavaScript로 옮겼습니다. 다음 코드는 Java에서 확실히 권장되지 않거나 올바르지 않습니다.

if(dayNumber = getClickedDayNumber(dayInfo))
{
    alert("day number found : " + dayNumber);
}
function getClickedDayNumber(dayInfo)
{
    dayNumber = dayInfo.indexOf("fc-day");
    if(dayNumber != -1) //substring found
    {
        //normally any calendar month consists of "40" days, so this will definitely pick up its day number.
        return parseInt(dayInfo.substring(dayNumber+6, dayNumber+8));
    }
    else return false;
}

기본적으로 방금 if 조건 문의 값에 변수를 할당하고 할당 된 값이 부울 인 것처럼 즉시 확인할 수 있다는 것을 알았습니다.

더 안전한 내기를 위해 일반적으로 코드를 두 줄로 분리하고 먼저 할당 한 다음 변수를 확인하지만 이제는 이것을 발견 했으므로 경험 많은 JavaScript 개발자의 눈에 좋은 관행인지 아닌지 궁금합니다.


나는 그것을 추천하지 않을 것입니다. 문제는 값을 비교하려고하지만 또는 =대신 단일을 사용하는 일반적인 오류처럼 보입니다 . 예를 들어 다음과 같은 경우 :=====

if (value = someFunction()) {
    ...
}

그게 의도 한 것인지, 아니면 이렇게 작성하려고했는지 알 수 없습니다.

if (value == someFunction()) {
    ...
}

실제로 할당을 수행하려면 명시 적 비교도 수행하는 것이 좋습니다.

if ((value = someFunction()) === <whatever truthy value you are expecting>) {
    ...
}

좋은 습관이 아니라는 증거는 없습니다. 예, 실수처럼 보일 수 있지만 현명한 댓글로 쉽게 해결할 수 있습니다. 예를 들어 :

if (x = processorIntensiveFunction()) { // declaration inside if intended
    alert(x);
}

이 함수가 다음과 같이 두 번째로 실행되도록 허용해야하는 이유 :

alert(processorIntensiveFunction());

첫 번째 버전이 나빠 보이기 때문에? 나는 그 논리에 동의 할 수 없습니다.


나는 그것을 여러 번했다. JavaScript 경고를 우회하기 위해 두 개의 괄호를 추가합니다.

if ((result = get_something())) { }

그것을 피해야합니다. 정말로 그것을 사용하고 싶다면 그 위에 무엇을하고 있는지에 대한 주석을 작성하십시오.


Java에서도이 작업을 수행 할 수 있습니다. 그리고 그것은 좋은 습관이 아닙니다. :)

(그리고 ===형식화 된 동등성을 위해 자바 스크립트에서 사용하십시오 . JS에 대한 Crockford의 The Good Parts 책을 읽어보십시오.)


There is one case when you do it, with while-loops.
When reading files, you usualy do like this:

void readFile(String pathToFile) {
    // Create a FileInputStream object
    FileInputStream fileIn = null;
    try {
        // Create the FileInputStream
        fileIn = new FileInputStream(pathToFile);
        // Create a variable to store the current line's text in
        String currentLine;
        // While the file has lines left, read the next line,
        // store it in the variable and do whatever is in the loop
        while((currentLine = in.readLine()) != null) {
            // Print out the current line in the console
            // (you can do whatever you want with the line. this is just an example)
            System.out.println(currentLine);
        }
    } catch(IOException e) {
        // Handle exception
    } finally {
        try {
            // Close the FileInputStream
            fileIn.close();
        } catch(IOException e) {
            // Handle exception
        }
    }
}

Look at the while-loop at line 9. There, a new line is read and stored in a variable, and then the content of the loop is ran. I know this isn't an if-statement, but I guess a while loop can be included in your question as well.

The reason to this is that when using a FileInputStream, every time you call FileInputStream.readLine(), it reads the next line in the file, so if you would have called it from the loop with just fileIn.readLine() != null without assigning the variable, instead of calling (currentLine = fileIn.readLine()) != null, and then called it from inside of the loop too, you would only get every second line.

Hope you understand, and good luck!


You can do assignments within if statements in Java as well. A good example would be reading something in and writing it out:

http://www.exampledepot.com/egs/java.io/CopyFile.html?l=new

The code:

// Copies src file to dst file.
// If the dst file does not exist, it is created
void copy(File src, File dst) throws IOException 
{
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

It's not good practice. You soon will get confused about it. It looks similiar to a common error: misuse "=" and "==" operators.

You should break it into 2 lines of codes. It not only helps to make the code clearer, but also easy to refactor in the future. Imagine that you change the IF condition? You may accidently remove the line and your variable no longer get the value assigned to it.


If you were to refer to Martin Fowlers book Refactoring improving the design of existing code ! Then there are several cases where it would be good practice eg. long complex conditionals to use a function or method call to assert your case:

"Motivation

One of the most common areas of complexity in a program lies in complex conditional logic. As you write code to test conditions and to do various things depending on various conditions, you quickly end up with a pretty long method. Length of a method is in itself a factor that makes it harder to read, but conditions increase the difficulty. The problem usually lies in the fact that the code, both in the condition checks and in the actions, tells you what happens but can easily obscure why it happens.

As with any large block of code, you can make your intention clearer by decomposing it and replacing chunks of code with a method call named after the intention of that block of code. > With conditions you can receive further benefit by doing this for the conditional part and each of the alternatives. This way you highlight the condition and make it clearly what you > are branching on. You also highlight the reason for the branching."

And yes his answer is also valid for Java implementations. It does not assign the conditional function to a variable though in the examples.


I would consider this more of an old-school C style; it is not really good practice in JavaScript so you should avoid it.


you could do something like so:

if (value = /* sic */ some_function()){
  use_value(value)
}

I came here from golang, where it's common to see something like

if (err := doSomething(); err != nil) {
    return nil, err
}

In which err is scoped to that if block only. As such, here's what I'm doing in es6, which seems pretty ugly, but doesn't make my rather strict eslint rules whinge, and achieves the same.

{
  const err = doSomething()
  if (err != null) {
    return (null, err)
  }
}

The extra braces define a new, uh, "lexical scope"? Which means I can use const, and err isn't available to the outer block.

참고URL : https://stackoverflow.com/questions/2576571/assign-variable-in-if-condition-statement-good-practice-or-not

반응형