• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 03:26
CEST 09:26
KST 16:26
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL22] Ro8 Preview: In A Tizzy9[ASL22] Ro16 Preview: Holy Diver5[ASL22] Ro16 Preview: Rough Waters10[ASL22] Ro24 Preview: Siren's Call8[ASL22] Ro24 Preview: Summer's End9
Community News
Weekly Cups (Sep 13-20): herO scores triple1BSL Season 235Weekly Cups (Sep 7-12): SHIN, ByuN, MaxPax double down1StarCraft open world shooter announced at BlizzCon101Weekly Cups (Aug 30-Sep 7): herO thrives amid growing schism10
StarCraft 2
General
Balance hotfix patch 5.0.16b (July 16) Blizzard Classic Cup @ BlizzCon 2026 - $100k prize pool How do you feel about the StarCraft shooter announcement at BlizzCon 2026? The Death of Cheese: From a Professional Cheeser Weekly Cups (Sep 13-20): herO scores triple
Tourneys
Stellar Fest TWO the Moon (Dec 16-20) Sparkling Tuna Cup - Weekly Open Tournament 2026 GSTL Announcement RSL Revival: Season 6 - Qualifiers and Main Event RSL goes to London! 2026 Offline Finals Nov 21-22
Strategy
[H] ZvP Mid-Late Game: Stalkers Collossi HT
Custom Maps
Nexus Wars 2021 GUIDE [M] (2) Industrial Park
External Content
Mutation # 544 Double Trouble The PondCast: SC2 News & Results Mutation # 543 Enhanced Defenses Mutation # 542 The Ascended
Brood War
General
screpdb: new Starcraft reporting tool an AI researcher's take on the ladder bot BW General Discussion Bot on ladder [ASL22] Ro8 Preview: In A Tizzy
Tourneys
[ASL22] Ro8 Day 2 [ASL22] Ro16 Group D [ASL22] Ro8 Day 1 [IPSL] IPSL is Back With Winter 26-27!
Strategy
Cliff Jump Revisited (1 in a 1000 strategy) Replay Review Process - What do you do? Simple Questions, Simple Answers Odyssey Mineral Stack Saturation
Other Games
General Games
Diablo IV Nintendo Switch Thread Warcraft III: The Frozen Throne Stormgate/Frost Giant Megathread EVE Corporation
Dota 2
Dota 2 Champions League Season 3 Begins April 25! Official 'what is Dota anymore' discussion
League of Legends
[TL LoL EUW IHs] Teemo shall perish
Heroes of the Storm
Heroes of the Storm 2.0
Hearthstone
Deck construction bug
TL Mafia
TL Mafia Community Thread
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread Artificial Intelligence Thread Things Aren’t Peaceful in Palestine All you football fans (soccer)!
Fan Clubs
MarineLorD Fan Club The Creator Fan Club The ShoWTimE Fan Club
Media & Entertainment
Movie Discussion! [Manga] One Piece Diablo Animated Series on Netflix
Sports
Football (Soccer) Thread TeamLiquid Health and Fitness Initiative For 2023 MLB/Baseball 2023
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
Recent Gifted Posts
Blogs
Gaming Intensity, Problemati…
TrAiDoS
38 yo Retired SWE loo…
PurE)Rabbit-SF
Can Bots Beat Pros?? Starcr…
namkraft
[meme] I finally understa…
LUCKY_NOOB
Regacy Esports:Our Goa…
regacyesports
Dreaming of BW patches (mod…
c3rberUs
Customize Sidebar...

Website Feedback

Closed Threads



Active: 7947 users

The Big Programming Thread - Page 270

Forum Index > General Forum
Post a Reply
Prev 1 268 269 270 271 272 1032 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
ThatGuy
Profile Blog Joined April 2008
Canada695 Posts
March 15 2013 02:32 GMT
#5381
On March 15 2013 11:18 Orome wrote:
Hey guys, small C++ question that I hope someone can help me with. Assuming we have a std::stack called someStack consisting of SomeClass objects, why does this sort of code work fine?

SomeClass *next = someStack.top();
stack.pop();
next.printWhatever();


Since next is a pointer variable pointing to someStack.top(), shouldn't it point to a null object once that object is destroyed through pop?


Pop does not destroy the object, it simply de-references it from the stack (otherwise, using a stack as a container wouldn't be very useful would it!). Since next* contains the address to the object, the garbage collector has no reason to clean out that object from memory.
nunez
Profile Blog Joined February 2011
Norway4003 Posts
March 15 2013 02:41 GMT
#5382
On March 15 2013 11:18 Orome wrote:
Hey guys, small C++ question that I hope someone can help me with. Assuming we have a std::stack called someStack consisting of SomeClass objects, why does this sort of code work fine?

SomeClass *next = someStack.top();
stack.pop();
next.printWhatever();


Since next is a pointer variable pointing to someStack.top(), shouldn't it point to a null object once that object is destroyed through pop?


i don't think pop() invokes the destructor of top() when called.

pop_back (same as pop()):
"Removes the last element of the container.
No iterators or references are invalidated."
conspired against by a confederacy of dunces.
alwinuz
Profile Joined September 2011
Netherlands77 Posts
Last Edited: 2013-03-15 02:56:10
March 15 2013 02:48 GMT
#5383
On March 15 2013 06:49 Morfildur wrote:
Show nested quote +
On March 15 2013 03:53 alwinuz wrote:
I don't think speed matters, it's more a question of what is more readable and maintainable code.
Write easy code first, optimize for speed later (and measure first!).
But is this more readable than the original code? Not sure... personal preference I think.


I think it's definitely more readable and maintainable.

There is just one place you have to look at to know where every level begins and ends, you don't have to go through each "else if" to find all the values. If you need to adjust it you instantly know where you have to do it, no need to search through potentially dozens of cases. If you have to add a case, no need to search through all branches to know where it belongs, you can see it in the short list.

Sure, in this case it's a small amount of branches but i had a similar situation with price groups where certain video lengths resulted in different prices and there were twice as many potential values and the previous "if/else if" stuff was far too long. After i changed it to something similar to my code above (in PHP), it was so easy that i was able to copy-paste the list into an email to the product manager and he understood it easily.

I could probably also have written it like this, which is easier to the untrained eye:

var boundaries = new Array();
boundaries["39"] = "";
boundaries["49"] = "third level";
...

Hey I'm with you I write code like this all the time. But it can look difficult for someone who is unfamiliar with this type of coding. Clever code is not always the easiest code to read, so at least a comment would be great for my coworkers.


On March 15 2013 04:17 RoyGBiv_13 wrote:
Show nested quote +
On March 15 2013 03:53 alwinuz wrote:
I don't think speed matters, it's more a question of what is more readable and maintainable code.
Write easy code first, optimize for speed later (and measure first!).
But is this more readable than the original code? Not sure... personal preference I think.


I don't really want to start a big huff over nothing, but there is a misconception I don't want spread. The idea that an easily maintainable design is a trade off with with code speed is absurd. The better the design, the smaller the code base, more maintainable, readable, and faster it will be. If you find that your code is running slow, then optimizing it will only cause problems in your understanding of the code. This is often why people rewrite programs from scratch, because they tried to optimize something, realized they did the design wrong, and start over.

Optimization should be done out the gate, so that your design pattern will reflect the quickest way to solve the problem, and be easier to understand because of it.


You don't want to start a big huf, then what did you just do?
I'll just dump a relevant story: http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html
And you give the answer yourself: there's a difference between micro-optimization at code level, and optimizing the design of the software as a whole. + what Tobberoth said


On March 15 2013 06:44 Blisse wrote:
Show nested quote +
On March 15 2013 06:37 Tobberoth wrote:
On March 15 2013 06:34 Blisse wrote:

On March 14 2013 23:25 FFGenerations wrote:
Using javascript & html, i have a button on a page and a text box. User inputs a grade number into the text box and presses the button. An alert pops up based on the input, using a simple if statement, telling the user if the entered grade is a merit, pass etc.

+ Show Spoiler +

if(grade!="")
{
if(grade>-1&&grade<40)
{
alert("This is below threshold.")
}
else if(grade>39&&grade<50)
{
alert("This is a third class degree.")
}
else if(grade>49&&grade<60)
{
alert("This is a lower second degree.")
}
else if(grade>59&&grade<70)
{
alert("This is an upper second degree.")
}
else if(grade>69&&grade<101)
{
alert("This is a first class degree.")
}
else
{
alert("Please enter a grade from 0 to 100.")
}
}
else
{
alert("Please enter a grade from 0 to 100.")
}
}


The question is, why do i need to lay out everything within a second if statement?
The first time i wrote it, i had similar to the following:

+ Show Spoiler +


if(grade="")
{
alert("You need to enter a grade")
}
else if(grade>-1&&grade<40)
{
alert("This is below threshold.")
}
else if(grade>39&&grade<50)
{
alert("This is a third class degree.")
}
else if(grade>49&&grade<60)
{
alert("This is a lower second degree.")
}
else if(grade>59&&grade<70)
{
alert("This is an upper second degree.")
}
else if(grade>69&&grade<101)
{
alert("This is a first class degree.")
}
else
{
alert("Please enter a grade from 0 to 100.")
}



however, this kept displaying "This is below threshold." instead of running the if(grade="") part.
My tutor said it might be something to do with the if statements switching from string ("") to int (grade>-1&&grade<40) which is somehow messing it up.

Many thanks



Your code seems to be able to compare integers and strings without regard for the data type.

I think you have to apply a parseInt(grade) after you've validated the grade is a number, before you can perform all these checks. That's what I think I did when I did JS some years ago.

There's no problem comparing strings and numbers in javascript. Try something like:
alert("20" > 5) and you'll get true.


Because "20" as an ASCII value should be greater than 5, at least it would make sense if it were.

"4" > 5 doesn't seem like it would return true, but it probably does here. Again, not a JS person.

And anyways, I don't believe you're suggesting one should compare strings with integers like that. Best practice should always be string with string and int with int.

"4" > 5 actually returns false! (just tested) I didn't know that because I always follow your best practice.

On March 14 2013 23:25 FFGenerations wrote:
Using javascript & html, i have a button on a page and a text box. User inputs a grade number into the text box and presses the button. An alert pops up based on the input, using a simple if statement, telling the user if the entered grade is a merit, pass etc.

+ Show Spoiler +

if(grade!="")
{
if(grade>-1&&grade<40)
{
alert("This is below threshold.")
}
else if(grade>39&&grade<50)
{
alert("This is a third class degree.")
}
else if(grade>49&&grade<60)
{
alert("This is a lower second degree.")
}
else if(grade>59&&grade<70)
{
alert("This is an upper second degree.")
}
else if(grade>69&&grade<101)
{
alert("This is a first class degree.")
}
else
{
alert("Please enter a grade from 0 to 100.")
}
}
else
{
alert("Please enter a grade from 0 to 100.")
}
}


