• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 19:57
CEST 01:57
KST 08:57
  • 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
Code S Season 1 - RO8 Preview3[ASL21] Ro8 Preview Pt2: Progenitors8Code S Season 1 - RO12 Group A: Rogue, Percival, Solar, Zoun13[ASL21] Ro8 Preview Pt1: Inheritors16[ASL21] Ro16 Preview Pt2: All Star10
Community News
Maestros of The Game 2 announcement and schedule !6Weekly Cups (April 27-May 4): Clem takes triple0RSL Revival: Season 5 - Qualifiers and Main Event12Code S Season 1 (2026) - RO12 Results12026 GSL Season 1 Qualifiers25
StarCraft 2
General
Code S Season 1 - RO8 Preview Behind the Blue - Team Liquid History Book Weekly Cups (April 27-May 4): Clem takes triple Blizzard Classic Cup @ BlizzCon 2026 - $100k prize pool Code S Season 1 (2026) - RO12 Results
Tourneys
GSL Code S Season 1 (2026) Maestros of The Game 2 announcement and schedule ! Sea Duckling Open (Global, Bronze-Diamond) RSL Revival: Season 5 - Qualifiers and Main Event Sparkling Tuna Cup - Weekly Open Tournament
Strategy
Custom Maps
[D]RTS in all its shapes and glory <3 [A] Nemrods 1/4 players
External Content
Mutation # 524 Death and Taxes The PondCast: SC2 News & Results Mutation # 523 Firewall Mutation # 522 Flip My Base
Brood War
General
Do we have a pimpest plays list? BGH Auto Balance -> http://bghmmr.eu/ (Spoiler) Asl ro8 D winner interview BW General Discussion AI Question
Tourneys
[ASL21] Ro8 Day 4 Small VOD Thread 2.0 [BSL22] RO16 Group Stage - 02 - 10 May [ASL21] Ro8 Day 3
Strategy
Simple Questions, Simple Answers Fighting Spirit mining rates What's the deal with APM & what's its true value Any training maps people recommend?
Other Games
General Games
Stormgate/Frost Giant Megathread OutLive 25 (RTS Game) Nintendo Switch Thread Dawn of War IV Daigo vs Menard Best of 10
Dota 2
The Story of Wings Gaming
League of Legends
G2 just beat GenG in First stand
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
Vanilla Mini Mafia Mafia Game Mode Feedback/Ideas TL Mafia Community Thread Five o'clock TL Mafia
Community
General
European Politico-economics QA Mega-thread US Politics Mega-thread The Letting Off Steam Thread Russo-Ukrainian War Thread 3D technology/software discussion
Fan Clubs
The IdrA Fan Club
Media & Entertainment
Anime Discussion Thread [Manga] One Piece [Req][Books] Good Fantasy/SciFi books
Sports
2024 - 2026 Football Thread McBoner: A hockey love story Formula 1 Discussion
World Cup 2022
Tech Support
streaming software Strange computer issues (software) [G] How to Block Livestream Ads
TL Community
The Automated Ban List
Blogs
How EEG Data Can Predict Gam…
TrAiDoS
ramps on octagon
StaticNine
Funny Nicknames
LUCKY_NOOB
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1930 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
Germany2594 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 States3702 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 3m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
SpeCial 119
StarCraft: Brood War
GuemChi 3491
Artosis 661
NaDa 17
Terrorterran 12
Dota 2
monkeys_forever333
Other Games
summit1g7913
tarik_tv6206
Doublelift2626
Liquid`RaSZi1551
shahzam550
syndereN164
JimRising 157
ViBE53
Mew2King34
Organizations
Other Games
gamesdonequick2039
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
[ Show 15 non-featured ]
StarCraft 2
• musti20045 29
• Adnapsc2 14
• CranKy Ducklings SOOP7
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• imaqtpie2002
Other Games
• Scarra1638
Upcoming Events
Replay Cast
3m
CranKy Ducklings12
Escore
10h 3m
The PondCast
10h 3m
WardiTV Invitational
11h 3m
Zoun vs Ryung
Lambo vs ShoWTimE
Big Brain Bouts
16h 3m
Fjant vs Bly
Serral vs Shameless
OSC
22h 3m
Replay Cast
1d
CranKy Ducklings
1d 10h
RSL Revival
1d 10h
SHIN vs Bunny
ByuN vs Shameless
WardiTV Invitational
1d 11h
Krystianer vs TriGGeR
Cure vs Rogue
[ Show More ]
uThermal 2v2 Circuit
1d 15h
BSL
1d 19h
Artosis vs TerrOr
spx vs StRyKeR
Replay Cast
2 days
Sparkling Tuna Cup
2 days
RSL Revival
2 days
Cure vs Zoun
Clem vs Lambo
WardiTV Invitational
2 days
BSL
2 days
Dewalt vs DragOn
Aether vs Jimin
GSL
3 days
Afreeca Starleague
3 days
Soma vs Leta
Wardi Open
3 days
Monday Night Weeklies
3 days
OSC
4 days
CranKy Ducklings
4 days
Afreeca Starleague
4 days
Light vs Flash
Replay Cast
5 days
Replay Cast
6 days
The PondCast
6 days
Liquipedia Results

Completed

Proleague 2026-05-05
WardiTV TLMC #16
Nations Cup 2026

Ongoing

BSL Season 22
ASL Season 21
CSL 2026 SPRING (S20)
IPSL Spring 2026
KCM Race Survival 2026 Season 2
Acropolis #4
SCTL 2026 Spring
RSL Revival: Season 5
2026 GSL S1
BLAST Rivals Spring 2026
IEM Rio 2026
PGL Bucharest 2026
Stake Ranked Episode 1
BLAST Open Spring 2026
ESL Pro League S23 Finals
ESL Pro League S23 Stage 1&2
PGL Cluj-Napoca 2026

Upcoming

Escore Tournament S2: W6
KK 2v2 League Season 1
BSL 22 Non-Korean Championship
YSL S3
Escore Tournament S2: W7
Escore Tournament S2: W8
CSLAN 4
Kung Fu Cup 2026 Grand Finals
HSC XXIX
uThermal 2v2 2026 Main Event
Maestros of the Game 2
2026 GSL S2
Stake Ranked Episode 3
XSE Pro League 2026
IEM Cologne Major 2026
Stake Ranked Episode 2
CS Asia Championships 2026
IEM Atlanta 2026
Asian Champions League 2026
PGL Astana 2026
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.