Homegrown utility methods - java

Static utility methods are generally frowned up by OO purists.
I was wondering however what people feel about utility methods that are used to avoid something simple like a null check throughout the application.
String.trim() throws a NPE when invoked on a null String. So I have to do:
if(str!=null)
setValue(str.trim());
else
setValue("");
What if I create a utility method that checks for the null?
setValue(myTrim(str));
public static String myTrim(String str) {
if(str==null) return ""
else return str.trim();
}
The one problem I have encountered with methods like these is that some developers on the team might not like/not know this utility and might be doing staight calls after doing a null comparison.
Is this something that you do your framework too? If yes, what are the other common utility general use methods that people have created and are using in their applications?
What do you feel are the pros and cons of either approach?

I'd be inclined to replace the homegrown uses when an existing library (like Apache Commons Blah Blah Blah) already has written it. Code you can offload to someone else lets you focus on the important parts of the software that truly differentiate your work from everyone else's. But yes, utility classes with static methods are great, if they need to be written by you at all.
FYI, take a look at StringUtils.trimToEmpty(). Good luck.

some developers on the team might not like/not know this utility
That's what communication is good for. And I don't mean e-mail.
Talks about these kind of functions, probably other team members are doing the same and by not communitating you're duplicating code and efforts.
You may find a way to use these utility methods or even some more experienced developer migth have already develop a more mature lib or used a 3rd party.
But by all means, communicate with your team

I'm not an OO purist. So i love stuff like this. Anything that makes it easier to write code that reflects my intentions without getting bogged down in irrelevant details.
Write it. Use it yourself. Don't be shy - demonstrate how much cleaner it makes your code. Worst case, at least there'll be a bit less repetition in your code...

In terms of a design principle, there are some things that are just more logically static methods. If the utility class that you're writing doesn't really have any "state", and it feels more logical to make it uninstantiable with a bunch of static methods, then do it like that. But make sure your class is genuinely uninstantiable (give it a private constructor; I've seen people declare the class as abstract, but that's no good because people can override it).
The problem that you then get into is that if your class is project-wide, you need to treat it as a library class. And writing libraries is different from writing general code:
in general code, you should profile rather than prematurely optimising; but in a library method, you can't predict how people will use your call in the future;
you need to be very careful to document or clearly name what your method does;
you need to give it generic behaviour, and not be blinded by some specific feature that you need at that moment (e.g. if you have a method to "tokenise a string", what do you do with empty tokens? if you need to ignore them, will other callers to your method?)

I have a few classes that just contain fave static methods - they do make sense to have. You can put together extensive unit tests checking any and all boundary conditions.
In the case you described though - wouldn't it be better to make the setValue method accept any string sent to it? The method could then apply a default null string, trim it or even throw an exception if the value was incorrect.
The JavaDoc on that routine can then clearly state what inputs are valid/invalid and what happens to invalid inputs.
Not saying this is right - just another viewpoint

I use a lot of utility functions. There are some things that just don't need "objects", but I don't like the particular example you have of trim().
A reference to string that is null is very different from an empty string. Unless the app is very simple, and you know you always want to read a null reference as "", I wouldn't do it. For this case, I prefer:
setValue((str != null) ? str.trim() : "")
For me, an uncaught NPE is a good indication that there's a major error going on in the application!

Related

Using Facade Design Pattern | Drawbacks/ Solutions/ Suggestions