The question is, why do i need to lay out everything within a second if statement?
The first time i wrote it, i had similar to the following:

+ Show Spoiler +


if(grade="")
{
alert("You need to enter a grade")
}
else if(grade>-1&&grade<40)
{
alert("This is below threshold.")
}
else if(grade>39&&grade<50)
{
alert("This is a third class degree.")
}
else if(grade>49&&grade<60)
{
alert("This is a lower second degree.")
}
else if(grade>59&&grade<70)
{
alert("This is an upper second degree.")
}
else if(grade>69&&grade<101)
{
alert("This is a first class degree.")
}
else
{
alert("Please enter a grade from 0 to 100.")
}



however, this kept displaying "This is below threshold." instead of running the if(grade="") part.
My tutor said it might be something to do with the if statements switching from string ("") to int (grade>-1&&grade<40) which is somehow messing it up.

Many thanks

Not sure if you know this already, but have you tried debugging? In Google Chrome press F12, or use Firebug addon in Firefox. You can set a breakpoint, step through your code, inspect the value of 'grade' etc. Sorry no actual answer to your question, but maybe you can find the answer yourself!
ddengster
Profile Blog Joined January 2009
Singapore129 Posts
March 15 2013 02:49 GMT
#5384
What are you storing in your std::stack? Pointers(stack<SomeClass*>) or Objects(stack<SomeClass>)?
Judging from the way you use you wrote the code, it's pointers. Remember that pointers are merely addresses, and that they point to some location in memory. If you created the object using new (ie. on the heap), it won't be destroyed until you delete the pointer. stack.pop() simply removes the topmost element in the stack. If it's of this type: stack<SomeClass>, then it'll call the destructor, else for stack<SomeClass*> it simply removes the topmost address

