Shortcut assignment in go excluding empty/nil value - go

This can be done in python / javascript:
# Python:
a = ""
b = "test"
c = a or b # test
// javascript
a = "";
b = "test";
c = a || b; // test
Can the same be accomplished in go without doing some conditional block? The only way I'm able to do this so far is with conditional blocks...
a := ""
b := "test"
var c
if a {
c = a
} else {
c = b
}
I think this is answer is going to be "no, this cannot be done", but I figured I would ask just in case I'm wrong. The example here is simplified. The variables a and b could have been defined long ago...

From golang FAQ, There is no ternary testing operation in Go. You may use the following to achieve the same result:
if expr {
n = trueVal
} else {
n = falseVal
}

Related

Random in a loop problerm

Random r = new Random(DateTime.Now.Millisecond);
int numberOfFoos = foos.Count;
int fooIndex1 = 0,fooIndex2 = 0;
Foo foo1 = new Foo();
Foo foo2 = new Foo();
do
{
while(fooIndex1 == fooIndex2)
{
fooIndex1 = r.Next(4);
fooIndex2 = r.Next(4);
}
foo1 = foosList[fooIndex1];
foo2 = foosList[fooIndex2];
}while(foo1.NumberOfLittleFoos == 0 || foo2.NumberOfLittleFoos == 0);
Why fooIndex1 is always 0 and fooIndex2 is always 2? I was trying to use Guid.NewGuid().GetHashCode() to generate random integers, but it still doesn't work rightly.
By this code I am trying to select 2 different Foo's from foosList.
I would be grateful for any help.
Your code will return same values for fooIndex1 and fooIndex2 only if DateTime.Now.Millisecond is the same for different runs. It's specified in Random class specification.
I've have run your code twice. First run gives fooIndex1 = 0, fooIndex2 = 2 and the second fooIndex1 = 1, fooIndex2 = 3.
Strange that you use r.Next(4). May be it's better to use r.Next(foosList.Count) to be able to access all items in your foosList.

Getting an Instance from 'unsafeAddressOf'

