Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (499)
Games in Android Showcase (118)
games submitted by our members
Games in WIP (567)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  this. - code consistency and readability  (Read 1455 times)
0 Members and 1 Guest are viewing this topic.
Offline Permafrostrocks

Senior Newbie





« Posted 2013-09-15 10:19:06 »

Hello again,
Since I learned about classes and their internal reference this, I wondered if you would use it always when you mean it.
Consider the following Class of a program:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
public class NarcissisticClass{

    public Boolean lookingGood = true;

    public void stillLookingGood(Boolean lookingGood){
        this.lookingGood = lookingGood;
    }

    public void invertLookingGood(){
        this.lookingGood = !this.lookingGood;
    }

}


The method stillLookingGood(Boolean lookingGood) actually requires you to use "this.". invertLookingGood(), on the other hand, does not need it. You could also just reference to the variable lookingGood.

I thought: Ok, being consistent and making everywhere clear, what I am referencing to, must be a good idea. Damage done and I am lost in a jungle of looooong expressions when writing advanced mathematical calculations. There you might use a relevant amount of global variables of the surrounding object and other objects as well. So, could it be that less is more in these situations? Should I just neglect writing this. if the compiler already knows what you mean? What is more important for other programmers or for yourself after not watching the code for maybe years: The consistancy of always knowing, that you mean this.variable or the general readability of code blocks?
Offline Nate

JGO Kernel


Medals: 149
Projects: 4
Exp: 14 years


Esoteric Software


« Reply #1 - Posted 2013-09-15 10:25:35 »

IMO, use this only when required. I often use parameters with the same names as fields, eg in setters. Use your IDE to color parameters differently from fields. It isn't hard to see what is going on.

Offline quew8

JGO Coder


Medals: 30



« Reply #2 - Posted 2013-09-15 10:26:42 »

My Humble Opinion:
Consistency is one of the most important features of readable code. Overly long expressions are just confusing and detract from readability. That seems contradictory, but is very possible to harmonize. What I do, is reference local fields with this in constructors and setters, and in any other methods I make sure that I never create parameters with names which hide local fields. So basic, boilerplate code is very clear and follows the same format but more complex methods are also very readable.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline CodeHead

JGO Knight


Medals: 41


From rags to riches...to rags.


« Reply #3 - Posted 2013-09-15 10:30:26 »

I've always considered using "this" everywhere bad practice. It makes it harder to visually scan the code for instances of a variable/function call. Granted, pretty much every text application has a "find" function in it, but that can be cumbersome when just concentrating on a small segment of your code as opposed to looking for all instances of something.

As a side note, I also tend to avoid giving function parameters the same name as class member variables. My implementation of NarcissisticClass would probably have the member variable named "m_lookingGood". My secondary reason for doing such is that it groups all of my class member variables together in my IDE's class navigator pane.

Those are just my opinions though. Your mileage may vary. Code consistency is a good thing, code repetitiveness, not so much. Cool

Arthur: Are all men from the future loud-mouthed braggarts?
Ash: Nope. Just me baby...Just me.
Offline Jeremy
« Reply #4 - Posted 2013-09-15 10:33:31 »

I prefix member variables with 'm_' for this reason. Some people use '_'

I don't think you should have to be creative with names to avoid name collisions either (I usually see this in code that avoid the m_). Alternately, you can just use 'this' everywhere (seems messy to me though.)

JevaEngine, Latest Playthrough (This demo is networked with a centralized server model)

http://www.youtube.com/watch?v=rWA8bajpVXg
Offline Permafrostrocks

Senior Newbie





« Reply #5 - Posted 2013-09-15 10:44:48 »

Ok, I will try to add a small prefix to every member variable from now on and see where it takes me.

Thank you for your response!
Offline davedes
« Reply #6 - Posted 2013-09-15 13:25:29 »

I would not use "m_" prefix in Java -- it's considered really bad practice and for the most part your other programmers will hate you. Wink

Let your IDE handle this with syntax coloring. Using "this" is fine and even encouraged to increase readability. And obviously the boolean (which is lower case, not the object!) should use a more standardized setter/getter, like setLookingGood(boolean) and isLookingGood(). If the user wants to invert the boolean, they would then use
setLookingGood( !isLookingGood() )
. I would only deviate from these if the class really needed it for convenience or usability.

Offline RobinB

JGO Ninja


Medals: 44
Projects: 1
Exp: 3 years


Spacegame in progress


« Reply #7 - Posted 2013-09-15 13:27:41 »

Or just this:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
public class NarcissisticClass{

    public Boolean lookingGood = true;

    public void stillLookingGood(Boolean look){
        lookingGood = look;
    }

    public void invertLookingGood(){
        lookingGood = !lookingGood;
    }

}
Offline relminator
« Reply #8 - Posted 2013-09-15 14:54:44 »