Check out NEO Impossible Bosses, RTS-MOBA boss rush at http://neoimpossiblebosses.coder-ddeng.com
Orome
Profile Blog Joined June 2004
Switzerland11984 Posts
March 15 2013 02:57 GMT
#5385
Damn that was quick, thanks to everyone for pitching in. ddengster nailed what I was confused about, I really was storing pointers to the objects, not the objects themselves. Makes perfect sense now.
On a purely personal note, I'd like to show Yellow the beauty of infinitely repeating Starcraft 2 bunkers. -Boxer
waxypants
Profile Blog Joined September 2009
United States479 Posts
March 15 2013 07:57 GMT
#5386
On March 15 2013 11:57 Orome wrote:
Damn that was quick, thanks to everyone for pitching in. ddengster nailed what I was confused about, I really was storing pointers to the objects, not the objects themselves. Makes perfect sense now.


Even if it did get destroyed upon popping, pointers don't just reassign themselves when the thing they point to is deallocated, and the memory doesn't just disappear. I would expect that the function call would still usually work even if the object was destroyed immediately before.
Frigo
Profile Joined August 2009
Hungary1023 Posts
Last Edited: 2013-03-15 11:24:11
March 15 2013 11:24 GMT
#5387
On March 15 2013 11:48 alwinuz wrote:
You don't want to start a big huf, then what did you just do?
I'll just dump a relevant story: http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html
And you give the answer yourself: there's a difference between micro-optimization at code level, and optimizing the design of the software as a whole. + what Tobberoth said


