Java - performance consideration when using multiple methods - java

I have a pretty complex java class with over 60 small helper methods used for easy readability and understanding.Just wondering, do you think having these many methods in a class could affect performance in any way?
class MyClass() {
//Some static final variables
MyInnerClass m = loadAllVariables();
private void update(){
}
...
//All 60 methods come here
....
private MyInnerClass loadAllVariables() {
MyInnerClass m = new MyInnerClass();
//load all variables with pre-initialized values
}
private MyInnerClass() {
int a, b, c; //In reality, I have over 20 variables
}
}

No. The number of methods in a method doesn't matter much. Only the methods used are really loaded. If you have thousands of methods this is more likely to be a problem for you (the developer)
Keeping your code simple and clear is more likely to improve performance.

Performance wouldn't be really affected that much. Just make sure you are not implementing the God-anti-pattern.
From an engineering perspective, it might be confusing for other developers to navigate through your complex hierarchy of inner classes.

May be you need to use Extract Class. It is common methodology for solving Feature Envy code smell (these are both taken from Martin Fowler's Refactoring).
About the many methods in one class - I reacall that I've read somewhere that the JVM will optimize additionaly your code, will inline methods, etc.

It depend !!!
First, It likes Peter Lawrey has said, just the methods you use in your answer will take some time. for example:
public void update(){
if (sth) methodA();
else if(sth other) methodB();
else if(sth other) methodC();
}
in above example, always one method will be called.
Seconly, It depends on your platform. If you are developing for desktop, 60 methods make nonsense, unless you use thousand and thousand methods. But if you are developing on Android, 60 methods for one update() function really a big problem. That why many expert say you shouldn't use Getter/Setter on Mobile Platform. And of course, this work will anti again Design pattern :)) That the reason why when you develop on Mobile Platform, you will have hard choice between performance and Maintenance. (It means your code will be clear and easily to read )
Hope it's clear for you :)

Sorry folks, the answers are wrong or not addressing the really important point.
All methods in the class above are private. This means there is no polymorphism going on and the JVM can invoke the method directly and not via invoke dynamic. "private" implies "final".
Further more, all the tiny methods get inlined by the JIT. So there is no performance difference.

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.

Speed optimizing: private and public variables - Java

I am asking this question purely for the speed aspects of the question.
What is the difference in speed between getting the value from an object when it is private or public (Java)?
class MyClass {
public int myInt = 5;
}
class MyOtherClass {
private int myInt = 5;
public int getMyInt() {
return myInt;
}
}
class MyMainClass {
public static void main (String [] args) {
MyClass myObject = new MyClass();
MyOtherClass myOtherObject = new MyOtherClass();
// which is faster?
System.out.println(myObject.myInt);
System.out.println(myOtherObject.getMyInt ());
}
}
I know I can test it, but if anyone alreay knows it, it can't hurt :)
Thanks in advance!
Public and private access is nothing more than determining at compile time whether or not you have access to a variable. At run time, they are exactly the same. This means if you can trick the JVM into thinking you have access (through reflection, unsafe, or modifying the bytecode) then you can. Public and private is just compile time information. That's not to say it doesn't get stored in the bytecode, because it does, but only so it can be referenced if something tries to compile against it.
The access modifier on the field doesn't make any difference in speed, but invoking the accessor method does.
However, the difference isn't great, and is likely to diminish after repeated invocations due to JIT compiler optimizations. It depends on your situation, but I haven't found a case where performance concerns justified the elimination of an accessor. Let good design principles drive your decisions.
One good design principle that will help performance in this case is to prohibit inheritance unless you know it is needed and have taken steps to support it. In particular, declaring the class to be final (or at least the accessor method) will provide faster method dispatch and might also serve as a hint to the JITC to inline more agressively.
Keeping accessors final also allows the compiler to inline calls to the accessor. If the field is private, calls to the accessor from within the class can be inlined (and in a good design, these are far and away the most common case), while a package accessible field can be inlined throughout the package, etc.
As far as I know, when you're calling a getter or any function that will just return some value and nothing else, this method will get inlined so there's no difference whatsoever between the method call and the dirrect access of the field.
You ask about accessing private vs. public variables, but your code example and comment to glowcoder hint that you're really asking about private fields vs. public methods (or, fields vs. methods ... as glowcoder correctly said, public vs. private has no impact on performance).
Many modern compilers will optimize calls to short methods to be equivalent to access to the field they wrap (by inlining the call), but it's entirely possible that a given Java environment will perform a function call instead (which is slightly slower) to invoke the method.
It's up to the particular compiler whether to generate inline code or a function call. Lacking knowledge of which java compiler you're using (and possibly which compiler options), it's not possible to say for sure.
From a performance perspective, the difference is infinitesimal, if there's any difference at all. The compiler is going to optimize this code almost identically, and once the code is compiled, the JVM is going to treat public and private variables exactly the same way (I don't believe it even knows about the distinction between public and private post-compilation).
From a pragmatic standpoint, it's difficult to conceive of any possible scenario where it's worth breaking the traditional Java attribute access pattern for performance purposes. There was a similar question asked on StackOverflow on this subject for C++, and the answers are just as relevant for Java:
Any performance reason to put attributes protected/private?

