• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EST 01:19
CET 07:19
KST 15:19
  • 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 win1BGE Stara Zagora 2026 announced14[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
SC2 Proleague Discontinued; SKT, KT, SGK, CJ disband Weekly Cups (Nov 24-30): MaxPax, Clem, herO win BGE Stara Zagora 2026 announced Information Request Regarding Chinese Ladder SC: Evo Complete - Ranked Ladder OPEN ALPHA
Tourneys
$5,000+ WardiTV 2025 Championship Constellation Cup - Main Event - Stellar Fest RSL Revival: Season 3 Tenacious Turtle Tussle [Alpha Pro Series] Nice vs Cure
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
Which season is the best in ASL? [ASL20] Ask the mapmakers — Drop your questions BGH Auto Balance -> http://bghmmr.eu/ FlaSh's Valkyrie Copium BW General Discussion
Tourneys
[Megathread] Daily Proleagues [BSL21] RO16 Group B - Sunday 21:00 CET [BSL21] RO16 Group C - Saturday 21:00 CET Small VOD Thread 2.0
Strategy
Game Theory for Starcraft How to stay on top of macro? Current Meta PvZ map balance
Other Games
General Games
Stormgate/Frost Giant Megathread Path of Exile Nintendo Switch Thread Should offensive tower rushing be viable in RTS games? The Perfect Game
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
Things Aren’t Peaceful in Palestine Russo-Ukrainian War Thread US Politics Mega-thread The Big Programming Thread Artificial Intelligence Thread
Fan Clubs
White-Ra Fan Club
Media & Entertainment
[Manga] One Piece Movie Discussion! Anime Discussion Thread
Sports
Formula 1 Discussion 2024 - 2026 Football Thread NBA General Discussion MLB/Baseball 2023
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
James Bond movies ranking - pa…
Topin
Esports Earnings: Bigger Pri…
TrAiDoS
Thanks for the RSL
Hildegard
Saturation point
Uldridge
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1417 users

The Big Programming Thread - Page 766

Forum Index > General Forum
Post a Reply
Prev 1 764 765 766 767 768 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.
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
Spain18138 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
Spain18138 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
Poland17488 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
Spain18138 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
Spain18138 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
Spain18138 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 1032 Next
Please log in or register to reply.
Live Events Refresh
Next event in 5h 41m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
RuFF_SC2 128
ProTech26
StarCraft: Brood War
Jaedong 358
Tasteless 235
Leta 141
BeSt 104
sorry 61
ZergMaN 49
Noble 18
Bale 16
Movie 12
Shine 12
[ Show more ]
Backho 11
ivOry 8
yabsab 8
Icarus 7
zelot 7
Dota 2
monkeys_forever1443
XaKoH 481
NeuroSwarm89
League of Legends
JimRising 656
Other Games
summit1g12334
WinterStarcraft562
C9.Mang0352
Mew2King106
Organizations
Other Games
gamesdonequick898
StarCraft: Brood War
UltimateBattle 5
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 18 non-featured ]
StarCraft 2
• Hupsaiya 150
• Berry_CruncH78
• intothetv
• sooper7s
• Migwel
• AfreecaTV YouTube
• LaughNgamezSOOP
• IndyKCrew
• Kozan
StarCraft: Brood War
• Azhi_Dahaki36
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• masondota22196
League of Legends
• Scarra1575
• Rush1496
• Lourlo1108
• Stunt712
Upcoming Events
Wardi Open
5h 41m
StarCraft2.fi
10h 41m
PiGosaur Monday
18h 41m
Wardi Open
1d 5h
StarCraft2.fi
1d 10h
Replay Cast
1d 17h
The PondCast
2 days
Replay Cast
2 days
Korean StarCraft League
3 days
CranKy Ducklings
4 days
[ Show More ]
SC Evo League
4 days
BSL 21
4 days
Sziky vs OyAji
Gypsy vs eOnzErG
Sparkling Tuna Cup
5 days
BSL 21
5 days
Bonyth vs StRyKeR
Tarson vs Dandy
Replay Cast
6 days
Wardi Open
6 days
StarCraft2.fi
6 days
Replay Cast
6 days
Liquipedia Results

Completed

Proleague 2025-11-28
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.