What's even more sadder that I have read the article and other people did as well and there are walls of comments, that there is even discussion about it, when this should be obvious to everyone with a working brain ;;
http://www.fimfiction.net/user/Treasure_Chest
Blisse
Profile Blog Joined July 2010
Canada3710 Posts
March 15 2013 13:13 GMT
#5388
On March 15 2013 11:48 alwinuz wrote:

Show nested quote +
On March 15 2013 04:17 RoyGBiv_13 wrote:
On March 15 2013 03:53 alwinuz wrote:
I don't think speed matters, it's more a question of what is more readable and maintainable code.
Write easy code first, optimize for speed later (and measure first!).
But is this more readable than the original code? Not sure... personal preference I think.


I don't really want to start a big huff over nothing, but there is a misconception I don't want spread. The idea that an easily maintainable design is a trade off with with code speed is absurd. The better the design, the smaller the code base, more maintainable, readable, and faster it will be. If you find that your code is running slow, then optimizing it will only cause problems in your understanding of the code. This is often why people rewrite programs from scratch, because they tried to optimize something, realized they did the design wrong, and start over.

Optimization should be done out the gate, so that your design pattern will reflect the quickest way to solve the problem, and be easier to understand because of it.


You don't want to start a big huf, then what did you just do?
I'll just dump a relevant story: http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html
And you give the answer yourself: there's a difference between micro-optimization at code level, and optimizing the design of the software as a whole. + what Tobberoth said


Show nested quote +
On March 15 2013 06:44 Blisse wrote:
On March 15 2013 06:37 Tobberoth wrote:
On March 15 2013 06:34 Blisse wrote:

On March 14 2013 23:25 FFGenerations wrote:
Using javascript & html, i have a button on a page and a text box. User inputs a grade number into the text box and presses the button. An alert pops up based on the input, using a simple if statement, telling the user if the entered grade is a merit, pass etc.

+ Show Spoiler +

if(grade!="")
{
if(grade>-1&&grade<40)
{
alert("This is below threshold.")
}
else if(grade>39&&grade<50)
{
alert("This is a third class degree.")
}
else if(grade>49&&grade<60)
{
alert("This is a lower second degree.")
}
else if(grade>59&&grade<70)
{
alert("This is an upper second degree.")
}
else if(grade>69&&grade<101)
{
alert("This is a first class degree.")
}
else
{
alert("Please enter a grade from 0 to 100.")
}
}
else
{
alert("Please enter a grade from 0 to 100.")
}
}


The question is, why do i need to lay out everything within a second if statement?
The first time i wrote it, i had similar to the following:

+ Show Spoiler +


if(grade="")
{
alert("You need to enter a grade")
}
else if(grade>-1&&grade<40)
{
alert("This is below threshold.")
}
else if(grade>39&&grade<50)
{
alert("This is a third class degree.")
}
else if(grade>49&&grade<60)
{
alert("This is a lower second degree.")
}
else if(grade>59&&grade<70)
{
alert("This is an upper second degree.")
}
else if(grade>69&&grade<101)
{
alert("This is a first class degree.")
}
else
{
alert("Please enter a grade from 0 to 100.")
}



however, this kept displaying "This is below threshold." instead of running the if(grade="") part.
My tutor said it might be something to do with the if statements switching from string ("") to int (grade>-1&&grade<40) which is somehow messing it up.

Many thanks



Your code seems to be able to compare integers and strings without regard for the data type.

I think you have to apply a parseInt(grade) after you've validated the grade is a number, before you can perform all these checks. That's what I think I did when I did JS some years ago.

There's no problem comparing strings and numbers in javascript. Try something like:
alert("20" > 5) and you'll get true.


Because "20" as an ASCII value should be greater than 5, at least it would make sense if it were.

"4" > 5 doesn't seem like it would return true, but it probably does here. Again, not a JS person.

And anyways, I don't believe you're suggesting one should compare strings with integers like that. Best practice should always be string with string and int with int.

"4" > 5 actually returns false! (just tested) I didn't know that because I always follow your best practice.




JS, what are you high on. Cool to know, but -.-
There is no one like you in the universe.
Yoshi-
Profile Joined October 2008
Germany10227 Posts
March 15 2013 13:55 GMT
#5389
JS is just very loose with the types, if you compare a string to an int the string will get converted to a number.
AmericanUmlaut
Profile Blog Joined November 2010
Germany2597 Posts
March 15 2013 15:04 GMT
#5390
Types in JS are a bloody nightmare.

typeof(NaN) => "Number"

Yay Javascript.
The frumious Bandersnatch
Tobberoth
Profile Joined August 2010
Sweden6375 Posts
March 15 2013 15:26 GMT
#5391
On March 15 2013 06:44 Blisse wrote:
Show nested quote +
On March 15 2013 06:37 Tobberoth wrote:
On March 15 2013 06:34 Blisse wrote:

