• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 09:04
CEST 15:04
KST 22:04
  • 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
Serral wins HomeStory Cup 2914Serral wins Maestros of the Game 243ByuL, and the Limitations of Standard Play3Team Liquid Map Contest #22: Results and Winners7Code S Season 2 (2026): RO4 and Finals Preview12
Community News
ZeroSpace Early Access is Now Live!7Weekly Cups (July 13-19): Terran & Protoss rise; Zerg falters2Balance hotfix patch 5.0.16b (July 16)70Reynor: GSL Loss Wasn't About Preparation Format16[IPSL] Spring 2026 Grand Finals - This Weekend!18
StarCraft 2
General
Balance hotfix patch 5.0.16b (July 16) Weekly Cups (July 13-19): Terran & Protoss rise; Zerg falters How would you feel about frequent/monthly balance patches for SC2? Clem: "I don't have that much hope in Blizzard" [D] Wireframe Casting Removed
Tourneys
RSL Revival: Season 6 - Qualifiers and Main Event Master Swan Open (Global Bronze-Master 2) WardiTV Summer Cup 2026 GSL CK #5 Race War HomeStory Cup 29
Strategy
[G] Having the right mentality to improve
Custom Maps
New Map Maker - Looking for Advice - Love or Hate Work In Progress Melee Maps [D]RTS in all its shapes and glory <3
External Content
Mutation # 535 Assembly of Vengeance The PondCast: SC2 News & Results Mutation # 534 Burning Evacuation Mutation # 533 Die Together
Brood War
General
HORROR STARCRAFT MOVIE BGH Auto Balance -> http://bghmmr.eu/ How Famous was FlaSh before his Debut? BW General Discussion screpdb: new Starcraft reporting tool
Tourneys
[Megathread] Daily Proleagues [IPSL] Spring 2026 Grand Finals - This Weekend! Escore Tournament - Season 3 Small VOD Thread 2.0
Strategy
Simple Questions, Simple Answers PvT advise for noobs Fighting Spirit mining rates Creating a full chart of Zerg builds
Other Games
General Games
ZeroSpace Early Access is Now Live! ZeroSpace at Steam NextFest - Last free demo Path of Exile Nintendo Switch Thread Stormgate/Frost Giant Megathread
Dota 2
Looking for a Dota Mentor Official 'what is Dota anymore' discussion
League of Legends
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug
TL Mafia
TL Mafia Power Rank NeO.D_StephenKing vs This Guy From 1 Million Dance TL Mafia Community Thread Vanilla Mini Mafia
Community
General
Russo-Ukrainian War Thread US Politics Mega-thread How to buy a book - shipping from Korea to Europe The Games Industry And ATVI UK Politics Mega-thread
Fan Clubs
The IdrA Fan Club The HerO Fan Club!
Media & Entertainment
Movie Discussion! Anime Discussion Thread [Req][Books] Good Fantasy/SciFi books Series you have seen recently...
Sports
2024 - 2026 Football Thread TeamLiquid Health and Fitness Initiative For 2023 Formula 1 Discussion MLB/Baseball 2023 McBoner: A hockey love story
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread Simple Questions Simple Answers FPS when play League Of Legend on laptop
TL Community
Northern Ireland Global Starcraft The Automated Ban List
Blogs
Hello guys!
LIN1s
Role of Gaming on Mental Hea…
TrAiDoS
ASL S22 English Commentary…
namkraft
Poker (part 2)
Nebuchad
An Exploration of th…
waywardstrategy
ramps on octagon
StaticNine
Customize Sidebar...

Website Feedback

Closed Threads



Active: 3820 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 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
WardiTV Summer Champion…
12:05
Summer Cup Group B
WardiTV622
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
ProTech81
SHIN 39
Livibee 20
StarCraft: Brood War
Calm 6716
Bisu 2473
Shuttle 1911
Jaedong 1207
Soma 431
Hyuk 400
firebathero 354
Mini 325
Light 305
Larva 250
[ Show more ]
Stork 248
Soulkey 240
actioN 169
ggaemo 159
hero 157
Snow 144
Dewaltoss 135
Hyun 124
Rush 115
Mong 107
ZerO 85
Pusan 79
Sharp 73
Killer 46
Free 41
soO 38
ToSsGirL 37
sorry 30
JYJ 29
Bale 24
HiyA 23
JulyZerg 20
910 16
Hm[arnc] 15
Sexy 13
Movie 13
Barracks 13
Sacsri 13
IntoTheRainbow 12
Noble 11
zelot 10
Terrorterran 6
GoRush 6
Icarus 5
ajuk12(nOOB) 5
Rock 1
Dota 2
Dendi1179
qojqva504
XcaliburYe280
syndereN127
League of Legends
KnowMe31
Counter-Strike
fl0m2536
x6flipin558
byalli497
Other Games
FrodaN3579
singsing2545
B2W.Neo738
Lowko495
hiko478
uThermal414
crisheroes257
OGKoka 235
DeMusliM208
Harstem148
Liquid`LucifroN126
CosmosSc2 36
ArmadaUGS33
Trikslyr23
ZerO(Twitch)20
Liquid`VortiX15
Organizations
Other Games
gamesdonequick1112
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
[ Show 12 non-featured ]
StarCraft 2
• StrangeGG 64
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• TFBlade903
Upcoming Events
PiGosaur Cup
10h 56m
The PondCast
20h 56m
Kung Fu Cup
21h 56m
OSC
1d 10h
CrankTV Team League
1d 21h
Replay Cast
2 days
CrankTV Team League
2 days
Korean StarCraft League
3 days
Afreeca Starleague
3 days
RSL Revival
3 days
Clem vs ByuN
Serral vs SHIN
[ Show More ]
Online Event
4 days
Replay Cast
4 days
RSL Revival
4 days
herO vs Solar
Rogue vs Lambo
WardiTV Weekly
5 days
Sparkling Tuna Cup
6 days
Liquipedia Results

Completed

Acropolis #4
HSC XXIX
Eternal Conflict S2 E3

Ongoing

CSL 2026 Summer (S21)
KCM Race Survival 2026 Season 3
RSL Revival: Season 6
CranK Gathers Season 4: BW vs SC2 Team League
SCTL 2026 Spring
BLAST Bounty Summer Qual
Stake Ranked Episode 3
XSE Pro League 2026
IEM Cologne Major 2026
Stake Ranked Episode 2
CS Asia Championships 2026
Asian Champions League 2026
IEM Atlanta 2026
PGL Astana 2026

Upcoming

Escore Tournament S3: W4
ASL S22 SEASON OPEN Day 2
Escore Tournament S3: W5
CSLAN 4
Blizzard Classic Cup 2026
HSC XXX
SC4ALL II: StarCraft II
Kung Fu Cup 2026 Grand Finals
Light Tournament 2026
Eternal Conflict S2 Finale
ESL Pro League Season 24
Stake Ranked Episode 4
Logitech G Connect 2026
SL StarSeries Fall 2026
FISSURE Playground #5
BLAST Open Fall 2026
Esports World Cup 2026
BLAST Bounty Summer 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.