Each method in Facade Object is combination of several other methods exposed in several interfaces. Over the period of time this object will also grow as we will come to know about different operations that can be achieved by combining different interfaces available in complex system and its method.
My question is simple:
1) It is a better option to go ahead with Facade or do we have some other option available? because as we increase the number of methods to accommodate each new operation in Facade object, it also becomes complex. A possible solution that I can think of is to create one more Facade
2) Also, is there a limit-on methods exposed by facade when we will say it become complex?
Update: my analysis says stop adding more method to a Facade if it is making hard to understand and rethink your design; is that it?
Since your question is very abstract, it's hard to answer it in a way that is guaranteed to be good for the specifics of what you're writing.
As far as I can tell, the question you're asking is really, if you have
interface A { public void a(); }
interface B { public void b(); }
class ABFacade {
private final A a = ...
private final B b = ...
public void ab() { a.a(); b.b(); }
}
then is that useful or not?
The answer is going to depend on
The problem domain - how well defined is it?
How you name things - will people understand it?
Code reuse - is there more than one thing that will ever need to call a facade method?
I don't think there is a single right answer - at least not with specific examples. It also depends on what the purpose for using this pattern is - better code reuse? Fewer sets of duplicate code that does something complex? Creating choke points all code that does X must pass through? Clarity for other developers? The answers to that question profoundly affects what your code should look like.
I can suggest some general things that might help result in something useful:
If a facade method will only be used in one place, it probably does not deserve to be in the facade - if it the code only has one client, it probably makes more sense to do all the steps inline
Can some operation on the facade be given clear naming? Would the result be more intuitive to use than writing out everything the facade does? If so, then that probably should be on the facade
At the end, it's just a pattern. If it lets you write smaller, better or more reliable software, use it; if it doesn't, don't bother.

Java Class That Has 90% Static Members. Good Practice Or What?

I'm 14 and have been learning java for about 4/5 months. I'm coding a game now called super mario winshine and i wanted to know if it is good practice to have a class that is mostly static variables.
The class is the one that holds all the information for the game's level/world. Since I only need one version of this class, and lots of other classes will be using it, I choose to make all the variables static. Is this good practice?
I have considered the fact that i could keep the variables "non-static" and just clone the main object i use for that class, but I thought i would rather sacrifice "O-O" for memory in this case.
As soon as you want to have two or more worlds this will fail. Say, when your first release is a runaway success and you want to add the "parallel universe" expansion set.
In my experience, 90% of the time when marketing says "oh, don't worry, there will only be one Application/Window/Database/User" they are wrong.
ADDED
I would also avoid using a true Singleton pattern with World.getInstance() etc. Those are for the rare cases where it really is an essential requirement that there only be one of something. In your case, you are using it as a convenience, not a requirement.
There is no perfect fix, YMMV, but I'd consider a single static method, something like
World World.getWorld(String name)
and then you call real (non-static) methods on the World that is returned. For V1 of your program, allow null to mean "the default world".
Some might put that method into a class named WorldManager, or, perhaps showing my age, a more clever name like Amber. :-)
It all depends upon what your methods and classes are. There is no problem in defining utility methods as static methods in a class. There is no need to make it a singleton as others are suggesting. Look at the Math class from java.lang package. It has lot of utility methods but it isn't a singleton.
Also check out static imports functionality. Using this you doesn't need to qualify method calls with the class name.
Well, what you are doing is definitely an option. Or you could use a singleton pattern:
public class World {
private static World instance = new World();
private World() {
}
public static World getInstance() {
return instance;
}
}
Now just use World.getInstance() everywhere to have a unique object of this type per application.
I would say it's definitely not a good practice.
I've not seen your code, but having several static variables in a class that other classes access freely seems to indicate that you're not really using object orientation/classes but more just writing procedural code in Java. Classes should generally encapsulate/hide all their variables - static or not - from access from other classes so that other classes don't depend on how the class is implemented.
The static part also causes problems with making threads work (global variables are hard to lock in a good way so that nothing deadlocks) and with unit testing (mocking is all but impossible)
I also agree with the other posters, if you need "global variables", at least make them singletons. That allows you to change strategy easier later and does not lock you to one world.
Edit: I'm definitely not advocating singletons as a good pattern here if someone read it like that, but it does solve some problems with static variables, esp. regarding testing/mocking compared to just statics so I'd say it's a ever so slightly lighter shade of gray :) It is also a pattern that is easier to gradually replace with better patterns by for example using a IoC container.
I think it is fine as long as you don't need anything more sophisticated, in other words, static fields are OK as long as different objects (including subclasses if there will be any) do not need different values.
You code by yourself, refactoring is easy with modern tools, me says don't fix it until it is broken, and focus on the algorithmic aspects of your project.
Perhaps you may think to encapsulate all those static fields within a different static class, as it is a good principle to "keep what changes seperate from what does not". Chances are one day you will want to initiate that static class with different values, for example want to read the initial values from an XML file and/or registry, add behaviour, etc. so instead of a static class you will implement it with a Singleton pattern.
But clearly that is not the concern of today. Till then, enjoy!
You may wish to look into implementing this class as a singleton, while there is nothing particularly wrong with your approach it may lead to some inflexibility further down the road.
Also you should take in to consideration the purpose of static members which is to be a member of the class and 'act' on/with the class not an instance of it. For example the static method in a singleton returns either a new instance of the class if one doesn't already exist or returns the instance, and because the method is static you do not instantiate a new one. This is probably worth a read because it can be somewhat confusing when determining the appropriate use of static members
I'm not sure what you are really talking about from your short description, so I'll try this:
public class Level {
static List<Mushroom> mushrooms;
static List<Coin> coins;
...
}
Is that you were describing?
You asked if this is "good practice" and I can tell you that this looks very odd, so, no, it's not.
You gain absolutely nothing by doing this. You make it impossible to have more than one Level, which brings no advantage, but it could cause trouble in the future.
I didn't understand your last paragraph where you say you made most things static to save memory. You would usually create one Level and it would be passed around (without cloning) to the various classes/methods that read from it or modify it.