On March 14 2013 23:25 FFGenerations wrote:
Using javascript & html, i have a button on a page and a text box. User inputs a grade number into the text box and presses the button. An alert pops up based on the input, using a simple if statement, telling the user if the entered grade is a merit, pass etc.

+ Show Spoiler +

if(grade!="")
{
if(grade>-1&&grade<40)
{
alert("This is below threshold.")
}
else if(grade>39&&grade<50)
{
alert("This is a third class degree.")
}
else if(grade>49&&grade<60)
{
alert("This is a lower second degree.")
}
else if(grade>59&&grade<70)
{
alert("This is an upper second degree.")
}
else if(grade>69&&grade<101)
{
alert("This is a first class degree.")
}
else
{
alert("Please enter a grade from 0 to 100.")
}
}
else
{
alert("Please enter a grade from 0 to 100.")
}
}


The question is, why do i need to lay out everything within a second if statement?
The first time i wrote it, i had similar to the following:

+ Show Spoiler +


if(grade="")
{
alert("You need to enter a grade")
}
else if(grade>-1&&grade<40)
{
alert("This is below threshold.")
}
else if(grade>39&&grade<50)
{
alert("This is a third class degree.")
}
else if(grade>49&&grade<60)
{
alert("This is a lower second degree.")
}
else if(grade>59&&grade<70)
{
alert("This is an upper second degree.")
}
else if(grade>69&&grade<101)
{
alert("This is a first class degree.")
}
else
{
alert("Please enter a grade from 0 to 100.")
}



however, this kept displaying "This is below threshold." instead of running the if(grade="") part.
My tutor said it might be something to do with the if statements switching from string ("") to int (grade>-1&&grade<40) which is somehow messing it up.

Many thanks



Your code seems to be able to compare integers and strings without regard for the data type.

I think you have to apply a parseInt(grade) after you've validated the grade is a number, before you can perform all these checks. That's what I think I did when I did JS some years ago.

There's no problem comparing strings and numbers in javascript. Try something like:
alert("20" > 5) and you'll get true.


Because "20" as an ASCII value should be greater than 5, at least it would make sense if it were.

"4" > 5 doesn't seem like it would return true, but it probably does here. Again, not a JS person.

And anyways, I don't believe you're suggesting one should compare strings with integers like that. Best practice should always be string with string and int with int.

Best practice is one thing, the mechanics of a language something else. JS is very weakly and dynamically typed. If you see this as a weakness of the language, of course you should avoid comparision between types, but the language does support it just fine. I find it's less an issue of "You shouldn't compare strings and integers" because it's fine to do so in JS, it's more along the lines of "What's the reason behind trying to compare a string and an integer, why aren't both integers to begin with?" If there's a good reason for one of the inputs being a string, and there's previous validation in place to make sure it's a number, I see no reason to write extra code to convert it when JS doesn't need you to.
Shield
Profile Blog Joined August 2009
Bulgaria4824 Posts
March 15 2013 16:24 GMT
#5392
On March 16 2013 00:26 Tobberoth wrote:
Show nested quote +
On March 15 2013 06:44 Blisse wrote:
On March 15 2013 06:37 Tobberoth wrote:
On March 15 2013 06:34 Blisse wrote:

On March 14 2013 23:25 FFGenerations wrote:
Using javascript & html, i have a button on a page and a text box. User inputs a grade number into the text box and presses the button. An alert pops up based on the input, using a simple if statement, telling the user if the entered grade is a merit, pass etc.

+ Show Spoiler +

if(grade!="")
{
if(grade>-1&&grade<40)
{
alert("This is below threshold.")
}
else if(grade>39&&grade<50)
{
alert("This is a third class degree.")
}
else if(grade>49&&grade<60)
{
alert("This is a lower second degree.")
}
else if(grade>59&&grade<70)
{
alert("This is an upper second degree.")
}
else if(grade>69&&grade<101)
{
alert("This is a first class degree.")
}
else
{
alert("Please enter a grade from 0 to 100.")
}
}
else
{
alert("Please enter a grade from 0 to 100.")
}
}


The question is, why do i need to lay out everything within a second if statement?
The first time i wrote it, i had similar to the following:

+ Show Spoiler +


if(grade="")
{
alert("You need to enter a grade")
}
else if(grade>-1&&grade<40)
{
alert("This is below threshold.")
}
else if(grade>39&&grade<50)
{
alert("This is a third class degree.")
}
else if(grade>49&&grade<60)
{
alert("This is a lower second degree.")
}
else if(grade>59&&grade<70)
{
alert("This is an upper second degree.")
}
else if(grade>69&&grade<101)
{
alert("This is a first class degree.")
}
else
{
alert("Please enter a grade from 0 to 100.")
}



however, this kept displaying "This is below threshold." instead of running the if(grade="") part.
My tutor said it might be something to do with the if statements switching from string ("") to int (grade>-1&&grade<40) which is somehow messing it up.