I encode an Int64 (on the graphics card) with unsafeAddressOf of some instances (that are properly stored in and retained by some array).
I then would like to get back to my instances from my Int64. I manage to get an UnsafePointer<MyClass> correctly initialized from my Int64.
Then, I do:
let x = UnsafePointer<MyClass>.memory.
But using x crashes.
I understand it is unsafe and tricky considering ARC. But still, is there any way to achieve this in Swift, or is it helpless?
Thanks.
What you are trying to do is extremely unsafe, as you yourself said, and there are probably safer approaches to solving whatever problem you are working on, but here is a complete example that does it:
func getPointer<T:AnyObject>(obj : T) -> Int64
{
return unsafeBitCast(unsafeAddressOf(obj), Int64.self)
}
func recoverObject<T:AnyObject>(ptr : Int64) -> T
{
return Unmanaged<T>.fromOpaque(COpaquePointer(bitPattern: Int(ptr))).takeUnretainedValue()
}
class C {
var cID = 0
func foo() {
print("Instance of C, id = \(cID)")
}
}
class D {
var dID = 0
func foo() {
print("Instance of D, id = \(dID)")
}
}
let c : C = C()
let d : D = D()
c.cID = 123;
d.dID = 321;
let cPtr : Int64 = getPointer(c)
let dPtr : Int64 = getPointer(d)
c.cID *= 10
let c1 : C = recoverObject(cPtr)
let d1 : D = recoverObject(dPtr)
c1.foo()
d1.foo()
The output is:
Instance of C, id = 1230
Instance of D, id = 321
Thanks to user3441734 for some helpful hints! Note the use of generics. The functions for getting a "pointer" and de-referencing it should work with any class (won't work with structs, though).
As far as safer ways of doing this, the answer would depend on the context of what you are doing. Why can't the array of instances be accessed wherever you need the instances instead of obtaining them via Int64s? If the array is actually maintained by (Objective-)C code in a 3rd party library, then there are additional problems that may arise due to memory alignment etc. It may be possible to write C code that would return instances to Swift code in a safer way.
Please let me know about more details if the answer doesn't work for some reason.
class C {
func foo() {
print("C")
}
}
var c = C()
let addr = unsafeAddressOf(c)
dump(addr)
/*
▿ UnsafePointer(0x7F86E942B230)
- pointerValue: 140217415807536
*/
let pC = withUnsafePointer(&c) { (p) -> UnsafePointer<C> in
return p
}
dump(pC)
/*
▿ UnsafePointer(0x10DE5B390)
- pointerValue: 4528124816
*/
dump(pC.memory)
/*
- C #0
*/
let opaquePointer = COpaquePointer(addr)
let unmanagedC = Unmanaged<C>.fromOpaque(opaquePointer)
dump(unmanagedC)
/*
▿ Swift.Unmanaged<C>
- _value: C #0
*/
// I still dont have an idea how to use it ...
ha, i got it!
unmanagedC.takeUnretainedValue().foo() // prints C !

For loop won't end. Don't know why

I'm writing a for loop for a project that prompts the user to input a number and keeps prompting, continually adding the numbers up. When a string is introduced, the loop should stop. I've done it with a while loop, but the project states that we must do it with a for loop also. The problem is that the prompt keeps running even when 'a = false'. Could someone explain javascript's thinking process? I want to understand why it keeps running back through the loop even though the condition isn't met. Thank you
var addSequence2 = function() {
var total = 0;
var a;
for (; a = true; ) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
a = true;
total = +total + +input;
}
else if (isNaN(input)) {
a = false;
document.write("Your total is " + total);
}
}
};
There is a difference between a = true and a == true.
Your for-loop is basically asking "can I set 'a' to true?", to which the answer is yes, and the loop continues.
Change the condition to a == true (thus asking "Is the value of 'a' true?")
To elaborate, in most programming languages, we distinguish between assignment ("Make 'x' be 4") and testing for equality ("Is 'x' 4?"). By convention (at least in languages that derive their syntax from C), we use '=' to assign/set a value, and '==' to test.
If I'm understanding the specification correctly (no guarantee), what happens here is that the condition condenses as follows:
Is (a = true) true?
Complete the bracket: set a to true
Is (a) true? (we just set it to true, so it must be!)
Try using the equal to operator, i.e. change
for (; a = true; ) {
to
for (; a == true; ) {
You should use a == true instead of a = true......= is an assignment operator
for (; a = true; ), you are assigning the value to the variable "a" and it will always remain true and will end up in infinite loop. In JavaScript it should a===true.
I suspect you want your for to look like this :
for(;a==true;)
as a=true is an assignment, not a comparison.
a == true. The double equal sign compares the two. Single equal assigns the value true to a so this always returns true.
for (; a = true; ) <-- this is an assignation
for (; a == true; ) <-- this should be better
Here's your fixed code :
var addSequence2 = function() {
var total = 0;
var a = true;
for(;Boolean(a);) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
total = total + input;
}
else{
a = false;
document.write("Your total is " + total);
}
}
};

removing nesting of if statements

I have a piece of code, which I am not sure how to refactor.. It is not very readable and I would like to make it readable. Here is a the problem
There are two columns in database which can be either NULL, 0 or have a value each. On the web page there is a checkbox - enable and text box - value for each of those two columns.
x = checkbox1
z = textbox1
y = checkbox2
w = textbox2
The logic is if both the checkboxes are not selected, then both the values should be 0. If either one is selected and other is not, then others value should be NULL. and for the one that is selected, if the textbox is empty its value should be NULL else should be the value in the textbox
if{x}
{
if(z)
{
a = NULL;
}
else
{
a = z;
}
if(y)
{
if(w)
{
b=w;
}
else
{
b = NULL;
}
}
else
{
b = null
}
}
else
{
if(y)
{
a = NULL;
if(w)
{
b=w;
}
else
{
b = NULL;
}
}
else
{
a = 0;
b = 0;
}
}
Trust me this is a valid scenario. Let me know if this makes sense or I should give more information
Using some logical ands and nots, we get something more readable.
We can save a little by defaulting to NULL (thus not needing to set the other to NULL). We can also save by putting the code for checking if a textbox is set or using null into a little function.
In pseudo code:
a = NULL
b = NULL
if (not checkbox1) and (not checkbox2):
a = 0
b = 0
if (checkbox1):
a = valueornull(textbox1)
if (checkbox2):
b = valueornull(textbox2)
function valueornull(textbox):
if textbox value:
return value
else:
return null
I think it would help to use more descriptive names that the single letters here, but assuming this is C code, it looks a lot neater with inline if statements:
if(x)
{
a = z ? NULL : z;
b = (y && w) ? w : NULL;
}
else
{
a = y ? NULL : 0;
b = (y && w) ? w : 0;
}

Redundant code constructs

