• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 08:14
CEST 14:14
KST 21:14
  • 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 1 - Final Week6[ASL19] Finals Recap: Standing Tall12HomeStory Cup 27 - Info & Preview18Classic wins Code S Season 2 (2025)16Code S RO4 & Finals Preview: herO, Rogue, Classic, GuMiho0
Community News
Weekly Cups (July 7-13): Classic continues to roll2Team TLMC #5 - Submission extension1Firefly given lifetime ban by ESIC following match-fixing investigation17$25,000 Streamerzone StarCraft Pro Series announced7Weekly Cups (June 30 - July 6): Classic Doubles7
StarCraft 2
General
RSL Revival patreon money discussion thread Weekly Cups (July 7-13): Classic continues to roll Esports World Cup 2025 - Final Player Roster TL Team Map Contest #5: Presented by Monster Energy Team TLMC #5 - Submission extension
Tourneys
RSL: Revival, a new crowdfunded tournament series $5,100+ SEL Season 2 Championship (SC: Evo) WardiTV Mondays Sparkling Tuna Cup - Weekly Open Tournament 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
External Content
Mutation # 482 Wheel of Misfortune Mutation # 481 Fear and Lava Mutation # 480 Moths to the Flame Mutation # 479 Worn Out Welcome
Brood War
General
Flash Announces Hiatus From ASL BW General Discussion A cwal.gg Extension - Easily keep track of anyone [Guide] MyStarcraft [ASL19] Finals Recap: Standing Tall
Tourneys
[BSL20] Non-Korean Championship 4x BSL + 4x China [Megathread] Daily Proleagues 2025 ACS Season 2 Qualifier Small VOD Thread 2.0
Strategy
Simple Questions, Simple Answers I am doing this better than progamers do.
Other Games
General Games
Nintendo Switch Thread Stormgate/Frost Giant Megathread Path of Exile CCLP - Command & Conquer League Project The PlayStation 5
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 The Accidental Video Game Porn Archive Russo-Ukrainian War Thread Porn and Stuff Summer Games Done Quick 2025!
Fan Clubs
SKT1 Classic Fan Club! Maru Fan Club
Media & Entertainment
Movie Discussion! [Manga] One Piece Anime Discussion Thread [\m/] Heavy Metal Thread
Sports
2024 - 2025 Football Thread Formula 1 Discussion 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
The Automated Ban List
Blogs
Men Take Risks, Women Win Ga…
TrAiDoS
momentary artworks from des…
tankgirl
from making sc maps to makin…
Husyelt
StarCraft improvement
iopq
Trip to the Zoo
micronesia
Customize Sidebar...

Website Feedback

Closed Threads



Active: 588 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
Spain17975 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
Spain17975 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
Poland17248 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
Spain17975 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
Spain17975 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
Spain17975 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
Wardi Open
11:00
#44
WardiTV776
OGKoka 721
CranKy Ducklings123
Rex109
Liquipedia
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
OGKoka 721
Harstem 293
Creator 130
Rex 109
StarCraft: Brood War
BeSt 12853
Sea 3007
Mini 2226
Rush 1597
Zeus 1131
Larva 596
Stork 450
Leta 403
PianO 346
firebathero 302
[ Show more ]
EffOrt 176
Pusan 158
ToSsGirL 87
Mind 85
Barracks 33
Shine 32
Shinee 32
sSak 29
Sharp 29
JulyZerg 26
sorry 24
Movie 21
soO 20
Icarus 15
SilentControl 9
IntoTheRainbow 8
Bale 7
Terrorterran 4
Dota 2
qojqva2728
XcaliburYe551
League of Legends
Dendi691
Counter-Strike
shoxiejesuss983
x6flipin725
flusha409
Super Smash Bros
Mew2King130
Heroes of the Storm
Khaldor215
Other Games
singsing1940
B2W.Neo1160
crisheroes383
Fuzer 299
Pyrionflax223
mouzStarbuck215
Happy195
hiko193
SortOf188
Lowko162
ArmadaUGS64
QueenE19
Organizations
Other Games
gamesdonequick4957
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 11 non-featured ]
StarCraft 2
• AfreecaTV YouTube
• intothetv
• Kozan
• IndyKCrew
• LaughNgamezSOOP
• Migwel
• sooper7s
StarCraft: Brood War
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
League of Legends
• Nemesis2112
Upcoming Events
RotterdaM Event
3h 46m
Replay Cast
21h 46m
WardiTV European League
1d 3h
ShoWTimE vs sebesdes
Percival vs NightPhoenix
Shameless vs Nicoract
Krystianer vs Scarlett
ByuN vs uThermal
Harstem vs HeRoMaRinE
PiGosaur Monday
1d 11h
uThermal 2v2 Circuit
2 days
Replay Cast
2 days
The PondCast
2 days
Replay Cast
3 days
Epic.LAN
3 days
CranKy Ducklings
4 days
[ Show More ]
Epic.LAN
4 days
BSL20 Non-Korean Champi…
5 days
Bonyth vs Sziky
Dewalt vs Hawk
Hawk vs QiaoGege
Sziky vs Dewalt
Mihu vs Bonyth
Zhanhun vs QiaoGege
QiaoGege vs Fengzi
Sparkling Tuna Cup
5 days
Online Event
6 days
BSL20 Non-Korean Champi…
6 days
Bonyth vs Zhanhun
Dewalt vs Mihu
Hawk vs Sziky
Sziky vs QiaoGege
Mihu vs Hawk
Zhanhun vs Dewalt
Fengzi vs Bonyth
Liquipedia Results

Completed

2025 ACS Season 2: Qualifier
RSL Revival: Season 1
Murky Cup #2

Ongoing

JPL Season 2
BSL 2v2 Season 3
Copa Latinoamericana 4
Jiahua Invitational
BSL20 Non-Korean Championship
Championship of Russia 2025
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

Upcoming

CSL Xiamen Invitational
CSL Xiamen Invitational: ShowMatche
2025 ACS Season 2
CSLPRO Last Chance 2025
CSLPRO Chat StarLAN 3
BSL Season 21
K-Championship
RSL Revival: Season 2
SEL Season 2 Championship
uThermal 2v2 Main Event
FEL Cracov 2025
Esports World Cup 2025
Underdog Cup #2
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.