Many thanks



Your code seems to be able to compare integers and strings without regard for the data type.

I think you have to apply a parseInt(grade) after you've validated the grade is a number, before you can perform all these checks. That's what I think I did when I did JS some years ago.

There's no problem comparing strings and numbers in javascript. Try something like:
alert("20" > 5) and you'll get true.


Because "20" as an ASCII value should be greater than 5, at least it would make sense if it were.

"4" > 5 doesn't seem like it would return true, but it probably does here. Again, not a JS person.

And anyways, I don't believe you're suggesting one should compare strings with integers like that. Best practice should always be string with string and int with int.

Best practice is one thing, the mechanics of a language something else. JS is very weakly and dynamically typed. If you see this as a weakness of the language, of course you should avoid comparision between types, but the language does support it just fine. I find it's less an issue of "You shouldn't compare strings and integers" because it's fine to do so in JS, it's more along the lines of "What's the reason behind trying to compare a string and an integer, why aren't both integers to begin with?" If there's a good reason for one of the inputs being a string, and there's previous validation in place to make sure it's a number, I see no reason to write extra code to convert it when JS doesn't need you to.


If readability/understanding isn't an issue, then your reasoning sounds fine to me.
mcc
Profile Joined October 2010
Czech Republic4646 Posts
Last Edited: 2013-03-15 16:51:13
March 15 2013 16:43 GMT
#5393
On March 15 2013 06:49 Morfildur wrote:
Show nested quote +
On March 15 2013 03:53 alwinuz wrote:
I don't think speed matters, it's more a question of what is more readable and maintainable code.
Write easy code first, optimize for speed later (and measure first!).
But is this more readable than the original code? Not sure... personal preference I think.


I think it's definitely more readable and maintainable.

There is just one place you have to look at to know where every level begins and ends, you don't have to go through each "else if" to find all the values. If you need to adjust it you instantly know where you have to do it, no need to search through potentially dozens of cases. If you have to add a case, no need to search through all branches to know where it belongs, you can see it in the short list.

Sure, in this case it's a small amount of branches but i had a similar situation with price groups where certain video lengths resulted in different prices and there were twice as many potential values and the previous "if/else if" stuff was far too long. After i changed it to something similar to my code above (in PHP), it was so easy that i was able to copy-paste the list into an email to the product manager and he understood it easily.

I could probably also have written it like this, which is easier to the untrained eye:

var boundaries = new Array();
boundaries["39"] = "";
boundaries["49"] = "third level";
...

Should be in DB anyway

EDIT: by that I mean I agree with your way of coding it. I was more commenting on your story, that it should have been stored in DB and loaded into the structures like the above. Then easy select to show manager the data, and you can change stuff without deploy. But I am exaggerating a bit, in smaller programs/programs not dependent on DB the trade-off is often not worth it.
mcc
Profile Joined October 2010
Czech Republic4646 Posts
March 15 2013 16:46 GMT
#5394
On March 16 2013 00:04 AmericanUmlaut wrote:
Types in JS are a bloody nightmare.

typeof(NaN) => "Number"

Yay Javascript.

Yep, JS type design is terrible shit. Empty string is equivalent to false, who knew Caused me some wasted time yesterday.
enigmaticcam
Profile Blog Joined October 2010
United States280 Posts
Last Edited: 2013-03-15 17:27:28
March 15 2013 16:57 GMT
#5395
Anybody here have any experience with Objective-C? I'm trying to do some C work in it (don't ask me why, it's long winded), and my C is a bit rusty. I can't seem to figure out what I'm doing wrong.

Basically, I have a char array and I'm trying to replace characters. Here's an example:

@implementation BlahViewController {
char *_test;
}

- (void)viewDidLoad {
char test[3] = "ab";
_test = test;

NSString *withoutZ = [NSString stringWithCString:_test encoding:NSASCIIStringEncoding];
NSLog(@"%@", withoutZ);

_test[0] = "z";
NSString *withZ = [NSString stringWithCString:_test encoding:NSASCIIStringEncoding];
NSLog(@"%@", withZ);
}


The result is that withoutZ = "ab", but withZ = "hb". Sometimes the first character in withZ is different from one build to the next. I'm sure it's something simple I'm doing wrong. Can anyone help me out?

Edit: Nevermind, I figured it out. I forgot to put the pointer.
_test[0] = *"z";


But now I'm not sure how to implement that in the way I need to. The above was just an example test for me to make sure I understood how it works, but when I try to implement it, it's not working quite right. Here's what I'm trying to do, simplified:

@implementation CSTGameBoard {
char *_boardKey;
char *_charForNumber;
}

- (id)init {
self = [super init];
if (self) {
char boardKey[33] = "00000000000000000000000000000000";
_boardKey = boardKey;

char charForNumber[11] = "0123456789";
_charForNumber = charForNumber;
}
return self;
}