The most egregiously redundant code construct I often see involves using the code sequence
if (condition)
return true;
else
return false;
instead of simply writing
return (condition);
I've seen this beginner error in all sorts of languages: from Pascal and C to PHP and Java. What other such constructs would you flag in a code review?
if (foo == true)
{
do stuff
}
I keep telling the developer that does that that it should be
if ((foo == true) == true)
{
do stuff
}
but he hasn't gotten the hint yet.
if (condition == true)
{
...
}
instead of
if (condition)
{
...
}
Edit:
or even worse and turning around the conditional test:
if (condition == false)
{
...
}
which is easily read as
if (condition) then ...
Using comments instead of source control:
-Commenting out or renaming functions instead of deleting them and trusting that source control can get them back for you if needed.
-Adding comments like "RWF Change" instead of just making the change and letting source control assign the blame.
Somewhere I’ve spotted this thing, which I find to be the pinnacle of boolean redundancy:
return (test == 1)? ((test == 0) ? 0 : 1) : ((test == 0) ? 0 : 1);
:-)
Redundant code is not in itself an error. But if you're really trying to save every character
return (condition);
is redundant too. You can write:
return condition;
Declaring separately from assignment in languages other than C:
int foo;
foo = GetFoo();
Returning uselessly at the end:
// stuff
return;
}
I once had a guy who repeatedly did this:
bool a;
bool b;
...
if (a == true)
b = true;
else
b = false;
void myfunction() {
if(condition) {
// Do some stuff
if(othercond) {
// Do more stuff
}
}
}
instead of
void myfunction() {
if(!condition)
return;
// Do some stuff
if(!othercond)
return;
// Do more stuff
}
Using .tostring on a string
Putting an exit statement as first statement in a function to disable the execution of that function, instead of one of the following options:
Completely removing the function
Commenting the function body
Keeping the function but deleting all the code
Using the exit as first statement makes it very hard to spot, you can easily read over it.
Fear of null (this also can lead to serious problems):
if (name != null)
person.Name = name;
Redundant if's (not using else):
if (!IsPostback)
{
// do something
}
if (IsPostback)
{
// do something else
}
Redundant checks (Split never returns null):
string[] words = sentence.Split(' ');
if (words != null)
More on checks (the second check is redundant if you are going to loop)
if (myArray != null && myArray.Length > 0)
foreach (string s in myArray)
And my favorite for ASP.NET: Scattered DataBinds all over the code in order to make the page render.
Copy paste redundancy:
if (x > 0)
{
// a lot of code to calculate z
y = x + z;
}
else
{
// a lot of code to calculate z
y = x - z;
}
instead of
if (x > 0)
y = x + CalcZ(x);
else
y = x - CalcZ(x);
or even better (or more obfuscated)
y = x + (x > 0 ? 1 : -1) * CalcZ(x)
Allocating elements on the heap instead of the stack.
{
char buff = malloc(1024);
/* ... */
free(buff);
}
instead of
{
char buff[1024];
/* ... */
}
or
{
struct foo *x = (struct foo *)malloc(sizeof(struct foo));
x->a = ...;
bar(x);
free(x);
}
instead of
{
struct foo x;
x.a = ...;
bar(&x);
}
The most common redundant code construct I see is code that is never called from anywhere in the program.
The other is design patterns used where there is no point in using them. For example, writing "new BobFactory().createBob()" everywhere, instead of just writing "new Bob()".
Deleting unused and unnecessary code can massively improve the quality of the system and the team's ability to maintain it. The benefits are often startling to teams who have never considered deleting unnecessary code from their system. I once performed a code review by sitting with a team and deleting over half the code in their project without changing the functionality of their system. I thought they'd be offended but they frequently asked me back for design advice and feedback after that.
I often run into the following:
function foo() {
if ( something ) {
return;
} else {
do_something();
}
}
But it doesn't help telling them that the else is useless here. It has to be either
function foo() {
if ( something ) {
return;
}
do_something();
}
or - depending on the length of checks that are done before do_something():
function foo() {
if ( !something ) {
do_something();
}
}
From nightmarish code reviews.....
char s[100];
followed by
memset(s,0,100);
followed by
s[strlen(s)] = 0;
with lots of nasty
if (strcmp(s, "1") == 0)
littered about the code.
Using an array when you want set behavior. You need to check everything to make sure its not in the array before you insert it, which makes your code longer and slower.
Redundant .ToString() invocations:
const int foo = 5;
Console.WriteLine("Number of Items: " + foo.ToString());
Unnecessary string formatting:
const int foo = 5;
Console.WriteLine("Number of Items: {0}", foo);

Resources