Silly question about how you format long if statements - syntax

On long if statements where they take up more than one line, do you put the conditions like AND or OR on a new line like this:
if (something
&& something else)
Or like this:
if (something &&
something else)

For complex conditions, consider extracting it into a function or a variable:
if (complexCondition(foo)) { ..
As a bonus, the name of the function or variable can be used to communicate what the condition means. This makes your code easier to read.

I typically do it the second way, since I can line up the statements. However, either way is fine when you're writing code, as long as you're consistent.

I prefer a rendition of the first. My reasoning is that deleting a condition via cut/paste/comment for any testing purposes is easier. It's a lot easier to comment out a line than it is to delete the and from the line above and comment out a line. This is more when I'm doing where clauses in SQL than in an if statement in any other given language, but is similar.

Given my druthers, I'd avoid long if tests in the first place. I'd rather do something like:
bool fTest1 = A == B ;
bool fTest2 = C ;
bool fTest3 = f(1,2,3) ;
bool fSuccess = ( fTest1 | ftest2 ) & fTest3 ;
if ( fSuccess )
...
Otherwise something like this:
if ( A == B
&& ( C == D
|| E == F
)
&& Z > Y
) {
...
}
else
{
...
}
YMMV, of course.
The former is far easier to debug, test, log, etc.

I usually format using the IDE formatter and then rearrange a bit to make it look beautiful.

I'm working in VSC and recently managed to not only write, but make readable very long conditions in nested if statements. Just use brackets and new lines like this. It should make automatic indentations:
foreach ($panstwa as $key => $value) {
if (is_object($value)) {
if (
(
($value->checkbox1 === true) && (is_string($value->panstwoZListy)) && ($value->panstwoZListy !== 'none') && ($value->panstwo === '') && ($value->panstwoZListy !== '')
) ||
(
(
($value->checkbox2 === true &&
($value->checkbox2_1 === true || $value->checkbox2_2 === true || $value->checkbox2_3 === true || $value->checkbox2_4 === true || $value->checkbox2_5 === true || $value->checkbox2_6 === true)
) ||
($value->checkbox3 === true &&
($value->checkbox3_1 === true || $value->checkbox3_2 === true)
) ||
($value->checkbox4 === true &&
(
(
($value->checkbox4_1 === true || $value->checkbox4_2 === true || $value->checkbox4_3 === true || $value->checkbox4_4 === true || $value->checkbox4_5 === true || $value->checkbox4_6 === true || $value->checkbox4_7 === true) && ($value->checkbox4_8 === false)
) ||
(
($value->checkbox4_1 === false && $value->checkbox4_2 === false && $value->checkbox4_3 === false && $value->checkbox4_4 === false && $value->checkbox4_5 === false && $value->checkbox4_6 === false && $value->checkbox4_7 === false) && ($value->checkbox4_8 === true) && (sprawdzRegexTextInput($value->prawnieUzasadnionyInteres)) && (is_object($value->dokumentacjaOceny) || is_string($value->dokumentacjaOceny))
)
)
)
) &&
(is_string($value->panstwo)) && ($value->panstwoZListy === 'none') && ($value->panstwo !== '') && (sprawdzRegexTextInput($value->panstwo)
)
) &&
((is_int($value->panstwoid) && is_numeric($value->panstwoid)) || (is_bool($value->panstwoid) && $value->panstwoid === false)) &&
(is_bool($value->zmiana))
) {
echo "ok";
//nie robię nic
} else {
$flagaPanstwa = false;
}
} else {
$flagaPanstwa = false;
}
}

Related

Ignore part of the linq query if variable equals a specific value

var longlinq = viewModel.Where(x => (x.Systems.Storage == SelectOption || x.Systems.Laptop == SelectOption ||
x.Systems._2In1 == SelectOption ||
x.Systems.Convertible == SelectOption )
||
(x.Component.Components == SelectOptionComp ||
x.Component.Boards == SelectOptionComp)
||
( x.Service.Services == SelectOptionSer ||
x.Service.DevelopmentTools_andServices == SelectOptionSer )
||
(x.Software.Softwares == SelectOptionSoft ||
x.Software.Analytics == SelectOptionSoft)
||
(x.Application.Applications == SelectOptionApp ||
x.Application.PrintImaging_andOfficeAutomation ));
Let me explain my question with an example:
For instance SelectOptionComp equals "-", then I want to ignore the parts where I used
SelectOptionComp in longlinq or set SelectOptionComp to " " in the longlinq.
I don't want to use ifs because of large number of combinations.
How do I do that?
I have used ternary operator Use the ternary operator: (SelectOptionComp == "-" ? true : (x.Component.Components == SelectOptionComp || x.Component.Boards == SelectOptionComp))

LINQ to Entities grouped logical operations in Where

I'm trying to execute the following linq query and it seems to be ignoring order of operations. (Parentheses first)
var result = _repo.Transactions.Where(t =>
t.DateEntered > EntityFunctions.AddDays(DateTime.Now, -7)
&& ( t.TranDesc != "BALANCE FORWARD" && t.Withdrawl == 0 && t.Deposit == 0 ) );
Here's the where clause that generates:
WHERE ([Extent1].[dateentered] > (DATEADD (day, -7, SysDateTime())))
AND (N'BALANCE FORWARD' <> [Extent1].[TranDesc])
AND (cast(0 as decimal(18)) = [Extent1].[Withdrawl])
AND (cast(0 as decimal(18)) = [Extent1].[Deposit])
Any ideas what I'm doing wrong?
EDIT:
This is actually what I wanted and it solved my problem. Just didn't think it all the way though. Thanks.
var result = _repo.Transactions.Where(t =>
t.dateentered > EntityFunctions.AddDays(DateTime.Now, -7)
&& ((t.TranDesc == "BALANCE FORWARD" && (t.Withdrawl != 0 || t.Deposit != 0))
|| (t.TranDesc != "BALANCE FORWARD")));
There is no difference between a && (b && c && d) and a && b && c && d, and that's why parentheses within generated SQL are not exactly the same as in your LINQ query. But at the end there is no difference between these queries.

C library for interfacing microcontroller and AT modem

I am working on some embedded system, where I use low-end uC, i.e. Atmega128.
My system also includes modem, driven via AT commands. I tried to look for any appropriate C library (for GCC), but couldn't find any. Although I know that putting "all" the possible AT command set into uC memory and so having "general purpose" library is unreasonable (and I just need around 30 commands for whole operation), I just need to get some suitable (i.e. lightweight, robust) control mechanism for handling transmitted and received UART strings in uC.
Does anybody know of any proven libraries or functions? Or maybe anyone could point me to some good resources/suggestions?
I hope you might be using this for the GSM or GPRS Modem interfacing, assuming as you have not specified application.
Brief : GSM, GPRS modem is also using AT command inteface for communication with external controller.
See detailed explanation here:
Microchip AN1373 - Using PIC32 MCUs to Develop GSM/GPRS/GPS Solutions
void UART_Buf(void)
{
ch=SCI2D;
if(rx_buffer[2] == 'O' && rx_buffer[3] =='K')
{
rx_buffer[5] = '\0';
msgindex=2; // code for OK
rx_wr_i=0;
}
if(rx_buffer[2] == 'B' && rx_buffer[3] =='U' && rx_buffer[4] == 'S' && rx_buffer[5] =='Y')
{
msgindex=3; // Code for Busy
rx_wr_i=0;
}
if(rx_buffer[2] == 'N' && rx_buffer[3] =='O' && rx_buffer[4] == ' ' && rx_buffer[5] =='C' && rx_buffer[6] =='A' && rx_buffer[7] =='R'&& rx_buffer[8] =='R' && rx_buffer[9] =='I' && rx_buffer[10] =='E' && rx_buffer[11] =='R')
{
msgindex=3; // Code for No Carrier
rx_wr_i=0;
}
if(rx_buffer[2] == 'E' && rx_buffer[3] =='R' && rx_buffer[4] == 'R' && rx_buffer[5] =='O' && rx_buffer[6] =='R' )
{
msgindex=4; // Code for Error
rx_wr_i=0;
}
if(rx_buffer[2]=='+' && rx_buffer[3]=='C' && rx_buffer[4] == 'M' && rx_buffer[5] =='S' )
{
msgindex=3;
}
if(rx_buffer[2]=='+' && rx_buffer[3]=='C' && rx_buffer[4] == 'M' && rx_buffer[5] =='E' )
{
msgindex=3;
}
if(rx_buffer[2]=='+' && rx_buffer[3]=='C' && rx_buffer[4] == 'M' && rx_buffer[5] =='G' && rx_buffer[6]== 'R')
{
msgindex=6;
}
if(rx_buffer[2]=='E' && rx_buffer[3]=='R' && rx_buffer[4] == 'R' && rx_buffer[5] =='O' && rx_buffer[6] == 'R')
{
msgindex=3;
}
if(rx_buffer[2]=='+' && rx_buffer[3]=='C' && rx_buffer[4] == 'S' && rx_buffer[5] =='Q' )
{
msgindex=7;
}
if(rx_buffer[2]=='+' && rx_buffer[3]=='C' && rx_buffer[4] == 'O' && rx_buffer[5] =='L'&& rx_buffer[6] =='P' )
{
msgindex=8;
}
if(ch == '\r')
linefeed++;
}
and in ISR
__interrupt void isrVsci2rx(void)
{
SCI2S1_RDRF = 0;
rx_buffer[rx_ack++]= SCI2D;
if(rx_ack>RX_BUFFER_MASK)
rx_ack=0;
UART_Buf();
rx_length++;
}
check msgindex and linefeed to know response received.

How to simplify a simple loop in Javascript?

I am now trying it out for a while and get it perfect. I am trying to simplify this for loop I created and make it actually work, without any arrays and only the most basic of basic JavaScript.
for (var x=0;x<=1;x++) {
if (secondInput == luckyNumber || secondInput == luckyNumber2 || secondInput == luckyNumber3) {
if (thirdInput == luckyNumber || thirdInput == luckyNumber2 || thirdInput == luckyNumber3) {
if (firstInput == luckyNumber || firstInput == luckyNumber2 || firstInput == luckyNumber3) {
while (firstInput !== secondInput){
while(firstInput !== thirdInput){while(secondInput !== thirdInput) {
alert('Congratulations! You got all 3 numbers correct. You\'ve won £1,000!');
}
}
}
}
}
}
Does this code make sense or am I doing something wrong? I've got the feeling that I can even leave the loop out, but it is the only way how I think it is correct.
Write a function that takes the input, compares it to the lucky numbers and returns a boolean with the result.
Call that function in your if clauses.
I don't quite understand what you are trying to do with the while loops.
You could try using this idea to help:
[1, 3, 2].sort()
(store your questions and answers in arrays, and sort both then compare. Of course, checking javascript arrays for equality is a fun new project :) )
Here you go. You said you wanted it simplified.
for (var x = 0; 1 >= x; x++) {
if (!(secondInput != luckyNumber && secondInput != luckyNumber2 && secondInput != luckyNumber3 || thirdInput != luckyNumber && thirdInput != luckyNumber2 && thirdInput != luckyNumber3 || firstInput != luckyNumber && firstInput != luckyNumber2 && firstInput != luckyNumber3)) {
while (firstInput !== secondInput) {
while (firstInput !== thirdInput) {
while (secondInput !== thirdInput) {
alert("Congratulations! You got all 3 numbers correct. You\'ve won £1,000!");
}
}
}
}
}

Linq query with multiple conditions

how to write the linq query with these conditions..first we have to check the OrderType if this is true then and condition should be checked.How to write the query..if i close the condition at .OrderType.XYZ) then it says 'zj' doesn't belong to the current context..if we remove that no error but we r not getting the req result
bool btnvisible= datacontext.GetOrders(new List<Items> { selectedItem }).
.Where((zj => wo.OrderId== (int)BL.OrderType.PQR || zj.OrderId== (int)BL.OrderType.XYZ)
&&( zj.OrderId== (int)BL.Statuses.Assigned
|| zj.OrderId== (int)BL.Statuses.Planned
|| zj.OrderId== (int)BL.Statuses.InProgess
|| zj.OrderId== (int)BL.Statuses.Paused
|| zj.OrderId== (int)BL.Statuses.Ready)).Any();
return btnEnable;
I think this is due to some misplaced brackets. You have .Where((zj => ...) ... zj ...). The variable zj doesn't exist outside of the first set of brackets. It should be something like:
bool btnvisible= datacontext.GetOrders(new List<Items> { selectedItem })
.Where(zj => (wo.OrderId== (int)BL.OrderType.PQR || zj.OrderId== (int)BL.OrderType.XYZ)
&& (zj.OrderId== (int)BL.Statuses.Assigned
|| zj.OrderId== (int)BL.Statuses.Planned
|| zj.OrderId== (int)BL.Statuses.InProgess
|| zj.OrderId== (int)BL.Statuses.Paused
|| zj.OrderId== (int)BL.Statuses.Ready)).Any();
return btnEnable;
You appear to have a mismatched parenthesis problem.
.Where((zj => wo.OrderId== (int)BL.OrderType.PQR || zj.OrderId== (int)BL.OrderType.XYZ)
^ ^
That's mucking with the scope of your variable. Revisit it.
var readyStats = new [] {
(int)BL.Statuses.Assigned,
(int)BL.Statuses.Planned,
(int)BL.Statuses.InProgess,
(int)BL.Statuses.Paused,
(int)BL.Statuses.Ready,
};
var orderTypes = new [] {
(int)BL.OrderType.PQR,
(int)BL.OrderType.XYZ
}
bool btnvisible= datacontext.GetOrders(new List<Items> { selectedItem }).
.Where(wo => orderTypes.Contains(wo.OrderId) && readyStats.Contains(wo.OrderId)).Any();
or
bool btnvisible= datacontext.GetOrders(new List<Items> { selectedItem }).
.Any(wo => orderTypes.Contains(wo.OrderId) && readyStats.Contains(wo.OrderId));
I think the problem is here:
.Where((zj => wo.
The right version should be:
.Where(zj => zj.

Resources