prefixing m_, etc, is so 90's.  It's considered bad code even in C++.
Offline Permafrostrocks

Senior Newbie





« Reply #9 - Posted 2013-09-15 15:01:47 »

I often forget, how to write the boolean when I am switching between the languages.

But now you made me hesitate again which way to use. I really like to give all input parameters easy-to-understand names which includes both the object members and the local ones from the methods. I don't really get why it is considered bad coding style to use prefixes like "_". In Python you are even encourage to do somethign similar. In the end, it seem to be best to let the IDE or editor color the code for everybody. If and only if there is a lack of good variable names, it would be viable to use prefixes.

EDIT:
prefixing m_, etc, is so 90's.  It's considered bad code even in C++.

Not in all languages. In Python they are often used with a silent agreement of a meaning.
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline davedes
« Reply #10 - Posted 2013-09-15 15:07:56 »

In loosely typed languages like JavaScript and Python, it is common to use "_" as a prefix to suggest "private" -- as in "do not touch." Also, these languages do not have the same IDE tooling, and so syntax changes like prefixes become more common.

In Java, we can actually declare a member as private, and our IDEs know when it's an instance or class member.

You are asking about best practices... Best practice is to stick to the language's conventions... Which means no prefixing in Java. Wink

EDIT: Also note, in Python, underscore prefixing is actually an official standard and part of the language. Wildcard import statements skip underscore-prefixed members.

Offline Jeremy
« Reply #11 - Posted 2013-09-15 17:14:08 »

I would not use "m_" prefix in Java -- it's considered really bad practice and for the most part your other programmers will hate you. Wink

I don't think that is true at all. There is absolutely no way to justify accidently overlapping scopes because you haven't employed a proper naming convention and you can say 'only some variables might be hidden' at best regarding the code. Then you can at best be forced to always use the 'this' indirection due to the unpredictable nature of variable naming. You are intentionally & explicitly throwing away a scope that you are naturally placed into every time.

It is controversial I agree, but I've seen lots of code do it either way.

Android source guide-lines encourages the m prefix on private non-static member variables as well for Java:
http://source.android.com/source/code-style.html#follow-field-naming-conventions

JevaEngine, Latest Playthrough (This demo is networked with a centralized server model)

http://www.youtube.com/watch?v=rWA8bajpVXg
Offline sproingie

JGO Kernel


Medals: 202



« Reply #12 - Posted 2013-09-15 17:27:37 »

You use "m_" in Android because Android code uses it.  Avoid the hell out of it everywhere else.  The scope you're naturally placed into is the exact reason you don't treat it as "special".  You don't name locals with "l_foo" do you?  If your variable naming is "unpredictable", you have much bigger problems.
Offline Jeremy
« Reply #13 - Posted 2013-09-15 17:42:06 »

You use "m_" in Android because Android code uses it.
Indeed. That is a pretty shallow way to derive the point in my argument though.

Quote
The scope you're naturally placed into is the exact reason you don't treat it as "special".  You don't name locals with "l_foo" do you?  If your variable naming is "unpredictable", you have much bigger problems.

Ofcourse member variables are 'special.' They are accessible by every member method in the class and they shed their scope upon every member of the class. You don't treat your member variables like local variables, do you? I can name a million other differences with the way people handle the two.

They are unpredictable in that, if you have are accessing member variables without a naming convention, you must constantly assure yourself that the addition of member variables does not conflict with others in inner-scopes and that the addition of variables inside of inner-scopes does not collide with that of a 'god' scope with the exact same naming convention. You are thus forced to always use this indirection.

The difference is that when someone is writing a method it is easier to take the context of just the method rather than the context of the entire class at the exact same time. If you have an inner-scope inside of a method you can't honestly compare the size of its scope to what a typical class sheds over its members.

It gets even messier with inner-classes as well. Inner.this.bluhbluhbluh /redundant .

JevaEngine, Latest Playthrough (This demo is networked with a centralized server model)

http://www.youtube.com/watch?v=rWA8bajpVXg
Offline Orangy Tang

JGO Kernel


Medals: 56
Projects: 11


Monkey for a head


« Reply #14 - Posted 2013-09-15 17:59:09 »

Consider the following Class of a program:

If you always declare your input args to a function as final (which IMHO everyone should do, at least for primitive types) then you'll get an error if you accidentally forget the 'this.' in the assignment.

For simple setXxx() methods it's often the style to have the arg name identical to the member name. That's helpful because you're hinting at the reader that it's supposed to be a straightforward 'set' with no translation, adjustment or other monkey business.

I generally only use 'this.' at times when I want to emphasise that the code is changing the object's state. Particularly when you've got a bunch of calculation on local values, then you set the result as a member.

