Мне не нравится этот …, этот обман языка?

Вам нужно добавить свой ярлык в AjaxRequestTarget, чтобы отразить сделанные вами изменения:

[...]
errorMessage.setVisible(true);
target.add(errorMessage);
return;
13
задан mpeterson 8 May 2009 в 14:52
поделиться

15 ответов

You're taking advantage of a language feature known as short circuiting. This is not cheating the language but in fact using a feature exactly how it was designed to be used.

106
ответ дан 1 December 2019 в 17:10
поделиться

A bit off topic but if you rand the same example in vb.net like this

dim someString as string
someString = MagicFunction()
if not string.IsNullOrEmpty(someString) and someString.Length > 3 then
    ' normal string, do whatever
else
    ' do someting else
end if

this would go bang on a null (nothing) string but in VB.Net you code it as follows do do the same in C#

dim someString as string
someString = MagicFunction()
if not string.IsNullOrEmpty(someString) andalso someString.Length > 3 then
    ' normal string, do whatever
else
    ' do someting else
end if

adding the andalso make it behave the same way, also it reads better. as someone who does both vb and c' development the second vb one show that the login is slighty different and therefor easyer to explain to someone that there is a differeance etc.

Drux

0
ответ дан 1 December 2019 в 17:10
поделиться

Написание кода стоило компании много долларов. Но поддержание этого стоит дороже!

Итак, я согласен с вашей точкой зрения: есть вероятность, что эта строка кода не будет сразу понятна парню, которому придется прочитать ее и исправить через 2 года.

Конечно, его попросят исправить критическую производственную ошибку. Он будет искать здесь и там и может этого не заметить.

Мы всегда должны писать код для следующего парня, и он может быть менее умным, чем мы. Для меня это единственное, что нужно помнить.

Это означает, что мы используем очевидные языковые особенности и избегаем других.

Всего наилучшего, Сильвен.

0
ответ дан 1 December 2019 в 17:10
поделиться

В большинстве случаев "правильное" действие - это короткое замыкание. Это приводит к более сжатому коду с меньшим количеством движущихся частей. Что обычно означает более простое обслуживание. Это особенно верно в C и C ++.

Я бы серьезно пересмотрел вопрос о найме кого-то, кто не знаком (и не знает, как использовать) операции короткого замыкания.

1
ответ дан 1 December 2019 в 17:10
поделиться

Я не думаю, что это нечто иное, чем что-то вроде этого:

INT* pNumber = GetAddressOfNumber();

if ((pNUmber != NULL) && (*pNumber > 0))
{
  // valid number, do whatever
}
else
{
  // On a null pointer, it drops to here, because (pNumber != NULL) fails
  // However, (*pNumber > 0), if used by itself, would throw and exception when dereferencing NULL
}

Это просто использование преимущества языка. Я думаю, что этот вид идиомы широко используется с тех пор, как C начал таким образом выполнять логические выражения (или какой-либо другой язык сделал это первым).

0
ответ дан 1 December 2019 в 17:10
поделиться

Если это был код на c, который вы скомпилировали в сборку, не только сокращает правильное поведение, но и быстрее . В машинном языке части оператора if вычисляются одна за другой. Без короткого замыкания происходит медленнее.

0
ответ дан 1 December 2019 в 17:10
поделиться

It makes sense because C# by default short circuits the conditions, so I think it's fine to use that to your advantage. In VB there may be some issues if the developer uses AND instead of ANDALSO.

0
ответ дан 1 December 2019 в 17:10
поделиться

I find it OK :) You're just making sure that you don't access a NULL variable. Actually, I always do such checking before doing any operation on my variable (also, when indexing collections and so) - it's safer, a best practice, that's all ..

0
ответ дан 1 December 2019 в 17:10
поделиться

This is valid code, in my opinion (although declaring a variable and assigning it on the next line is pretty annoying), but you should probably realize that you can enter the else-block also in the condition where the length of the string is < 3.

2
ответ дан 1 December 2019 в 17:10
поделиться

Мне это кажется совершенно разумное использование логического замыкания - во всяком случае, это обман с языком. Я только недавно пришел с VB6, который никогда не закрывал, и это действительно раздражало меня .

Одна проблема, на которую следует обратить внимание, - это то, что вам может потребоваться снова проверьте наличие Null в этом предложении else, поскольку - как написано - вы заканчиваете там как строки Null, так и строки с длиной меньше трех.

2
ответ дан 1 December 2019 в 17:10
поделиться

This is perfectly valid and there is nothing wrong with using it that way. If you are following documented behaviour for the language than all is well. In C# the syntax you are using are the conditional logic operators and thier docemented bahviour can be found on MSDN

For me it's the same as when you do not use parenthesis for when doing multiplication and addition in the same statement because the language documents that the multiplication operations will get carried out first.

2
ответ дан 1 December 2019 в 17:10
поделиться

Этот код полностью действителен, но мне нравится использовать Null Coalesce Operator, чтобы избежать проверки нулевого типа.

string someString = MagicFunction() ?? string.Empty;
if (someString.Length > 3)
{
    // normal string, do whatever
}
else
{
   // NULL strings will be converted to Length = 0 and will end up here.
}
5
ответ дан 1 December 2019 в 17:10
поделиться

If you are asking if its ok to depend on the "short circuit" relational operators && and ||, then yes thats totally fine.

24
ответ дан 1 December 2019 в 17:10
поделиться

There is nothing wrong with this, as you just want to make certain you won't get a nullpointer exception.

I think it is reasonable to do.

With Extensions you can make it cleaner, but the basic concept would still be valid.

6
ответ дан 1 December 2019 в 17:10
поделиться

Theres nothing wrong with this.

if(conditions are evaluated from left to right so it's perfectly fine to stack them like this.

4
ответ дан 1 December 2019 в 17:10
поделиться
Другие вопросы по тегам:

Похожие вопросы: