• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 15:35
CEST 21:35
KST 04:35
  • 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
TL.net Map Contest #21: Voting10[ASL20] Ro4 Preview: Descent11Team TLMC #5: Winners Announced!3[ASL20] Ro8 Preview Pt2: Holding On9Maestros of the Game: Live Finals Preview (RO4)5
Community News
BSL Team A vs Koreans - Sat-Sun 16:00 CET6Weekly Cups (Oct 6-12): Four star herO85.0.15 Patch Balance Hotfix (2025-10-8)80Weekly Cups (Sept 29-Oct 5): MaxPax triples up3PartinG joins SteamerZone, returns to SC2 competition32
StarCraft 2
General
Revisiting the game after10 years and wow it's bad The New Patch Killed Mech! TL.net Map Contest #21: Voting Stellar Fest: StarCraft II returns to Canada herO Talks: Poor Performance at EWC and more...
Tourneys
SC2's Safe House 2 - October 18 & 19 Sparkling Tuna Cup - Weekly Open Tournament $1,200 WardiTV October (Oct 21st-31st) WardiTV Mondays RSL Offline Finals Dates + Ticket Sales!
Strategy
Custom Maps
Map Editor closed ?
External Content
Mutation # 496 Endless Infection Mutation # 495 Rest In Peace Mutation # 494 Unstable Environment Mutation # 493 Quick Killers
Brood War
General
BW General Discussion BSL Season 21 BGH Auto Balance -> http://bghmmr.eu/ BW caster Sayle BSL Team A vs Koreans - Sat-Sun 16:00 CET
Tourneys
[ASL20] Semifinal B [Megathread] Daily Proleagues SC4ALL $1,500 Open Bracket LAN [ASL20] Semifinal A
Strategy
Current Meta BW - ajfirecracker Strategy & Training Relatively freeroll strategies Siegecraft - a new perspective
Other Games
General Games
Stormgate/Frost Giant Megathread Dawn of War IV Path of Exile Nintendo Switch Thread ZeroSpace Megathread
Dota 2
Official 'what is Dota anymore' discussion LiquidDota to reintegrate into TL.net
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
TL Mafia Community Thread SPIRED by.ASL Mafia {211640}
Community
General
Russo-Ukrainian War Thread Things Aren’t Peaceful in Palestine US Politics Mega-thread Men's Fashion Thread Sex and weight loss
Fan Clubs
The herO Fan Club! The Happy Fan Club!
Media & Entertainment
Series you have seen recently... Anime Discussion Thread [Manga] One Piece Movie Discussion!
Sports
2024 - 2026 Football Thread Formula 1 Discussion MLB/Baseball 2023 NBA General Discussion TeamLiquid Health and Fitness Initiative For 2023
World Cup 2022
Tech Support
SC2 Client Relocalization [Change SC2 Language] Linksys AE2500 USB WIFI keeps disconnecting Computer Build, Upgrade & Buying Resource Thread
TL Community
The Automated Ban List Recent Gifted Posts
Blogs
The Heroism of Pepe the Fro…
Peanutsc
Rocket League: Traits, Abili…
TrAiDoS
Customize Sidebar...

Website Feedback

Closed Threads



Active: 1540 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
Spain18093 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
Spain18093 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
Poland17386 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
Spain18093 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
Spain18093 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
Spain18093 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
IPSL
19:00
Ro24 Group D
Sziky vs Havi
Artosis vs Klauso
Airneanach43
Liquipedia
Safe House 2
17:00
Playoffs
TriGGeR vs Cham
Astrea vs TBD
ZombieGrub753
TKL 344
3DClanTV 80
CosmosSc2 63
EnkiAlexander 62
LiquipediaDiscussion
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
ZombieGrub753
TKL 344
ProTech80
JuggernautJason77
CosmosSc2 63
Railgan 28
StarCraft: Brood War
Larva 608
Barracks 330
Hyun 150
Dewaltoss 148
Mong 53
NaDa 35
scan(afreeca) 13
Dota 2
Gorgc7539
Counter-Strike
fl0m2598
Stewie2K352
Heroes of the Storm
Khaldor495
Liquid`Hasu469
Other Games
Grubby2123
ScreaM1536
Skadoodle226
ToD211
Pyrionflax202
gobbtv194
ArmadaUGS129
Hui .110
Organizations
Other Games
gamesdonequick2758
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 14 non-featured ]
StarCraft 2
• Adnapsc2 18
• Migwel
• AfreecaTV YouTube
• intothetv
• sooper7s
• Kozan
• IndyKCrew
• LaughNgamezSOOP
StarCraft: Brood War
• STPLYoutube
• ZZZeroYoutube
• BSLYoutube
Dota 2
• Ler44
League of Legends
• imaqtpie3678
Other Games
• Shiphtur134
Upcoming Events
Replay Cast
14h 25m
Monday Night Weeklies
20h 25m
WardiTV Invitational
1d 15h
WardiTV Invitational
1d 18h
Tenacious Turtle Tussle
3 days
The PondCast
3 days
WardiTV Invitational
4 days
Online Event
4 days
RSL Revival
5 days
RSL Revival
5 days
[ Show More ]
WardiTV Invitational
5 days
Afreeca Starleague
6 days
Snow vs Soma
Sparkling Tuna Cup
6 days
WardiTV Invitational
6 days
RSL Revival
6 days
Liquipedia Results

Completed

Acropolis #4 - TS2
WardiTV TLMC #15
HCC Europe

Ongoing

BSL 21 Points
ASL Season 20
CSL 2025 AUTUMN (S18)
C-Race Season 1
IPSL Winter 2025-26
EC S1
Thunderpick World Champ.
CS Asia Championships 2025
ESL Pro League S22
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

Upcoming

SC4ALL: Brood War
BSL Season 21
BSL 21 Team A
BSL 21 Non-Korean Championship
RSL Offline Finals
RSL Revival: Season 3
Stellar Fest
SC4ALL: StarCraft II
CranK Gathers Season 2: SC II Pro Teams
eXTREMESLAND 2025
ESL Impact League Season 8
SL Budapest Major 2025
BLAST Rivals Fall 2025
IEM Chengdu 2025
PGL Masters Bucharest 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.