Avoid accessing private properties directly from the same class

This is a very simple example where accessing directly could be dangerous
class Something{
public static final int MAX=123;
private int prop;
final void riskyMethod()
{
this.prop=800; //this is wrong
}
final void safeSetProp(int x)
{
if(x<MAX)
{
prop=x;
}
}
}
I know it could be done encapsulating "prop" in another class,
and defining it there as private, but that's a lot of useless code overhead!
Is there a way to force the use of methods to access same class properties?
a keyword? any trick?
I confess I have done things like this to avoid accidental access by the same class
private int IKWIDprop; //IKWID = I Know What I am Doing
I am sure you could know a better approach =)
Regards!
This is your class, come on! You always know what you are doing. If you don't, write tests. I understand you want to force the usage of getter instead of raw field in case at some point in the future the getter will be equipped with some extra logic. But because this is your class, you are fully responsible and capable of maintaining this code.
Bizzare Hungarian notation only clutters the code. Unit test your class to make sure nobody damages your work (including yourself). Nobody reads documentation and Javadocs, not to mention nobody will understand TIASCWIAFDPUGIage (thisIsASpecialCaseWhenIAccessFieldDirectlyPleaseUseGetterInstead_Age), including you after a while.
BTW if you force the usage of encapsulating getter inside your class, how does the getter itself access the field? So go back to earth and be reasonable. Having a strong suite of unit tests is much more helpful, reliable and provides better documentation.
UPDATE: Actually, there is a (sort of) clean way. You can use AspectJ, with few clever pointcuts, will catch raw private field access excluding some special cases. It can be executed at compile time to fail the build or at runtime. The pointcut would say something like: "each private field access from a method that is not annotated with #ThisIsASetter should generate compile time error. Maybe somebody more fluent with AspectJ can write this?
no, there is no such keyword. I advice you to write good documentaton, comments and to promis to beat those, who will use direct assigning of the value
One "trick" that comes to mind is to put any fields like this into an abstract class which provides the necessary getter/setter methods. Then, derive your "real" class from the abstract class, and now any writing to those private fields need to be done via the "safe" setter methods.
Of course, this is a ton of extra overhead, and it still doesn't prevent you from writing incorrect values in the abstract parent class anyway.
The point of private is to ensure that internal class invariants aren't disturbed incorrectly by code that consumes the class. As you note, it does not prevent the class itself from messing with them, because presumably the class knows what it's doing! If you want to ensure that certain invariants are correct prior to relying on them, you can always use assert statements. If they fire, you can look through your code and see what you've done that's caused the problem.
In general, your best bet is to just be careful with your code, rather than trying any "tricks".

