• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 14:08
CEST 20:08
KST 03:08
  • 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
[ASL19] Finals Recap: Standing Tall9HomeStory Cup 27 - Info & Preview18Classic wins Code S Season 2 (2025)16Code S RO4 & Finals Preview: herO, Rogue, Classic, GuMiho0TL Team Map Contest #5: Presented by Monster Energy6
Community News
Flash Announces Hiatus From ASL50Weekly Cups (June 23-29): Reynor in world title form?12FEL Cracov 2025 (July 27) - $8000 live event16Esports World Cup 2025 - Final Player Roster16Weekly Cups (June 16-22): Clem strikes back1
StarCraft 2
General
The SCII GOAT: A statistical Evaluation The GOAT ranking of GOAT rankings How does the number of casters affect your enjoyment of esports? Statistics for vetoed/disliked maps Esports World Cup 2025 - Final Player Roster
Tourneys
Master Swan Open (Global Bronze-Master 2) RSL: Revival, a new crowdfunded tournament series [GSL 2025] Code S: Season 2 - Semi Finals & Finals $5,100+ SEL Season 2 Championship (SC: Evo) FEL Cracov 2025 (July 27) - $8000 live event
Strategy
How did i lose this ZvP, whats the proper response Simple Questions Simple Answers
Custom Maps
[UMS] Zillion Zerglings
External Content
Mutation # 480 Moths to the Flame Mutation # 479 Worn Out Welcome Mutation # 478 Instant Karma Mutation # 477 Slow and Steady
Brood War
General
BGH Auto Balance -> http://bghmmr.eu/ Player “Jedi” cheat on CSL Unit and Spell Similarities Help: rep cant save Flash Announces Hiatus From ASL
Tourneys
[Megathread] Daily Proleagues [BSL20] Grand Finals - Sunday 20:00 CET Small VOD Thread 2.0 [BSL20] GosuLeague RO16 - Tue & Wed 20:00+CET
Strategy
Simple Questions, Simple Answers I am doing this better than progamers do.
Other Games
General Games
Stormgate/Frost Giant Megathread Nintendo Switch Thread Path of Exile What do you want from future RTS games? Beyond All Reason
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
Heroes of StarCraft mini-set
TL Mafia
TL Mafia Community Thread Vanilla Mini Mafia
Community
General
US Politics Mega-thread Things Aren’t Peaceful in Palestine Russo-Ukrainian War Thread Trading/Investing Thread The Games Industry And ATVI
Fan Clubs
SKT1 Classic Fan Club! Maru Fan Club
Media & Entertainment
Anime Discussion Thread [Manga] One Piece [\m/] Heavy Metal Thread
Sports
Formula 1 Discussion 2024 - 2025 Football Thread NBA General Discussion TeamLiquid Health and Fitness Initiative For 2023 NHL Playoffs 2024
World Cup 2022
Tech Support
Computer Build, Upgrade & Buying Resource Thread
TL Community
Blogs
Culture Clash in Video Games…
TrAiDoS
from making sc maps to makin…
Husyelt
Blog #2
tankgirl
StarCraft improvement
iopq
Trip to the Zoo
micronesia
Customize Sidebar...

Website Feedback

Closed Threads



Active: 761 users

The Big Programming Thread - Page 766

Forum Index > General Forum
Post a Reply
Prev 1 764 765 766 767 768 1031 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.
solidbebe
Profile Blog Joined November 2010
Netherlands4921 Posts
Last Edited: 2016-09-23 17:25:19
September 23 2016 17:23 GMT
#15301
Thats a constructor which creates an instance of 'class' and initializes 'variable' with whatever value it was passed in the constructor call.

rereading im not sure what your qeustion is, but if you're wondering, that will compile and work correctly. In fact, its a common style.
That's the 2nd time in a week I've seen someone sig a quote from this GD and I have never witnessed a sig quote happen in my TL history ever before. -Najda
Blitzkrieg0
Profile Blog Joined August 2010
United States13132 Posts
Last Edited: 2016-09-23 17:53:26
September 23 2016 17:25 GMT
#15302
On September 24 2016 02:21 travis wrote:
What happens if my class has a variable:

class {

int variable;

//and then the constructor takes a parameter with the same variable name and does this:

class(int variable){

this.variable = variable;


It sets the field in the class to value of the parameter passed to the method. You're calling this.variable to specify that you want the variable in a different scope than the method. The variable without this declaration is assumed to be in the method scope.

** I'll try to go a bit deeper and explain this better:

public class Box {

private int id;
private String name;

private static int boxId;

static {
boxId = 0;
}

public Box(String name) {
id = Box.getBoxId();
this.name = name;
}

public static int getBoxId() {
int ret = Box.boxId;
boxId++;
return ret;
}

public void setId(int id) {
this.id = id;
}
}


So given the previous bit of code, I have a class with a couple fields. In the constructor for my box object, I have a variable called id. There is not an id variable in the scope of the constructor so its assumed that I am referencing the id field of the object. In the setId method you'll notice that I have a parameter called id so I call this.id to specify to the compiler that I want the id variable in this objects scope instead of the method.
I'll always be your shadow and veil your eyes from states of ain soph aur.
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
September 23 2016 17:34 GMT
#15303
I guess my question was kind of like

when I do this.variable = variable;

how does it know that I am talking about the parameter that was passed, or if I was talking about the uninitialized variable.

I guess the answer is, "it just does" ?

(so mainly I was making sure this does in fact work)
Acrofales
Profile Joined August 2010
Spain17970 Posts
September 23 2016 17:41 GMT
#15304
On September 24 2016 02:34 travis wrote:
I guess my question was kind of like

when I do this.variable = variable;

how does it know that I am talking about the parameter that was passed, or if I was talking about the uninitialized variable.

I guess the answer is, "it just does" ?

(so mainly I was making sure this does in fact work)

It's not "it just does". It's about scope, as the answer explained. If you don't understand scopes, it's something you have to read up on. It's a very important part of almost all programming languages.
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
September 23 2016 17:48 GMT
#15305
ok, I didn't answer the question in a way that really gets to the root of what I am wondering about, since I used the this keyword


I understand scope. I don't think my question is about scope

if this was my program

public class myclass {

int number = 7;
int number2;

myclass(int number){

this.number2 = number;

}


then what happens
Blitzkrieg0
Profile Blog Joined August 2010
United States13132 Posts
September 23 2016 17:52 GMT
#15306
I edited my previous post with a better explanation of scope if that helps.
I'll always be your shadow and veil your eyes from states of ain soph aur.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
Last Edited: 2016-09-23 17:57:37
September 23 2016 17:54 GMT
#15307
On September 24 2016 02:34 travis wrote:
I guess my question was kind of like

when I do this.variable = variable;

how does it know that I am talking about the parameter that was passed, or if I was talking about the uninitialized variable.

I guess the answer is, "it just does" ?

(so mainly I was making sure this does in fact work)

The field "variable" is in object scope, the constructor parameter "variable" is in method scope. Relative to each other, the field is in the outer scope and the parameter is in the inner scope (think Matryoshka doll). Variables with the same name in an inner scope "hide" or "shadow" variables in outer scopes. So whenever you write just "variable", you will use the one closest to your current scope. That's the parameter if you're inside the constructor. If you write "this.variable", it will always look for a variable at object scope. This allows you to access the otherwise hidden field.

Remember that part recently where we couldn't find the reason for the null reference exception and then it turned out you just had to delete the type declaration "ArrayList<FoundTerm>"? That was exactly because with the type in front of the variable name you were declaring a new variable that hid one with the same name at object scope that you actually wanted to use instead.

I'm not a big fan of using hiding like that in constructors because it can introduce hard to spot errors. In some languages it is common practice to prefix variables at object scope, for example with an "m" (often in C++) or an underscore (C#). That way you can still use the plain name for stuff at the method scope, most commonly in the constructor.

EDIT: I wrote "class scope" before when I think it should actually be "object scope". Class scope should be static stuff only, while object scope is variables that are unique to each instance of a class.
If you have a good reason to disagree with the above, please tell me. Thank you.
Acrofales
Profile Joined August 2010
Spain17970 Posts
September 23 2016 18:01 GMT
#15308
On September 24 2016 02:48 travis wrote:
ok, I didn't answer the question in a way that really gets to the root of what I am wondering about, since I used the this keyword


I understand scope. I don't think my question is about scope

if this was my program

public class myclass {

int number = 7;
int number2;

myclass(int number){

this.number2 = number;

}


then what happens


You get scolded for using horrid syntax, and told to use proper builder patterns instead. But it's about the order of variable assignment. It works as you'd expect. Upon calling the constructor, the first act is to call the super constructor. If you don't do this explicitly, it is done implicitly. This creates the object you are constructing, and initializes your global variables. After that it runs your constructor, and changes the value of variable "number2" to the parameter you passed.
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
September 23 2016 18:03 GMT
#15309
Okay thanks all, so I guess it is a scope issue

and that the lesson is that when variables have the same name, the more local variable takes precedence?
Manit0u
Profile Blog Joined August 2004
Poland17243 Posts
Last Edited: 2016-09-23 19:52:27
September 23 2016 19:51 GMT
#15310
On September 24 2016 03:03 travis wrote:
Okay thanks all, so I guess it is a scope issue

and that the lesson is that when variables have the same name, the more local variable takes precedence?


A common mistake I see people make (example is from PHP):


$i = 7;

foreach ($somevar as $i) {
// do stuff
// $i declared before loop is overriden with each iteration
}

// $i is now whatever the last element of the iterable $somevar was


Also, I don't think you should be declaring classes within classes...
Time is precious. Waste it wisely.
Blisse
Profile Blog Joined July 2010
Canada3710 Posts
Last Edited: 2016-09-23 19:59:37
September 23 2016 19:59 GMT
#15311
On September 24 2016 03:03 travis wrote:
Okay thanks all, so I guess it is a scope issue

and that the lesson is that when variables have the same name, the more local variable takes precedence?


I would say it depends on the language? I wouldn't say "more local" though, I think "closest in scope" is clearer, but maybe "more local" is easier to understand.

See if these make sense to you.

http://stackoverflow.com/questions/2804880/in-c-what-is-the-scope-resolution-order-of-precedence-for-shadowed-variab

Behind the scenes, a compiler (preprocessor? one of those steps) (usually?) mangles the name of (all?) variables so it doesn't actually see your variable name. They then use the language rules to deduce which ones to call.

http://stackoverflow.com/questions/22067562/how-c-handles-the-same-variable-name-along-different-scopes
There is no one like you in the universe.
Acrofales
Profile Joined August 2010
Spain17970 Posts
September 23 2016 22:23 GMT
#15312
On September 24 2016 04:51 Manit0u wrote:
Show nested quote +
On September 24 2016 03:03 travis wrote:
Okay thanks all, so I guess it is a scope issue

and that the lesson is that when variables have the same name, the more local variable takes precedence?


A common mistake I see people make (example is from PHP):


$i = 7;

foreach ($somevar as $i) {
// do stuff
// $i declared before loop is overriden with each iteration
}

// $i is now whatever the last element of the iterable $somevar was


Also, I don't think you should be declaring classes within classes...

Not necessarily wrong to declare nested classes. I agree that it's fairly advanced, though, and as a beginner you are better off not doing that.
RoomOfMush
Profile Joined March 2015
1296 Posts
Last Edited: 2016-09-23 23:09:09
September 23 2016 23:07 GMT
#15313
On September 24 2016 02:54 spinesheath wrote:
I'm not a big fan of using hiding like that in constructors because it can introduce hard to spot errors. In some languages it is common practice to prefix variables at object scope, for example with an "m" (often in C++) or an underscore (C#). That way you can still use the plain name for stuff at the method scope, most commonly in the constructor.

Although I am not a big fan of naming parameters the same as fields either, it must be noted that todays IDE's are more than capable of detecting these kinds of bugs and generating a warning. I know for a fact that Eclipse will warn you if you assign a parameter to itself.
Birdie
Profile Blog Joined August 2007
New Zealand4438 Posts
September 23 2016 23:08 GMT
#15314
On September 24 2016 08:07 RoomOfMush wrote:
Show nested quote +
On September 24 2016 02:54 spinesheath wrote:
I'm not a big fan of using hiding like that in constructors because it can introduce hard to spot errors. In some languages it is common practice to prefix variables at object scope, for example with an "m" (often in C++) or an underscore (C#). That way you can still use the plain name for stuff at the method scope, most commonly in the constructor.

Although I am not a big fan of naming parameters equal to fields either, it must be noted that todays IDE's are more than capable of detecting these kinds of bugs and generating a warning. I know for a fact that Eclipse will warn you if you assign a parameter to itself.

Correct me if I'm wrong but I think the issue is more the readability of the code, not the compilability. If it's not immediately clear which of two variables is being referenced, then time is wasted on the main work of coding (which is reading).
Red classic | A butterfly dreamed he was Zhuangzi | 4.5k, heading to 5k as support!
RoomOfMush
Profile Joined March 2015
1296 Posts
Last Edited: 2016-09-23 23:11:51
September 23 2016 23:10 GMT
#15315
On September 24 2016 08:08 Birdie wrote:
Show nested quote +
On September 24 2016 08:07 RoomOfMush wrote:
On September 24 2016 02:54 spinesheath wrote:
I'm not a big fan of using hiding like that in constructors because it can introduce hard to spot errors. In some languages it is common practice to prefix variables at object scope, for example with an "m" (often in C++) or an underscore (C#). That way you can still use the plain name for stuff at the method scope, most commonly in the constructor.

Although I am not a big fan of naming parameters equal to fields either, it must be noted that todays IDE's are more than capable of detecting these kinds of bugs and generating a warning. I know for a fact that Eclipse will warn you if you assign a parameter to itself.

Correct me if I'm wrong but I think the issue is more the readability of the code, not the compilability. If it's not immediately clear which of two variables is being referenced, then time is wasted on the main work of coding (which is reading).

Thats a matter of personal taste, but spinesheath was explicitly talking about "hard to spot errors" and I assume he ment missing the "this" operator and assigning a parameter to itself.

But todays IDE's also have something for your particular problem: Syntax highlighting. Just tell your IDE to highlight fields in a different color to parameters and it will become quite obvious which one is being used.
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
September 24 2016 08:03 GMT
#15316
You can just as well read from or write to a variable in inner scope thinking you're working with a field. That doesn't have to involve any self assignment. Obviously IDEs can show a warning for that too, but if you use shadowing in your constructors regularly, then all your constructors will be littered with these warnings. So I suppose that most people who do that have the warning disabled.

Syntax highlighting is not part of your codebase. So if you ever work with others, you better not rely on that.
If you have a good reason to disagree with the above, please tell me. Thank you.
Acrofales
Profile Joined August 2010
Spain17970 Posts
September 24 2016 08:38 GMT
#15317
On September 24 2016 17:03 spinesheath wrote:
You can just as well read from or write to a variable in inner scope thinking you're working with a field. That doesn't have to involve any self assignment. Obviously IDEs can show a warning for that too, but if you use shadowing in your constructors regularly, then all your constructors will be littered with these warnings. So I suppose that most people who do that have the warning disabled.

Syntax highlighting is not part of your codebase. So if you ever work with others, you better not rely on that.

Huh? That's not when it shows a warning.


int fizz, bar;

public void foo(int bar) {
this.bar = bar; //fine, no warning
bar = bar; //warning (assigning bar to itself)
this.fizz = fizz; //warning (fizz is only in the outer scope, thus self assignment again.)
}
spinesheath
Profile Blog Joined June 2009
Germany8679 Posts
September 24 2016 09:03 GMT
#15318

int fizz, bar;

public void foo(int bar) { // this is where it could show a warning that bar is shadowing this.bar

int fizz; // this is where it could show a warning that fizz is shadowing this.fizz

// ... enough code to make you forget the line above ...

fizz = 5; // here you could mean to assign to this.fizz, introducing a bug

// and if we have some slightly more complex code with say loops, you might not even get a
// "value assigned to variable is never used" warning
}

If you have a good reason to disagree with the above, please tell me. Thank you.
Acrofales
Profile Joined August 2010
Spain17970 Posts
September 24 2016 09:22 GMT
#15319
On September 24 2016 18:03 spinesheath wrote:

int fizz, bar;

public void foo(int bar) { // this is where it could show a warning that bar is shadowing this.bar

int fizz; // this is where it could show a warning that fizz is shadowing this.fizz

// ... enough code to make you forget the line above ...

fizz = 5; // here you could mean to assign to this.fizz, introducing a bug

// and if we have some slightly more complex code with say loops, you might not even get a
// "value assigned to variable is never used" warning
}


Yeah, ok. That's pretty bad. Anybody using shadowing like that is asking for it, though

I mean, I'm not a fan of shadowing in general and never use it, except in the constructor to initialize fields. And that goes at the bottom of the constructor, so any operations you do before just setting the field aren't affected b the potential bugs you describe.
Prillan
Profile Joined August 2011
Sweden350 Posts
September 24 2016 10:55 GMT
#15320
On September 24 2016 18:03 spinesheath wrote:

int fizz, bar;

public void foo(int bar) { // this is where it could show a warning that bar is shadowing this.bar

int fizz; // this is where it could show a warning that fizz is shadowing this.fizz

// ... enough code to make you forget the line above ...

fizz = 5; // here you could mean to assign to this.fizz, introducing a bug

// and if we have some slightly more complex code with say loops, you might not even get a
// "value assigned to variable is never used" warning
}


One reason why I like the explicit self in python.


def method(self, bar):
... code here ...
TheBB's sidekick, aligulac.com | "Reality is frequently inaccurate." - Douglas Adams
Prev 1 764 765 766 767 768 1031 Next
Please log in or register to reply.
Live Events Refresh
Big Brain Bouts
16:00
#97
RotterdaM680
Liquipedia
FEL
16:00
Polish Championship: Qualifier
IndyStarCraft 227
CranKy Ducklings71
Liquipedia
WardiTV European League
16:00
Swiss Groups Day 2
YoungYakov vs ShamelessLIVE!
uThermal vs Fjant
Nicoract vs goblin
Harstem vs Gerald
WardiTV851
TKL 253
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
RotterdaM 680
TKL 253
IndyStarCraft 227
Hui .187
UpATreeSC 75
StarCraft: Brood War
Britney 30653
Calm 3783
Rain 2340
Horang2 881
Larva 458
BeSt 232
Mind 182
Movie 82
Mong 70
sas.Sziky 48
[ Show more ]
Barracks 47
Shinee 33
yabsab 32
soO 20
Free 19
Shine 13
Dewaltoss 9
Stormgate
NightEnD11
Dota 2
Gorgc12527
qojqva3066
League of Legends
Grubby3293
singsing2146
Counter-Strike
ScreaM2894
fl0m1629
Foxcn372
byalli247
Other Games
FrodaN1291
Beastyqt605
Fuzer 255
Trikslyr57
ZombieGrub22
Nathanias14
Organizations
Other Games
BasetradeTV24
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 16 non-featured ]
StarCraft 2
• intothetv
• AfreecaTV YouTube
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• WagamamaTV532
League of Legends
• Nemesis5061
• Jankos1520
• TFBlade1053
Other Games
• imaqtpie867
• Shiphtur377
Upcoming Events
Korean StarCraft League
8h 52m
CranKy Ducklings
15h 52m
RSL Revival
15h 52m
ByuN vs Cham
herO vs Reynor
FEL
21h 52m
RSL Revival
1d 15h
Clem vs Classic
SHIN vs Cure
FEL
1d 17h
BSL: ProLeague
1d 23h
Dewalt vs Bonyth
Replay Cast
3 days
Sparkling Tuna Cup
3 days
The PondCast
4 days
[ Show More ]
Replay Cast
5 days
RSL Revival
5 days
Replay Cast
6 days
RSL Revival
6 days
Liquipedia Results

Completed

Proleague 2025-06-28
HSC XXVII
Heroes 10 EU

Ongoing

JPL Season 2
BSL 2v2 Season 3
BSL Season 20
Acropolis #3
KCM Race Survival 2025 Season 2
CSL 17: 2025 SUMMER
Copa Latinoamericana 4
Championship of Russia 2025
RSL Revival: Season 1
Murky Cup #2
BLAST.tv Austin Major 2025
ESL Impact League Season 7
IEM Dallas 2025
PGL Astana 2025
Asian Champions League '25
BLAST Rivals Spring 2025
MESA Nomadic Masters
CCT Season 2 Global Finals
IEM Melbourne 2025

Upcoming

2025 ACS Season 2: Qualifier
CSLPRO Last Chance 2025
2025 ACS Season 2
CSLPRO Chat StarLAN 3
K-Championship
uThermal 2v2 Main Event
SEL Season 2 Championship
FEL Cracov 2025
Esports World Cup 2025
StarSeries Fall 2025
FISSURE Playground #2
BLAST Open Fall 2025
BLAST Open Fall Qual
Esports World Cup 2025
BLAST Bounty Fall 2025
BLAST Bounty Fall Qual
IEM Cologne 2025
FISSURE Playground #1
TLPD

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

Advertising | Privacy Policy | Terms Of Use | Contact Us

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