Is there a better way to write this If conditions - if-statement

I wonder if there is a better way to write this.
if ( num == 0 || num == 20 || num == 32 ) {
// execute
}
Would it be better to use case? or loop the condition?
Prefered language is Javascript, then any language will do.

In JavaScript you can write this instead:
if ([0, 2, 32].includes(num)) {
// execute
}
Or
let some_array = [0, 2, 32]
// more code
if (some_array.includes(num)) {
// execute
}
if the list of cases might change, especially if the exact set of options is a function of user actions. And then you might use an if-else statement, e.g.
let some_array = [0, 2, 32]
// more code
if (some_array.includes(num)) {
// execute
} else
// execute else
}
or more complex if else trees. But in any case Array.prototype.includes is a great option for something like this. It’s very flexible, maintainable, and easy to read. And much more powerful—-you can fetch the array of options from database using a REST call, or build it from user input, you can filter it based on user-supplied filters. All things that would be much harder to do if you test for each possible value by itself one at a time.

Related

Is it possible to create if statement dynamically based on JSON in C or C++

I would like to know that is there any approach to create "if" statements dynamically in C or C++ based on JSON.
For example, I have following JSON input
Rule1
{
"ifstatement1": {
"condition1": 0,
"condition2": "down"
},
"actionstatement1": {
"val1": 235959,
"val2": "yes",
"val3": 5,
"val4": 0,
"val5": "increse",
"val6": 1
}
}
Rule2
{
"ifstatement2": {
"condition1": 2,
"condition2": "up",
"condition3": 10
},
"actionstatement2": {
"val1": 1223,
"val2": "no",
"val3": 5
}
}
Based on above JSON input, I need to create if statements dynamically using C or C++. Have to parse above json data and treat this as actual if-else statements in C or C++.
whatever comes like "ifstatement1", should be converted to condition check, if this check is true then have to apply values present in "actionstatement1".
Number of ifstatements and action-statements can vary dynamically.
Is there any specific approach in C or C++ for evaluating json data as parameters dynamically ?
This is like a Rules that we are giving in JSON format. This rules should be stored when the program starts and it will be checked in particular period of time with the current values and stored values. if any condition matches, then apply values of that condition.
Please share if any better approach is available.
So if you are thinking of creating if statement inside your C++ code on the fly or after you compiled your code, the answer is you cannot do that. You can create parser that will have if statement ready for you. Remember C and C++ are compiled languages meaning what you put in code it is compiled to 0s and 1s and when you run it, those 0s and 1s are in memory loaded for you.
You should specify the condition you want to achieve and also make a decision about using C or C++ otherwise your question is too general.
Also yours does not look like a proper JSON: what is Rule1?Is it a Key? Then it should be something like {"Rule1" :{...}} and the inner structure should be same for example "ifstatement" instead of "ifstatement1" and "ifstatement2", "actionstatemen" instead of "actionstatement1" "actionstatement2"
I will assume your JSON, which is not a JOSN for how you posted, has the form:
[
{
"id" : "Rule1",
"ifstatement": {
"condition1": 0,
"condition2": "down"
},
"actionstatement": {
"val1": 235959,
"val2": "yes",
"val3": 5,
"val4": 0,
"val5": "increse",
"val6": 1
},
{
"id": "Rule2",
"ifstatement": {
"condition1": 2,
"condition2": "up",
"condition3": 10
},
"actionstatement": {
"val1": 1223,
"val2": "no",
"val3": 5
}
}
]
There are different libraries that allows that in C++. One of them is JSONcpp (I downloaded the source code but maybe if you are on Unix/Linux there is a binary version you can install.
The code I used to read it is something like:
Json::Value root;
std::string dataFileName = "yourPath/filename.json"
if( access( dataFileName.c_str(), F_OK ) != -1 )
{
std::ifstream file(dataFileName);
file >> root;// file exists
for (Json::Value::ArrayIndex i = 0; i != root.size(); i++)
{
for (Json::Value::ArrayIndex j = 0; j != root[i]["ifstatement"].size(); j++)
{
(root[i]["ifstatement"][j] );
...
}
}
}
So basically root represents all your file and the type Json::Value::ArrayIndex j allows to iterate through your JSON file that, for how I have rewritten its most external structure is an array. Then you can access the fields as:
root[0] equivalent to your original RUle1 and then specify the key: for example root[0]["ifstatement"]. If you have to convert a value to integer from the JSON file you should use the method asInt() or asFloat() for float.
Being your question too general I cannot help you further :(
As others have said from both the comments and User Gox's answer; you can not dynamically create if statements on the fly or dynamically speaking.
However, after reading your comment or reply to another:
This is sample conditions. if (condition1 == 0 && !strcmp(condition2, "down") ) then perform an action. condition1 values can be 0,1,2... and based on those values actions will vary.
This gives me a little more information about what you are trying to achieve. As others have stated you would probably have to write a parser to have if statements ready for you, but if you take your input from your JSON and create a relationship tree for example:
Initial Condition: Determining Condition: Action To Perform:
condition1 == 0: !strcmp(condition2, "down") perform desired action
condition1 == 0: next condition perform desired action
...
condition1 == 1: ... ...
...
condition1 == 2: ... ...
You should be able to create some kind of key structure such as using a std::multimap or something similar to build your table.

Best practice for having two if statements from the same bool c++

I have an if statement that [obviously] only runs if the condition is true. After this if statement there is some code that should always run, after that is another if statement that should run under the same condition as the first.
The code in the middle is performing an operation using a particular element of a stack, the ifs on either side perform a push/pop on the stack before and after the operation respectively.
so the logic is something like this:
Do I need to push the stack? yes/no
perform operation on top of stack
Was the stack pushed? (if yes then pop)
items 1 and 3 are the same condition.
This is the code that I first wrote to do this in c++
#include <stdio.h>
#include <stdlib.h>
int somefunction(){
return rand() % 3 + 1; //return a random number from 1 to 3
}
int ret = 0;
//:::::::::::::::::::::::::::::::::::::::
// Option 1 Start
//:::::::::::::::::::::::::::::::::::::::
int main(){
bool run = (ret = somefunction()) == 1; //if the return of the function is 1
run = (run || (ret == 2)); //or the return of the function is 2
if (run){ //execute this if block
//conditional code
if (ret == 1){
//more conditional code
}
}
//unconditional code
if (run){
//even more conditional code
}
}
//:::::::::::::::::::::::::::::::::::::::
// Option 1 End
//:::::::::::::::::::::::::::::::::::::::
After writing this I thought that it might be more efficient to do this:
//:::::::::::::::::::::::::::::::::::::::
// Option 2 Start
//:::::::::::::::::::::::::::::::::::::::
int main(){
bool run;
if (run=(((ret = somefunction()) == 1)||ret == 2)){ //if the return of the function is 1 or 2 then execute this if block
//conditional code
if (ret == 1){
//more conditional code
}
}
//unconditional code
if (run){
//even more conditional code
}
}
//:::::::::::::::::::::::::::::::::::::::
// Option 2 End
//:::::::::::::::::::::::::::::::::::::::
I prefer the first method for readability as it is split into several lines whereas the second has two assignments (=) and two comparisons (==) in the same line.
I want to know if it is better to use the second method (for reasons of efficiency or executable size) or if there is a better method than both.
Before anyone says it will only make an almost immeasurable difference, this is in a huge loop that has to run many thousands of times within 1/50 of a second so I would like to save as much time as possible.
Performance should not be your concern: the modern compilers are usually smart enough to optimize the code in any case. The results will be the same if the code is doing essentially the same thing.
So you should prefer the variant which is more readable (and therefore better maintainable).
I would write something like that:
ret = somefunction();
// I don't know what is the semantics of ret == 1, so let's imagine some
bool operationIsPush = (ret == 1);
bool operationIsOnTop = (ret == 2);
if (operationIsPush || operationIsOnTop)
{
//conditional code
}
if (operationIsPush)
{
//more conditional code
}
//unconditional code
if (operationIsPush || operationIsOnTop)
{
// ...
}
I believe there will be no difference in the performance here. The first reason is that your compiler will probably optimize the code in each case. The second is that you just change the place where operations take place (like "I do A->B->C or A->C->B"), not the amount of operations, so it's always the same amount of computing (1 function call, a couple of == and so on).
However consider that this
(run=(((ret = somefunction()) == 1)||ret == 2))
is pretty hard to read.
Correctness is more important than whether you fold two operations assigning a bool into one (which the compiler will probably do anyway).
For pushing/popping a stack, you should use a scopeguard (original article here). This will ensure that if something throws in the "unconditional bit", which you never really know for sure, then it still runs correctly. Otherwise you get funny a surprise (stack off by one, or overflowing).
if theres a situation that you can split "if-else" to distinct huge loops, it will be faster
rather than
loop { if_1 {some work} if_2 {some other work} }
you can
if_1 { loop {work }} if_2 {loop{same work}}
even more extremely, if you can split the most inner "if" sentences, you can have 10-20(dpending on your situation) distinct huge loops that runs x2 x3 faster (if it is slow bacause of "if")

Design Pattern For Making An Assembler

I'm making an 8051 assembler.
Before everything is a tokenizer which reads next tokens, sets error flags, recognizes EOF, etc.
Then there is the main loop of the compiler, which reads next tokens and check for valid mnemonics:
mnemonic= NextToken();
if (mnemonic.Error)
{
//throw some error
}
else if (mnemonic.Text == "ADD")
{
...
}
else if (mnemonic.Text == "ADDC")
{
...
}
And it continues to several cases. Worse than that is the code inside each case, which checks for valid parameters then converts it to compiled code. Right now it looks like this:
if (mnemonic.Text == "MOV")
{
arg1 = NextToken();
if (arg1.Error) { /* throw error */ break; }
arg2 = NextToken();
if (arg2.Error) { /* throw error */ break; }
if (arg1.Text == "A")
{
if (arg2.Text == "B")
output << 0x1234; //Example compiled code
else if (arg2.Text == "#B")
output << 0x5678; //Example compiled code
else
/* throw "Invalid parameters" */
}
else if (arg1.Text == "B")
{
if (arg2.Text == "A")
output << 0x9ABC; //Example compiled code
else if (arg2.Text == "#A")
output << 0x0DEF; //Example compiled code
else
/* throw "Invalid parameters" */
}
}
For each of the mnemonics I have to check for valid parameters then create the correct compiled code. Very similar codes for checking the valid parameters for each mnemonic repeat in each case.
So is there a design pattern for improving this code?
Or simply a simpler way to implement this?
Edit: I accepted plinth's answer, thanks to him. Still if you have ideas on this, i will be happy to learn them. Thanks all.
I've written a number of assemblers over the years doing hand parsing and frankly, you're probably better off using a grammar language and a parser generator.
Here's why - a typical assembly line will probably look something like this:
[label:] [instruction|directive][newline]
and an instruction will be:
plain-mnemonic|mnemonic-withargs
and a directive will be:
plain-directive|directive-withargs
etc.
With a decent parser generator like Gold, you should be able to knock out a grammar for 8051 in a few hours. The advantage to this over hand parsing is that you will be able to have complicated enough expressions in your assembly code like:
.define kMagicNumber 0xdeadbeef
CMPA #(2 * kMagicNumber + 1)
which can be a real bear to do by hand.
If you want to do it by hand, make a table of all your mnemonics which will also include the various allowable addressing modes that they support and for each addressing mode, the number of bytes that each variant will take and the opcode for it. Something like this:
enum {
Implied = 1, Direct = 2, Extended = 4, Indexed = 8 // etc
} AddressingMode;
/* for a 4 char mnemonic, this struct will be 5 bytes. A typical small processor
* has on the order of 100 instructions, making this table come in at ~500 bytes when all
* is said and done.
* The time to binary search that will be, worst case 8 compares on the mnemonic.
* I claim that I/O will take way more time than look up.
* You will also need a table and/or a routine that given a mnemonic and addressing mode
* will give you the actual opcode.
*/
struct InstructionInfo {
char Mnemonic[4];
char AddessingMode;
}
/* order them by mnemonic */
static InstructionInfo instrs[] = {
{ {'A', 'D', 'D', '\0'}, Direct|Extended|Indexed },
{ {'A', 'D', 'D', 'A'}, Direct|Extended|Indexed },
{ {'S', 'U', 'B', '\0'}, Direct|Extended|Indexed },
{ {'S', 'U', 'B', 'A'}, Direct|Extended|Indexed }
}; /* etc */
static int nInstrs = sizeof(instrs)/sizeof(InstrcutionInfo);
InstructionInfo *GetInstruction(char *mnemonic) {
/* binary search for mnemonic */
}
int InstructionSize(AddressingMode mode)
{
switch (mode) {
case Inplied: return 1;
/ * etc */
}
}
Then you will have a list of every instruction which in turn contains a list of all the addressing modes.
So your parser becomes something like this:
char *line = ReadLine();
int nextStart = 0;
int labelLen;
char *label = GetLabel(line, &labelLen, nextStart, &nextStart); // may be empty
int mnemonicLen;
char *mnemonic = GetMnemonic(line, &mnemonicLen, nextStart, &nextStart); // may be empty
if (IsOpcode(mnemonic, mnemonicLen)) {
AddressingModeInfo info = GetAddressingModeInfo(line, nextStart, &nextStart);
if (IsValidInstruction(mnemonic, info)) {
GenerateCode(mnemonic, info);
}
else throw new BadInstructionException(mnemonic, info);
}
else if (IsDirective()) { /* etc. */ }
Yes. Most assemblers use a table of data which describes the instructions: mnemonic, op code, operands forms etc.
I suggest looking at the source code for as. I'm having some trouble finding it though. Look here. (Thanks to Hossein.)
I think you should look into the Visitor pattern. It might not make your code that much simpler, but will reduce coupling and increase reusability. SableCC is a java framework to build compilers that uses it extensively.
When I was playing with a Microcode emulator tool, I converted everything into descendants of an Instruction class. From Instruction were category classes, such as Arithmetic_Instruction and Branch_Instruction. I used a factory pattern to create the instances.
Your best bet may be to get a hold of the assembly language syntax specification. Write a lexer to convert to tokens (**please, don't use if-elseif-else ladders). Then based on semantics, issue the code.
Long time ago, assemblers were a minimum of two passes: The first to resolve constants and form the skeletal code (including symbol tables). The second pass was to generate more concrete or absolute values.
Have you read the Dragon Book lately?
Have you looked at the "Command Dispatcher" pattern?
http://en.wikipedia.org/wiki/Command_pattern
The general idea would be to create an object that handles each instruction (command), and create a look-up table that maps each instruction to the handler class. Each command class would have a common interface (Command.Execute( *args ) for example) which would definitely give you a cleaner / more flexible design than your current enormous switch statement.

Self-imposed try/catch for unwanted integers

Try and catch statements are easy for actual exceptions, but how might I write a try/catch for a self-imposed restriction?
For example, if I am getting an integer from cin that I want to be either 2,4, or 7, and anything else to print "That number is not valid" and try again, how would this get written in c++?
#Adam Rosenfield is right: exceptions should be reserved for exceptional situations -- i.e., things you don't expect to happen (or at least not very often). A user entering bad data is expected to happen -- frequently.
Since you always want to read the input at least once, this is a situation where a do/while loop makes sense:
do {
std::cin >> number;
} while (number != 2 && number != 4 && number != 7);
You could probably do this using a simple while loop:
while (true) {
int value = /* ... read a number ... */
if (value == 2 || value == 4 || value == 7) break;
/* ... report an error ... */
}
You are correct that you shouldn't be using try/catch here. Those are heavyweight primitives for dealing with truly unrecoverable errors. In this case, this simple lightweight loop should work just fine.

Checking lists and running handlers

I find myself writing code that looks like this a lot:
set<int> affected_items;
while (string code = GetKeyCodeFromSomewhere())
{
if (code == "some constant" || code == "some other constant") {
affected_items.insert(some_constant_id);
} else if (code == "yet another constant" || code == "the constant I didn't mention yet") {
affected_items.insert(some_other_constant_id);
} // else if etc...
}
for (set<int>::iterator it = affected_items.begin(); it != affected_items.end(); it++)
{
switch(*it)
{
case some_constant_id:
RunSomeFunction(with, these, params);
break;
case some_other_constant_id:
RunSomeOtherFunction(with, these, other, params);
break;
// etc...
}
}
The reason I end up writing this code is that I need to only run the functions in the second loop once even if I've received multiple key codes that might cause them to run.
This just doesn't seem like the best way to do it. Is there a neater way?
One approach is to maintain a map from strings to booleans. The main logic can start with something like:
if(done[code])
continue;
done[code] = true;
Then you can perform the appropriate action as soon as you identify the code.
Another approach is to store something executable (object, function pointer, whatever) into a sort of "to do list." For example:
while (string code = GetKeyCodeFromSomewhere())
{
todo[code] = codefor[code];
}
Initialize codefor to contain the appropriate function pointer, or object subclassed from a common base class, for each code value. If the same code shows up more than once, the appropriate entry in todo will just get overwritten with the same value that it already had. At the end, iterate over todo and run all of its members.
Since you don't seem to care about the actual values in the set you could replace it with setting bits in an int. You can also replace the linear time search logic with log time search logic. Here's the final code:
// Ahead of time you build a static map from your strings to bit values.
std::map< std::string, int > codesToValues;
codesToValues[ "some constant" ] = 1;
codesToValues[ "some other constant" ] = 1;
codesToValues[ "yet another constant" ] = 2;
codesToValues[ "the constant I didn't mention yet" ] = 2;
// When you want to do your work
int affected_items = 0;
while (string code = GetKeyCodeFromSomewhere())
affected_items |= codesToValues[ code ];
if( affected_items & 1 )
RunSomeFunction(with, these, params);
if( affected_items & 2 )
RunSomeOtherFunction(with, these, other, params);
// etc...
Its certainly not neater, but you could maintain a set of flags that say whether you've called that specific function or not. That way you avoid having to save things off in a set, you just have the flags.
Since there is (presumably from the way it is written), a fixed at compile time number of different if/else blocks, you can do this pretty easily with a bitset.
Obviously, it will depend on the specific circumstances, but it might be better to have the functions that you call keep track of whether they've already been run and exit early if required.