Best way to add functionality to built-in types

I wonder what is the best way in terms of strict OOP to add functionality to built-in types like Strings or integers or more complex objects (in my case the BitSet class).
To be more specific - I got two scenarios:
Adding a md5 hashing method to the String object
Adding conversion methods (like fromByteArray() or toInteger()) to the BitSet class.
Now I wonder what the best practices for implementing this would be.
I could e.g. create a new Class "BitSetEx" extending from BitSet and add my methods. But I don't like the idea since this new class would need describing name and "BitSetWithConversionMethods" sound really silly.
Now I could write a class consisting only of static methods doing the conversions.
Well I got a lot of ideas but I wan't to know what would be the "best" in sense of OOP.
So could someone answer me this question?
There are a few approaches here:
Firstly, you could come up with a better name for the extends BitSet class. No, BitsetWithConversionMethods isn't a good name, but maybe something like ConvertibleBitSet is. Does that convey the intent and usage of the class? If so, it's a good name. Likewise you might have a HashableString (bearing in mind that you can't extend String, as Anthony points out in another answer). This approach of naming child classes with XableY (or XingY, like BufferingPort or SigningEmailSender) can sometimes be a useful one to describe the addition of new behaviour.
That said, I think there's a fair hint in your problem (not being able to find a name) that maybe this isn't a good design decision, and it's trying to do too much. It is generally a good design principle that a class should "do one thing". Obviously, depending on the level of abstraction, that can be stretched to include anything, but it's worth thinking about: do 'manipulating the set/unset state of a number of bits' and 'convert a bit pattern to another format' count as one thing? I'd argue that (especially with the hint that you're having a hard time coming up with a name) they're probably two different responsibilities. If so, having two classes will end up being cleaner, easier to maintain (another rule is that 'a class should have one reason to change'; one class to both manipulate + convert has at least 2 reasons to change), easier to test in isolation, etc.
So without knowing your design, I would suggest maybe two classes; in the BitSet example, have both a BitSet and (say) a BitSetConverter which is responsible for the conversion. If you wanted to get really fancy, perhaps even:
interface BitSetConverter<T> {
T convert(BitSet in);
BitSet parse(T in);
}
then you might have:
BitSetConverter<Integer> intConverter = ...;
Integer i = intConverter.convert(myBitSet);
BitSet new = intConverter.parse(12345);
which really isolates your changes, makes each different converter testable, etc.
(Of course, once you do that, you might like to look at guava and consider using a Function, e.g. a Function<BitSet, Integer> for one case, and Function<Integer, BitSet> for the other. Then you gain a whole ecosystem of Function-supporting code which may be useful)
I would go with the extending class. That is actually what you are doing, extending the current class with some extra methods.
As for the name: you should not name at for the new features, as you might add more later on. It is your extended BitSet class, so BitSetEx allready sounds better then the BitSetWithConversionMethods you propose.
You don't want to write a class with the static methods, this is like procedural programming in an OOP environment, and is considered wrong. You have an object that has certain methods (like the fromByteArray() you want to make) so you want those methods to be in that class. Extending is the way to go.
It depends. As nanne pointed out, subclass is an option. But only sometimes. Strings are declared final, so you cannot create a subclass. You have at least 2 other options:
1) Use 'encapsulation', i.e. create a class MyString which has a String on which it operates (as opposed to extending String, which you cannot do). Basically a wrapper around the String that adds your functionality.
2) Create a utility/helper, i.e. a class with only static methods that operate on Strings. So something like
class OurStringUtil {
....
public static int getMd5Hash(String string) {...}
....
}
Take a look at the Apache StringUtils stuff, it follows this approach; it's wonderful.
"Best way" is kinda subjective. And keep in mind that String is a final class, so you can't extend it.
Two possible approaches are writing wrappers such as StringWrapper(String) with your extra methods, or some kind of StringUtils class full of static methods (since Java 5, static methods can be imported if you wan't to use the util class directly).

Is writing "this." before instance variable and methods good or bad style?

One of my nasty (?) programming habits in C++ and Java is to always precede calls or accesses to members with a this. For example: this.process(this.event).
A few of my students commented on this, and I'm wondering if I am teaching bad habits.
My rationale is:
Makes code more readable — Easier to distinguish fields from local variables.
Makes it easier to distinguish standard calls from static calls (especially in Java)
Makes me remember that this call (unless the target is final) could end up on a different target, for example in an overriding version in a subclass.
Obviously, this has zero impact on the compiled program, it's just readability. So am I making it more or less readable?
Note: I turned it into a CW since there really isn't a correct answer.
I think it's less readable, especially in environments where fields are highlighted differently from local variables. The only time I want to see "this" is when it is required, for example:
this.fieldName = fieldName
When assigning the field.
That said, if you need some way to differentiate fields for some reason, I prefer "this.fieldName" to other conventions, like "m_fieldName" or "_fieldName"
This is a very subjective thing. Microsoft StyleCop has a rule requiring the this. qualifier (though it's C# related). Some people use underscore, some use weird hungarian notations. I personally qualify members with this. even if it's not explicitly required to avoid confusion, because there are cases when it can make one's code a bit more readable.
You may also want to check out this question:
What kind of prefix do you use for member variables?
I'd never seen this style until I joined my current employer. The first time I saw it I thought "this idiot has no idea and Java/OO languages generally are not his strong suit", but it turns out that it's a regularly-occurring affliction here and is mandatory style on a couple of projects, although these projects also use the
if (0 == someValue)
{
....
}
approach to doing conditionals, i.e. placing the constant first in the test so that you don't run the risk of writing
if (someValue = 0)
by accident - a common problem for C coders who ignore their compiler warnings. Thing is, in Java the above is simply invalid code and will be chucked out by the compiler, so they're actually making their code less intuitive for no benefit whatsoever.
For me, therefore, far from showing "the author is coding with a dedicated thought process", these things strike me as more likely to come from the kind of person who just sticks to the rules someone else told them once without questioning them or knowing the reasons for the rules in the first place (and therefore where the rules shouldn't apply).
The reasons I've heard mainly boil down to "it's best practice" usually citing Josh Bloch's Effective Java which has a huge influence here. In fact, however, Bloch doesn't even use it where even I think he probably should have to aid readability! Once again, it seems to be more the kind of thing being done by people who are told to do it and don't know why!
Personally, I'm inclined to agree more with what Bruce Eckel says in Thinking in Java (3rd and 4th editions):
'Some people will obsessively put this in front of every method call and field reference, arguing that it makes it "clearer and more explicit." Don't do it. There's a reason that we use high-level languages: They do things for us. If you put this in when it's not necessary, you will confuse and annoy everyone who reads your code, since all the rest of the code they've read won't use this everywhere. People expect this to be used only when it is necessary. Following a consistent and straightforward coding style saves time and money.'
footnote, p169, Thinking in Java, 4th edition
Quite. Less is more, people.
3 Reasons ( Nomex suit ON)
1) Standardization
2) Readability
3) IDE
1) The biggie Not part of Sun Java code style.
(No need to have any other styles for Java.)
So don't do it ( in Java.)
This is part of the blue collar Java thing: it's always the same everywhere.
2) Readability
If you want this.to have this.this in front of every this.other this.word; do you really this.think it improves this.readability?
If there are too many methods or variable in a class for you to know if it's a member or not... refactor.
You only have member variables and you don't have global variables or functions in Java. ( In other langunages you can have pointers, array overrun, unchecked exceptions and global variables too; enjoy.)
If you want to tell if the method is in your classes parent class or not...
remember to put #Override on your declarations and let the compiler tell you if you don't override correctly. super.xxxx() is standard style in Java if you want to call a parent method, otherwise leave it out.
3) IDE
Anyone writing code without an IDE that understands the language and gives an outline on the sidebar can do so on their own nickel. Realizing that if it aint' language sensitive, you're trapped in the 1950's. Without a GUI: Trapped in the 50's.
Any decent IDE or editor will tell you where a function/variable is from. Even the original VI (<64kb) will do this with CTags. There is just no excuse for using crappy tools. Good ones are given away for free!.
Sometimes I do like writing classes like this:
class SomeClass{
int x;
int y;
SomeClass(int x, int y){
this.x = x
this.y = y
}
}
This makes it easier to tell what argument is setting what member.
More readable, I think. I do it your way for exactly the same reasons.
I find that less is more. The more needlessly verbose junk you have in your code, the more problems people are going to have maintaining it. That said, having clear and consistent behavior is also important.
In my opinion you are making it more readable. It lets potential future troubleshooters know for a fact where the function you are calling is.
Second, it is not impossible to have a function with the exact same name global or from some namespace that that gets "using"'ed into conflict. So if there is a conflict the original code author will know for certain which function they are calling.
Granted that if there are namespace conflicts some other rule of clean coding is being broken, but nobody is perfect. So I feel that any rule that does not impede productivity, has the potential to reduce errors(however minuscule a potential), and could make a future troubleshooters goal easier, is a good rule.
There is a good technical reason to prefer to use or avoid this - the two are not always equivalent.
Consider the following code:
int f();
template <typename T>
struct A
{
int f();
};
template <typename T>
struct B : A<T>
{
int g()
{
return f();
return this->f();
}
};
Now, there are two f() calls in B<T>::g(). One would expect it to call A<T>::f(), but only the second one will. The first will call ::f(). The reason behind this is that because A<T> is dependent on T, the lookup does not normally find it. this, by being a pointer to B<T>, is also dependent on T however, so if you use it, the lookup will be delayed until after B<T> is instantiated.
Note that this behavior may not be present on some compilers (specifically, MSVC) which do not implement two-phase name lookup, but nonetheless it is the correct behavior.
Python folks do it all the time and almost all of them prefer it. They spell it 'self' instead of 'this'. There are ways around it putting explicit 'self' in, but the consensus is that explicit 'self' is essential to understanding the class method.
I have to join the 'include this' camp here; I don't do it consistently, but from a maintenance standpoint the benefits are obvious. If the maintainer doesn't use an IDE for whatever reason and therefore doesn't have member fields and methods specially highlighted, then they're in for a world of scrolling pain.
I use this for at least two reasons:
Fallacies reasons
I like to have consistent code styles when coding in C++, C, Java, C# or JavaScript. I keep myself using the same coding style, mostly inspired from java, but inspired by the other languages.
I like also to keep a coherence inside my code in one language. I use typename for template type parameters, instead of class, and I never play mixer with the two. This means that I hate it when having to add this at one point, but avoid it altogether.
My code is rather verbous. My method names can be long (or not). But they always use full names, and never compacted names (i.e. getNumber(), not getNbr()).
These reasons are not good enough from a technical viewpoint, but still, this is my coding way, and even if they do no (much) good, they do no (much) evil. In fact, in the codebase I work on there are more than enough historical anti-patterns wrote by others to let them question my coding style.
By the time they'll learn writing "exception" or "class", I'll think about all this, again...
Real reasons
While I appreciate the work of the compiler, there are some ambiguities I'd like to make UN-ambiguities.
For example, I (almost) never use using namespace MyNamespace. I either use the full namespace, or use a three-letters alias. I don't like ambiguities, and don't like it when the compiler suddenly tells me there are too functions "print" colliding together.
This is the reason I prefix Win32 functions by the global namespace, i.e. always write ::GetLastError() instead of GetLastError().
This goes the same way for this. When I use this, I consciously restrict the freedom of the compiler to search for an alternative symbol if it did not find the real one. This means methods, as well as member variables.
This could apparently be used as an argument against method overloading, perhaps. But this would only be apparent. If I write overloaded methods, I want the compiler to resolve the ambiguity at compile time. If a do not write the this keyword, it's not because I want to compiler to use another symbol than the one I had in mind (like a function instead of a method, or whatever).
My Conclusion?
All in all, this problem is mostly of style, and with genuine technical reasons. I won't want the death of someone not writing this.
As for Bruce Eckel's quote from his "Thinking Java"... I was not really impressed by the biased comparisons Java/C++ he keeps doing in his book (and the absence of comparison with C#, strangely), so his personal viewpoint about this, done in a footnote... Well...
Not a bad habit at all. I don't do it myself, but it's always a plus when I notice that someone else does it in a code review. It's a sign of quality and readability that shows the author is coding with a dedicated thought process, not just hacking away.
I would argue that what matters most is consistency. There are reasonable arguments for and against, so it's mostly a matter of taste when considering which approach.
"Readability"
I have found useful the use "this" specially when not using an IDE ( small quick programs )
Whem my class is large enough as to delegate some methods to a new class, replacing "this" with "otherRef" it's very easy with the most simple text editor.
ie
//Before
this.calculateMass();
this.perfornmDengerAction();
this.var = ...
this.other = ...
After the "refactor"
// after
this.calculateMass();
riskDouble.calculateMass();
riskDouble.setVar(...);
this.other = ...
When I use an IDE I don't usually use it. But I think that it makes you thing in a more OO way than just use the method.
class Employee {
void someMethod(){
// "this" shows somethings odd here.
this.openConnectino() ; // uh? Why an employee has a connection???
// After refactor, time to delegate.
this.database.connect(); // mmhh an employee might have a DB.. well..
}
... etc....
}
The most important as always is that if a development team decides to use it or not, that decision is respected.
From a .Net perspective, some of the code analysis tools I used saw the "this" and immediately concluded the method could not be static. It may be something to test with Java but if it does the same there, you could be missing some performance enhancements.
I used to always use this... Then a coworker pointed out to me that in general we strive to reduce unnecessary code, so shouldn't that rule apply here as well?
If you are going to remove the need to add this. in front of member variables, static analysis tools such as checkstyle can be invaluable in detecting cases where member variables hide fields. By removing such cases you can remove the need to use this in the first place. That being said I prefer to ignore these warnings in the case of constructors and setters rather than having to come up with new names for the method parameters :).
With respect to static variables I find that most decent IDEs will highlight these so that you can tell them apart. It also pays to use a naming convention for things like static constants. Static analysis tools can help here by enforcing the naming conventions.
I find that there is seldom any confusion with static methods as the method signatures are often different enough to make any further differentiation unnecessary.
I prefer the local assignment mode described above, but not for local method calls. And I agree with the 'consistency is the most important aspect' sentiments. I find this.something more readable, but I find consistent coding even more readable.
public void setFoo(String foo) {
this.foo = foo; //member assignment
}
public doSomething() {
doThat(); //member method
}
I have colleagues who prefer:
public void setFoo(String foo) {
_foo = foo;
}
less readable unless of course your students are still on green screen terminals like the students here... the elite have syntax highighting.
i just heard a rumour also that they have refactoring tools too, which means you don't need "this." for search and replace, and they can remove those pesky redundant thisses with a single keypress. apparently these tools can even split up methods so they're nice and short like they should have been to begin with, most of the time, and then it's obvious even to a green-screener which vars are fields.

Categories

Resources