Your functions should (usually) be small enough that you don't need m_ or 'this.' to make them readable. And if you use 'this.' everywhere then you loose the ability to make people sit up and notice when one actually appears.

[ TriangularPixels.com - Play Growth Spurt, Rescue Squad and Snowman Village ] [ Rebirth - game resource library ]
Offline Several Kilo-Bytes

Senior Member


Medals: 11



« Reply #15 - Posted 2013-09-15 18:03:29 »

As a NetBeans user I take full advantage of warnings, autocompletion, and templates. You can make scope errors or redundant assignments (x = x instead of this.x = x) get highlighted as warning or errors, so it is not a practical problem. You can automatically generate getters, setters, and constructors if you declare your fields first, so it's not a problem. The default parameter name is the same as the field name and it uses this.

I prefer that parameter names, field names, and method names following "get", "set", and "is" all be the same. It's more readable when other people do it because it is consistent. It also helps NetBeans guess what variables to use as parameters if the names are similar.  If you don't want to use this for some reason, the style below can be an alternative. (I think it just makes code more confusing.)
1  
2  
3  
4  
public void setColor(Color newColor)
{
  color = newColor;
}


"this" should be avoided where its redundant because long code just creates more work for yourself and other programmers. An exception might be for equals and compareTo methods. I usually have code like "if(this.color != other.color) return false;"

If you prefix (or postfix) anything, then do so with the parameter names. Prepend "new" or _ or append a 0 or _.
Offline davedes
« Reply #16 - Posted 2013-09-15 19:32:05 »

"Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed."
Java Code Conventions

Just sayin'. If you want to follow best practices, then follow the language's conventions. This becomes really important when you are in a large team or writing software that might be used by many other programmers.

Android SDK has its own style guidelines, which are important to follow. If you don't strictly follow their whitespace, use of braces, naming conventions, logging, etc. then your contributions will get rejected. Note that these naming conventions are specific to Android SDK contributions and patches, and rarely encouraged anywhere outside of that.

Offline Jeremy
« Reply #17 - Posted 2013-09-15 19:37:13 »

"Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed."
Java Code Conventions

Just sayin'. If you want to follow best practices, then follow the language's conventions. This becomes really important when you are in a large team or writing software that might be used by many other programmers.

Android SDK has its own style guidelines, which are important to follow. If you don't strictly follow their whitespace, use of braces, naming conventions, logging, etc. then your contributions will get rejected. Note that these naming conventions are specific to Android SDK contributions and patches, and rarely encouraged anywhere outside of that.

True.

The right answer here is use whatever style guidelines are set out by your team. If you haven't established one yet, then be consistent with what you have already.

JevaEngine, Latest Playthrough (This demo is networked with a centralized server model)

http://www.youtube.com/watch?v=rWA8bajpVXg
Offline sproingie

JGO Kernel


Medals: 202



« Reply #18 - Posted 2013-09-17 05:18:12 »

Ofcourse member variables are 'special.'

And it's my assertion that they're precisely not "special".  They're variables in object scope.  Go look up the concept of "static closure" sometime (you'll have to do better than Wikipedia though, which does a lousy job at it).  You can wave your hands and say I'm up in some hoity-toity theoretical ivory tower, but then go ask yourself why they didn't make 'this' mandatory?

Offline Jeremy
« Reply #19 - Posted 2013-09-17 16:33:57 »

Ofcourse member variables are 'special.'

And it's my assertion that they're precisely not "special".  They're variables in object scope.  Go look up the concept of "static closure" sometime (you'll have to do better than Wikipedia though, which does a lousy job at it).  You can wave your hands and say I'm up in some hoity-toity theoretical ivory tower, but then go ask yourself why they didn't make 'this' mandatory?



Not in the eyes of the compiler, anyone can create a scope anywhere they want.

They are 'special' in the eyes of programmers since they do have a particular significance and there are extra considerations not carried by local variables that need to be taken in to account when designing the class.

JevaEngine, Latest Playthrough (This demo is networked with a centralized server model)

http://www.youtube.com/watch?v=rWA8bajpVXg
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Pippogeek (38 views)
2014-09-24 16:13:29

Pippogeek (29 views)
2014-09-24 16:12:22

Pippogeek (18 views)
2014-09-24 16:12:06

Grunnt (42 views)
2014-09-23 14:38:19

radar3301 (24 views)
2014-09-21 23:33:17

BurntPizza (61 views)
2014-09-21 02:42:18

BurntPizza (31 views)
2014-09-21 01:30:30

moogie (36 views)
2014-09-21 00:26:15

UprightPath (49 views)
2014-09-20 20:14:06

BurntPizza (53 views)
2014-09-19 03:14:18
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!