• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 12:45
CET 18:45
KST 02:45
  • 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
RSL Season 3 - Playoffs Preview0RSL Season 3 - RO16 Groups C & D Preview0RSL Season 3 - RO16 Groups A & B Preview2TL.net Map Contest #21: Winners12Intel X Team Liquid Seoul event: Showmatches and Meet the Pros10
Community News
Weekly Cups (Nov 24-30): MaxPax, Clem, herO win2BGE Stara Zagora 2026 announced15[BSL21] Ro.16 Group Stage (C->B->A->D)4Weekly Cups (Nov 17-23): Solar, MaxPax, Clem win3RSL Season 3: RO16 results & RO8 bracket13
StarCraft 2
General
Chinese SC2 server to reopen; live all-star event in Hangzhou Maestros of the Game: Live Finals Preview (RO4) BGE Stara Zagora 2026 announced Weekly Cups (Nov 24-30): MaxPax, Clem, herO win SC2 Proleague Discontinued; SKT, KT, SGK, CJ disband
Tourneys
Sparkling Tuna Cup - Weekly Open Tournament RSL Offline Finals Info - Dec 13 and 14! StarCraft Evolution League (SC Evo Biweekly) RSL Offline FInals Sea Duckling Open (Global, Bronze-Diamond)
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 502 Negative Reinforcement Mutation # 501 Price of Progress Mutation # 500 Fright night Mutation # 499 Chilling Adaptation
Brood War
General
BW General Discussion Which season is the best in ASL? Data analysis on 70 million replays BGH Auto Balance -> http://bghmmr.eu/ [ASL20] Ask the mapmakers — Drop your questions
Tourneys
[Megathread] Daily Proleagues [BSL21] RO16 Group D - Sunday 21:00 CET [BSL21] RO16 Group A - Saturday 21:00 CET [BSL21] RO16 Group B - Sunday 21:00 CET
Strategy
Current Meta Game Theory for Starcraft How to stay on top of macro? PvZ map balance
Other Games
General Games
Nintendo Switch Thread Stormgate/Frost Giant Megathread ZeroSpace Megathread The Perfect Game Path of Exile
Dota 2
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 Heroes of StarCraft mini-set
TL Mafia
Mafia Game Mode Feedback/Ideas TL Mafia Community Thread
Community
General
US Politics Mega-thread Russo-Ukrainian War Thread Things Aren’t Peaceful in Palestine The Big Programming Thread Artificial Intelligence Thread
Fan Clubs
White-Ra Fan Club
Media & Entertainment
[Manga] One Piece Movie Discussion! Anime Discussion Thread
Sports
2024 - 2026 Football Thread Formula 1 Discussion NBA General Discussion
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
Where to ask questions and add stream? The Automated Ban List
Blogs
Physical Exertion During Gam…
TrAiDoS
James Bond movies ranking - pa…
Topin
Thanks for the RSL
Hildegard
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1373 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
Germany2581 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
OSC
16:00
OSC Elite Rising Star #17
Babymarine vs MindelVKLIVE!
ForJumy vs TBD
Shameless vs Percival
SteadfastSC147
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
mouzHeroMarine 602
Lowko484
SteadfastSC 147
ProTech128
MindelVK 50
Codebar 22
StarCraft: Brood War
Britney 24474
Calm 3476
Shuttle 729
EffOrt 534
Larva 371
Rush 220
firebathero 150
BeSt 126
Dewaltoss 96
PianO 63
[ Show more ]
yabsab 36
Aegong 20
soO 16
Terrorterran 14
scan(afreeca) 14
HiyA 10
SilentControl 9
JulyZerg 6
NaDa 6
Dota 2
Gorgc6897
Dendi975
420jenkins321
XcaliburYe178
Counter-Strike
fl0m4837
zeus420
chrisJcsgo52
minikerr19
Heroes of the Storm
Khaldor169
Other Games
Grubby3883
ArmadaUGS110
Livibee73
KnowMe62
Trikslyr60
Mew2King58
QueenE55
Organizations
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 16 non-featured ]
StarCraft 2
• poizon28 16
• Reevou 8
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• FirePhoenix2
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• C_a_k_e 2719
• WagamamaTV631
Other Games
• Shiphtur170
Upcoming Events
Replay Cast
6h 15m
Korean StarCraft League
1d 9h
CranKy Ducklings
1d 16h
WardiTV 2025
1d 18h
SC Evo League
1d 18h
BSL 21
2 days
Sziky vs OyAji
Gypsy vs eOnzErG
OSC
2 days
Solar vs Creator
ByuN vs Gerald
Percival vs Babymarine
Moja vs Krystianer
EnDerr vs ForJumy
sebesdes vs Nicoract
Sparkling Tuna Cup
2 days
WardiTV 2025
2 days
OSC
2 days
[ Show More ]
BSL 21
3 days
Bonyth vs StRyKeR
Tarson vs Dandy
Replay Cast
3 days
Wardi Open
3 days
StarCraft2.fi
3 days
Monday Night Weeklies
3 days
Replay Cast
4 days
WardiTV 2025
4 days
StarCraft2.fi
4 days
PiGosaur Monday
5 days
StarCraft2.fi
5 days
Tenacious Turtle Tussle
6 days
The PondCast
6 days
WardiTV 2025
6 days
StarCraft2.fi
6 days
Liquipedia Results

Completed

Proleague 2025-11-30
RSL Revival: Season 3
Light HT

Ongoing

C-Race Season 1
IPSL Winter 2025-26
KCM Race Survival 2025 Season 4
YSL S2
BSL Season 21
CSCL: Masked Kings S3
Slon Tour Season 2
Acropolis #4 - TS3
META Madness #9
SL Budapest Major 2025
ESL Impact League Season 8
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 2025
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
StarSeries Fall 2025
FISSURE Playground #2

Upcoming

BSL 21 Non-Korean Championship
Acropolis #4
IPSL Spring 2026
Bellum Gens Elite Stara Zagora 2026
HSC XXVIII
RSL Offline Finals
WardiTV 2025
Kuram Kup
PGL Cluj-Napoca 2026
IEM Kraków 2026
BLAST Bounty Winter 2026
BLAST Bounty Winter Qual
eXTREMESLAND 2025
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 © 2025 TLnet. All Rights Reserved.