- (void)updateBoardKeyWithInt:(int)number atCoefficient:(int)coefficient {
_boardKey[coefficient] = _charForNumber[number];
}


I'm writing up my own AI for one of my favorite board games, so optimization is paramount. For a given board position, I need to generate a unique board key that represents the current state of the board. I then convert the key to an NSString object that I use as a key in an NSDictionary to see if I've already evaluated this position before.

Because optimization is so important, I figured it would be much more efficient to use a char index rather than using NSString. Allocating new objects hundreds of thousands of times is not very efficient, right? This way I can limit the times I need to allocate a new NSString object to only when I need it for the dictionary reference.

So I use the charForNumber as a reference to replace characters in the boardKey at any given position with a character that represents a number. I don't do any conversions and it's one simple step. But I can't get it to work. The boardKey is fine when it's initialized, but as soon as I start replacing characters using updateBoardKeyWithInt, it goes wacky and spits out gobbley gunk. I tried to put a pointer before the _charForNumber[number], but then the project fails to compile. Any ideas?
ragz_gt
Profile Blog Joined April 2012
9172 Posts
March 15 2013 17:16 GMT
#5396
On March 14 2013 06:07 supereddie wrote:
Unit tests shouldn't be dependant on eachother - problem solved.


Theoretically yes. But with web pages it's sometimes unavoidable. You can't test stuff in a website if your login fails, or if the server goes down. Test suite runs on a VM for hours and sometime days and all your test fails, but it tells you nothing. Obviously can just let it finish but it's just a waste of resources / time (since email notification is not sent until all tests are completed).

Also it's not always realistic or practical to have complete dependency for integration tests. If you want to test delete an order, then needs to be an order there for you to delete. While you can put the create order code inside delete order test, but in real life it's much easier just have the delete test dependent on create test.
I'm not an otaku, I'm a specialist.
supereddie
Profile Joined March 2011
Netherlands151 Posts
March 15 2013 17:58 GMT
#5397
On March 16 2013 02:16 ragz_gt wrote:
Show nested quote +
On March 14 2013 06:07 supereddie wrote:
Unit tests shouldn't be dependant on eachother - problem solved.


Theoretically yes. But with web pages it's sometimes unavoidable. You can't test stuff in a website if your login fails, or if the server goes down. Test suite runs on a VM for hours and sometime days and all your test fails, but it tells you nothing. Obviously can just let it finish but it's just a waste of resources / time (since email notification is not sent until all tests are completed).

Also it's not always realistic or practical to have complete dependency for integration tests. If you want to test delete an order, then needs to be an order there for you to delete. While you can put the create order code inside delete order test, but in real life it's much easier just have the delete test dependent on create test.

You don't need to log in to be able to do a unit test. You don't need a server up for a unit test. That is the entire point of a unit test: you're testing a very small part of functionality of one class. If you've modelled your application correctly, it shouldn't be any problem to have lots of unit tests.

If needed you can mock/stub various dependencies of the class you're testing.

I can perfectly test a delete without a database; usually there will be a lot of functionality before the actual delete (like validation etc.), which can all be done by unit tests. For the actual deletion you can just use a test-database that you will be re-populating / restoring every time the test runs.

You should also test what happens when you try to delete an order if there is none in the datase. Or if you pass an invalid id.

Remember I'm talking about unit test, not integration tests. Unit tests should be stand-alone, independant tests.
"Do not try to make difficult things possible, but make simple things simple." - David Platt on Software Design
Frigo
Profile Joined August 2009
Hungary1023 Posts
Last Edited: 2013-03-15 19:13:20
March 15 2013 19:08 GMT
#5398
I get the impression he is not talking about unit tests but (UI) functional tests implemented in JUnit. (It is a different matter that he should have a thin UI layer and rely on API testing instead of UI testing.)

Unfortunately functional tests often require special enviroment and application state. That means a programmer has three options when it comes to functional tests:
- Build his application from the start with startup time in mind. Hot config only, no expensive initialization, etc. This is not always achievable due to external components, compatibility reasons, size of data, or simply because hot config would make the application too complex.
- Group his tests together that require the same kind of application state. Contexts should set up and tear down this state. Tests should restore this state after their run. Unfortunately sometimes they don't and thus can cause test interference, both within and outside the same group.
- Just ignore the entire issue, let his tests run forever and watch the astronomical costs.
http://www.fimfiction.net/user/Treasure_Chest
obesechicken13
Profile Blog Joined July 2008
United States10467 Posts
Last Edited: 2013-03-15 20:08:36
March 15 2013 20:08 GMT
#5399
On March 16 2013 04:08 Frigo wrote:
I get the impression he is not talking about unit tests but (UI) functional tests implemented in JUnit. (It is a different matter that he should have a thin UI layer and rely on API testing instead of UI testing.)