Should Java methods be static by default?

Say you're writing method foo() in class A. foo doesn't ever access any of A's state. You know nothing else about what foo does, or how it behaves. It could do anything.
Should foo always be static, regardless of any other considerations? Why not?
It seems my classes are always accumulating many private helper methods, as I break tasks down and apply the only-write-it-once principle. Most of these don't rely on the object's state, but would never be useful outside of the class's own methods. Should they be static by default? Is it wrong to end up with a large number of internal static methods?
To answer the question on the title, in general, Java methods should not be static by default. Java is an object-oriented language.
However, what you talk about is a bit different. You talk specifically of helper methods.
In the case of helper methods that just take values as parameters and return a value, without accessing state, they should be static. Private and static. Let me emphasize it:
Helper methods that do not access state should be static.
1. Major advantage: the code is more expressive.
Making those methods static has at least a major advantage: you make it totally explicit in the code that the method does not need to know any instance state.
The code speaks for itself. Things become more obvious for other people that will read your code, and even for you in some point in the future.
2. Another advantage: the code can be simpler to reason about.
If you make sure the method does not depend on external or global state, then it is a pure function, ie, a function in the mathematical sense: for the same input, you can be certain to obtain always the same output.
3. Optimization advantages
If the method is static and is a pure function, then in some cases it could be memoized to obtain some performance gains (in change of using more memory).
4. Bytecode-level differences
At the bytecode level, if you declare the helper method as an instance method or as a static method, you obtain two completely different things.
To help make this section easier to understand, let's use an example:
public class App {
public static void main(String[] args) {
WithoutStaticMethods without = new WithoutStaticMethods();
without.setValue(1);
without.calculate();
WithStaticMethods with = new WithStaticMethods();
with.setValue(1);
with.calculate();
}
}
class WithoutStaticMethods {
private int value;
private int helper(int a, int b) {
return a * b + 1;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int calculate() {
return helper(value, 2 * value);
}
}
class WithStaticMethods {
private int value;
private static int helper(int a, int b) {
return a * b + 1;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int calculate() {
return helper(value, 2 * value);
}
}
The lines we are interested in are the calls to helper(...) on the classes WithoutStaticMethods and WithStaticMethods.
Without static methods
In the first case, without static methods, when you call the helper method the JVM needs to push the reference to the instance to pass it to invokespecial. Take a look at the code of the calculate() method:
0 aload_0
1 aload_0
2 getfield #2 <app/WithoutStaticMethods.value>
5 iconst_2
6 aload_0
7 getfield #2 <app/WithoutStaticMethods.value>
10 imul
11 invokespecial #3 <app/WithoutStaticMethods.helper>
14 ireturn
The instruction at 0 (or 1), aload_0, will load the reference to the instance on the stack, and it will be consumed later by invokespecial. This instruction will put that value as the first parameter of the helper(...) function, and it is never used, as we can see here:
0 iload_1
1 iload_2
2 imul
3 iconst_1
4 iadd
5 ireturn
See there's no iload_0? It has been loaded unnecessarily.
With static methods
Now, if you declare the helper method, static, then the calculate() method will look like:
0 aload_0
1 getfield #2 <app/WithStaticMethods.value>
4 iconst_2
5 aload_0
6 getfield #2 <app/WithStaticMethods.value>
9 imul
10 invokestatic #3 <app/WithStaticMethods.helper>
13 ireturn
The differences are:
there's one less aload_0 instruction
the helper method is now called with invokestatic
Well, the code of the helper function is also a little bit different: there's no this as the first parameter, so the parameters are actually at positions 0 and 1, as we can see here:
0 iload_0
1 iload_1
2 imul
3 iconst_1
4 iadd
5 ireturn
Conclusion
From the code design angle, it makes much more sense to declare the helper method static: the code speaks for itself, it contains more useful information. It states that it does not need instance state to work.
At the bytecode level, it is much more clear what is happening, and there's no useless code (that, although I believe the JIT has no way to optimize it, would not incur a significant performance cost).
If a method does not use instance data, then it should be static. If the function is public, this will give the important efficiency boost that you don't need to create a superfluous instance of the object just to call the function. Probably more important is the self-documentation advantage: by declaring the function static, you telegraph to the reader that this function does not use instance data.
I don't understand the sentiment of many posters here that's there's something wrong with having static functions in a Java program. If a function is logically static, make it static. The Java library has many static functions. The Math class is pretty much filled with static functions.
If I need, say, a function to calculate a square root, the rational way to do it would be:
public class MathUtils
{
public static float squareRoot(float x)
{
... calculate square root of parameter x ...
return root;
}
}
Sure, you could make a "more OOPy" version that looked like this:
public class MathUtils
{
private float x;
public MathUtils(float x)
{
this.x=x;
}
public float squareRoot()
{
... calculate square root of this.x ...
return root;
}
}
But aside from meeting some abstract goal of using OOP whenever possible, how would this be any better? It takes more lines of code and it's less flexible.
(And yes, I now there's a square root function in the standard Math class. I was just using this as a convenient example.)
If the only place a static function is used and is every likely to be used is from within a certain class, then yes, make it a member of that class. If it makes no sense to call it from outside the class, make it private.
If a static function is logically associated with a class, but might reasonably be called from outside, then make it a public static. Like, Java's parseInt function is in the Integer class because it has to do with integers, so that was a rational place to put it.
On the other hand, it often happens that you're writing a class and you realize that you need some static function, but the function is not really tied to this class. This is just the first time you happened to realize you need it, but it might quite rationally be used by other classes that have nothing to do with what you're doing now. Like, to go back to the square root example, if you had a "Place" class that included latitude and longitude, and you wanted a function to calculate the distance between two places and you needed a square root as part of the calculation, (and pretending there was no square root function available in the standard library), it would make a lot of sense to create a separate square root function rather than embedding this in your larger logic. But it wouldn't really belong in your Place class. This would be a time to create a separate class for "math utilities" or some such.
You ask, "Should foo always be static, regardless of any other considerations?" I'd say "Almost, but not quite."
The only reason I can think of to make it not static would be if a subclass wants to override it.
I can't think of any other reasons, but I wouldn't rule out the possibility. I'm reluctant to say "never ever under any circumstances" because someone can usually come up with some special case.
Interesting question. In practical terms, I don't see the point in making class A's private helper methods static (unless they're related to a publicly-accessible static method in A, of course). You're not gaining anything -- by definition, any method that might need them already has an instance of A at its disposal. And since they're behind-the-scenes helper methods, there's nothing to say you (or another co-worker) won't eventually decide one of those stateless helpers might actually benefit from knowing the state, which could lead to a bit of a refactoring nuisance.
I don't think it's wrong to to end up with a large number of internal static methods, but I don't see what benefit you derive from them, either. I say default to non-static unless you have a good reason not to.
No. Never. Static methods should be an exception. OO is all about having Objects with behaviour which revolves around the object's state. Imho, ideally, there shouldn't be any (or very few) static methods, because everything unrelated to the object's state could (and to avoid leading the concept of an object ad absurdum, should) be placed in a plain old function at module level. Possible exception for factories because Complex.fromCartesian (to take a wikipedia example) reads so well.
Of course this (edit: Module-level functions) isn't possible in a single-paradigm OO language (edit: like Java) - that's why I'm such a devoted advocate of multi-paradigm language design, by the way. But even in a language exclusively OO, most methods will revolve around the object's state and therefore be nonstatic. That is, unless your design has nothing to do with OO - but in this case, you're using the wrong language.
I usually
Perform these steps in order, as needed:
a) I write some code in a member method, figure out that I can probably re-use some of this code and
Extract to non-static method
b) Now I'll see if this method needs access to state or if I can fit its needs into one or two parameters and a return statement. If the latter is the case:
Make method (private) static
c) If I then find that I can use this code in other classes of the same package I'll
Make method public and move Method to a package helper class with default visibility
E.g. In package com.mycompany.foo.bar.phleeem I would create be a class PhleeemHelper or PhleeemUtils with default visibility.
d) If I then realize that I need this functionality all over my application, I
Move the helper class to a dedicated utility package
e.g. com.mycompany.foo.utils.PhleeemUtils
Generally I like the concept of least possible visibility. Those who don't need my method shouldn't see it. That's why I start with private access, move to package access and only make things public when they are in a dedicated package.
Unless you pass in an object reference, a static method on an class enforces that the method itself cannot mutate the object because it lacks access to this. In that regard, the static modifier provides information to the programmer about the intention of the method, that of being side-effect free.
The anti-static purists may wish to remove those into a utility class which the anti-utility purists surely object to. But in reality, what does artificially moving those methods away from their only call site achieve, other than tight coupling to the new utility class.
A problem with blindly extracting common utility methods into their own classes is those utilities should really be treated as a new public API, even if it's only consumed by the original code. Few developers, when performing the refactoring, fail to consider this. Fast-forward to other devs using the crappy utility class. Later on somebody makes changes to the extension to suit themselves. If you're lucky a test or two breaks, but probably not.
I generally don't make them static but probably should. It's valuable as a hint to tell the next coder that this method CANT modify the state of your object, and it's valuable to give you a warning when you modify the method to access a member that you are changing the nature of the method.
Coding is all about communicating with the next coder--don't worry about making the code run, that's trivial. So to maximize communication I'd say that if you really need such a helper, making it static is a great idea. Making it private is critical too unless you are making a Math. like class.
Java conflates the concepts of module, namespace, adt, and class, as such to claim that some class-oriented OO-purity should prevent you from using a java class as a module, namespace, or adt is ridiculous.
Yes the methods should be static. Purely internal support methods should be private; helper methods protected; and utility functions should be public. Also, there is a world of difference between a static field, a static constant, and a public static method. The first is just another word for 'global variable'; and is almost always to be avoided, even mediation by accessor methods barely limits the damage. The second is treating the java class as a namespace for a symbolic constant, perfectly acceptable. The third is treating the java class as a module for a function, as a general rule side-effects should be avoided, or if necessary, limited to any parameters passed to the function. The use of static will help ensure that you don't inadvertently break this by accessing the object's members.
The other situation you will find static methods invaluable is when you are writing functional code in java. At this point most of the rules-of-thumb developed by OO-proponents go out the window. You will find yourself with classes full of static methods, and public static function constants bound to anonymous inner functors.
Ultimately java has very weak scoping constructs, conflating numerous concepts under the same 'class' and 'interface' syntax. You shouldn't so much 'default' to static, as feel free to use the facilities java offers to provide namespaces, ADT's, modules, etc as and when you feel the need for them.
I find it difficult to subscribe to those avoid-static-methods theories. They are there to promote a completely sanitary object-oriented model anti-septically cleansed of any deviation from object relationships. I don't see any way essential to be anti-septically pure in the practice object-orientedness.
Anyway, all of java.util.Arrays class are static. Numeric classes Integer, Boolean, String have static methods. Lots of static methods. All the static methods in those classes either convert to or from their respective class instances.
Since good old Gosling, et al, proved to be such useful role models of having static methods - there is no point avoiding them. I realise there are people who are perplexed enough to vote down my response. There are reasons and habits why many programmers love to convert as much of their members to static.
I once worked in an establishment where the project leader wanted us to make methods static as much as possible and finalize them. On the other hand, I am not that extreme. Like relational database schema design, it all depends on your data modelling strategy.
There should be a consistent reason why methods are made static. It does not hurt to follow the standard Java library pattern of when methods are made static.
The utmost importance is programming productivity and quality. In an adaptive and agile development environment, it is not only adapting the granularity of the project to respond effectively to requirements variation, but also adapting programming atmosphere like providing a conformable coding model to make best use of the programming skill set you have. At the end of the day (a project almost never ends), you want team members to be efficient and effective, not whether they avoided static methods or not.
Therefore, devise a programming model, whether you want MVP, injection, aspect-driven, level of static-avoidance/affinity, etc and know why you want them - not because some theoretical nut told you that your programming practice would violate oo principles. Remember, if you work in an industry it's always quality and profitability not theoretical purity.
Finally what is object-oriented? Object-orientation and data normalization are strategies to create an orthogonal information perspective. For example, in earlier days, IBM manuals were written to be very orthogonal. That is, if a piece of info is written somewhere in a page within those thousands of manuals, they avoid repeating that info. That is bad because you would be reading learning how to perform a certain task and frequently encounter concepts mentioned in other manuals and you would have to be familiar with the "data model" of the manuals to hunt those connecting pieces of info thro the thousands of manuals.
For the same reason, OS/2 failed to compete with Microsoft because IBM's concept of orthogonality was purely machine and data based and IBM was so proudly declaring their true object-orientedness vs Microsoft's false object-orientedness pandering to human perspective. They had forgotten we humans have our own respective varying orthogonal perspectives of information that do not conform to data and machine based orthogonality or even to each other.
If you are familiar with the topology of trees, you would realise that you could pick any leaf node and make it the root. Or even any node, if you don't mind having a multi-trunk tree. Everyone thinks his/her node is the root when in fact any could be the root. If you think your perspective of object-orientation is the canon, think again. More important is to minimise the number of nodes that are accepted as candidate roots.
There needs to be a compromise between effectiveness and efficiency. There is no point in having an efficient data or object model that can be hardly effectively used by fellow programmers.
If it does nothing with objects of this class, but actually belong to this class (I would consider moving it elsewhere), yes it should be static.
Don't use static if you can avoid it. It clashes with inheritance ( overriding ).
Also, not asked but slightly related, don't make utility methods public.
As for the rest, I agree with Matt b. If you have a load of potentially static methods, which don't use state, just put them in a private class, or possibly protected or package protected class.
It depends i.g. java.lang.Math has no method which isn't static.
(You could do a static import to write cos() instead of Math.cos())
This shouldn't be overused but as some code that is intented to be called as a utility it would be acceptable. I.g Thread.currentThread()
A static method is used to identify a method (or variable for that matter) that does not have to do with the objects created from that class but the class itself. For instance, you need a variable to count the number of objects created. You would put something like: 'private static int instances = 0;' and then put something in the constructor for that class that increments 'instances' so you may keep count of it.
Do think hard before creating a static method, but there are times when they are a good solution.
Joshua Bloch in "Item 1: Consider Static Factory Methods Instead of Constructors" in Effective Java makes a very persuasive case that static methods can be very beneficial. He gives the java.util.Collections class's 32 static factory methods as an example.
In one case, I have a hierarchy of POJO classes whose instances can be automatically serialized into XML and JSON, then deserialized back into objects. I have static methods that use Java generics to do deserialization: fromXML(String xml) and fromJSON(String json). The type of POJO they return isn't known a priori, but is determined by the XML or JSON text. (I originally packaged these methods into a helper class, but it was semantically cleaner to move these static methods into the root POJO class.)
A couple of other examples:
Using a class as a namespace to group related methods (eg, java.lang.Math).
The method truly is a private class-specific helper method with no need to access instance variables (the case cited here). Just don't sneak a this-equivalent into its argument list!
But don't use statics unthinkingly or you run the danger of falling into a more disorganized and more procedural style of programming.
No, the use of statics should be quite niche.
In this case the OP is likely 'hiding' state in the parameters passed into the static method. The way the question is posed makes this non-obvious (foo() has no inputs or outputs), but I think in real world examples the things that should actually be part of the object's state would fall out quite quickly.
At the end of the day every call to obj.method(param) resolves to method(obj, param), but this goes on at a way lower level than we should be designing at.
If it's only ever used by methods in A and wouldn't have any use outside it, then it should be static (and, probably, be placed in a Helper Class. It doesn't have any use outside A now, but there's no guarantee it will never have. Otherwise, it shouldn't.
If it doesn't have anything to do with the state of A, it could be useful at other places...
Anyway, that doesn't make a good reason for Java methods to be static by default.
Talking about this last issue, they shouldn't be static by default, because having to write 'static' make people think before writing static methods. That's a good practice when you have heterogeneous teams (the ones where Java is most useful).
When you write a static method you should keep in mind that you'r gonna use it at use-site with static-import (make it look class free) and thus it should behave just like a function which doesn't something and may or may not return something and is isolated with the state of class it belongs to. So static methods should be a rare situation.
If you seem to be making a lot of helper methods, then consider using package-private instance methods instead of private ones. Less typing, less boilerplate since you can re-use them as a helper to other classes in the same package.
I think "private static" (edit: for methods) is kind of an oxymoron in Java. The main point of static methods in my mind is to provide access to functions outside of the context of object instances. In other words, they're practically only ever useful if they're public. If you're only calling a method from within the context of a single object instance, and that method is private, it makes no sense to make it static. (edit: but, it makes no practical difference).
In this sort of case, I usually try to make the methods abstract enough that they're useful in other contexts, and I make them public in a utility class. Look at it as writing supporting library code, and think hard about your api.
Most static methods are written because
You break down a complex method into submethods, or
You wish String (or Date, or...) had some functionality that it doesn't have
The first is not bad per se, but it's often a sign that you're missing objects. Instead of working with default types such as String or List, try inventing your own classes and move the static methods to those classes.
The second reason produces the always-popular StringUtil, DateUtil, FooUtil classes. These are problematic because you have no way to discover that they exist, so programmers often write duplicates of these utility methods. The solution, again, is to avoid using String and Date all the time. Start creating your own objects, perhaps by wrapping the original object. The static methods become non-static methods of the new object.
If foo() doesn't have anything to do with Object A then why is the method in there?
Static methods should still be relevant. If there isn't anything going on then why have you written a method that has no association with it?
If foo is private, it may be anything, static or not. But, most of the time it will be not static as these is one less word to type. Then, if you need to use the state because you've changed your code, you can do it right away.
When it is protected or public, it depends on what it does. A rule of thumb is to make it not static when it isn't a part of the instance's behaviour, and make it static when it makes sense to call it without any object.
If you are unsure, ask yourself if it makes sense to override the method in a subclass.
I think letting the methods in Java to be static will result in a rather chaotic implementation by beginner who haven't understand OO correctly. We've been there and think about it. If the methods were static as default how hard it is for us to understand the OO principle?
So yes, once you mastered the concept, it is a bit itchy to have static all over the methods (as result of refactoring). Nothing we ca do about that I think.
NB: Let me guess, are you by any chance have read Clean Code?
Plenty of interesting answers.
If you desperately seek a rule, then use this:
If the code is only ever used by instance methods of a single class, then make it an instance method - it is simply an extraction of code out of an instance context - which could be refactored back into (or out of) methods that access instance state.
If the code is used by MORE THAN ONE class, and contains no access to instance variables in the class in which the method resides, then make it static.
End of story.

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