Unfortunately functional tests often require special enviroment and application state. That means a programmer has three options when it comes to functional tests:
- Build his application from the start with startup time in mind. Hot config only, no expensive initialization, etc. This is not always achievable due to external components, compatibility reasons, size of data, or simply because hot config would make the application too complex.
- Group his tests together that require the same kind of application state. Contexts should set up and tear down this state. Tests should restore this state after their run. Unfortunately sometimes they don't and thus can cause test interference, both within and outside the same group.
- Just ignore the entire issue, let his tests run forever and watch the astronomical costs.

I think functional tests are supposed to be independent too but in my experience they are not. Functional testing deletes in a database without a database does not mimic live environments. So in this sense you are right.

So you get tests that depend on each other.


I do want to note that the email at the end can still be sent though. You just have to make it send its results at a time when you think your functional tests would have already run.
I think in our modern age technology has evolved to become more addictive. The things that don't give us pleasure aren't used as much. Work was never meant to be fun, but doing it makes us happier in the long run.
tec27
Profile Blog Joined June 2004
United States3715 Posts
Last Edited: 2013-03-16 21:01:25
March 16 2013 03:33 GMT
#5400
On March 16 2013 01:46 mcc wrote:
Show nested quote +
On March 16 2013 00:04 AmericanUmlaut wrote:
Types in JS are a bloody nightmare.

typeof(NaN) => "Number"

Yay Javascript.

Yep, JS type design is terrible shit. Empty string is equivalent to false, who knew Caused me some wasted time yesterday.

Empty string does not equal false, it is merely a falsy value. Falsy values are very useful, and greatly increase the expressiveness of the language imo. I've programmed in JS a lot, and I can tell you that if you're actually checking if a variable equals or does not equal a falsy value, you are generally not doing the right thing anyway. But just in case, I'd recommend running your code through http://jshint.com (there's a command-line version as well if you'd like to lint through your editor/console) and it'll catch cases where you compare against falsy values without using !== or ===.

JS has some weird idiosyncracies, but its type system isn't one of them and makes for a very expressive and useful language.
Can you jam with the console cowboys in cyberspace?
Prev 1 268 269 270 271 272 1032 Next
Please log in or register to reply.
Live Events Refresh
Next event in 3h 34m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
ProTech124
Has 23
StarCraft: Brood War
Britney 2193
Leta 167
Dewaltoss 118
ggaemo 33
yabsab 33
Stork 30
Bale 21
League of Legends
JimRising 653
Reynor98
Counter-Strike
ceh9431
Other Games
Happy368
Livibee172
Maynarde126
Mew2King114
Organizations
Dota 2
PGL Dota 2 - Main Stream6304
Other Games
gamesdonequick485
StarCraft: Brood War
Afreeca ASL 371
[ Show 13 non-featured ]
StarCraft 2
• Berry_CruncH45
• mYiSmile19
• Letter143
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• Migwel
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• lizZardDota2156
League of Legends
• Stunt567
Upcoming Events
Kung Fu Cup
3h 34m
The PondCast
1d 2h
Replay Cast
1d 16h
Korean StarCraft League
2 days
CranKy Ducklings
3 days
GSL
4 days
Yamato Cup
4 days
Replay Cast
4 days
Afreeca Starleague
5 days
WardiTV Weekly
5 days
[ Show More ]
Sparkling Tuna Cup
6 days
Afreeca Starleague
6 days
PiGosaur Cup
6 days
Liquipedia Results

Completed

Super Anchor Qualifying S3
Blizzard Classic Cup 2026
Big Dog Cup 2026 Div 1

Ongoing

ASL Season 22
CSL 2026 AUTUMN (S22)
Acropolis #5
Acropolis #5 - GSA
Calamity Invitational
Logitech G Play Connect 2026
SL StarSeries Fall 2026
FISSURE Playground #3
BLAST Open Fall 2026
Esports World Cup 2026
BLAST Bounty Summer 2026
BLAST Bounty Summer Qual
Stake Ranked Episode 3
XSE Pro League 2026

Upcoming

Acropolis #5 - GSB
Acropolis #5 - GSC
BSL Season 23
SC4ALL II: Brood War
BSL 23: Non-Korean Championship
HSC XXX
Stellar Fest 2: Lunar Cup
SC4ALL II: StarCraft II
Kung Fu Cup 2026 Grand Finals
RSL Offline Finals
Custodian Cup
Copium Cup
PGL Major Singapore 2026
Stake Ranked Episode 6
BLAST Rivals Fall 2026
IEM Beijing 2026
Stake Ranked Episode 5
PGL Masters Bucharest 2026
1win Private Club #2
Thunderpick World Champ. '26
ESL Pro League Season 24
Stake Ranked Episode 4
1win Private Club #1
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2026 TLnet. All Rights Reserved.