Win a copy of Getting started with Java on the Raspberry Pi this week in the Raspberry Pi forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
Sheriffs:
  • Rob Spoor
  • Devaka Cooray
  • Liutauras Vilda
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Piet Souris

Can't spot error

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What makes you think there is an error?
 
Bartender
Posts: 242
27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Two issues.

1:

This line is syntactically invalid, since you're giving it 2 names. It should be just:


2: There is no value being returned from this function, even though you specified an integer return value. For this, you probably want to return the random int you generated.

Also, the method can be static

(edit) One more thing. In your comment, you specify that this method will create a value from 0 to 5. Have you read the documentation for nextInt()? I'll quote the relevant section:

Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive)


So, the current way you're doing it can generate 0, 1, 2, 3, or 4. Is that what you wanted?
 
Sheriff
Posts: 17616
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Zachary Griggs wrote:Also, the method can be static


I've seen you mention this in at least one other post. While there's technically nothing wrong with this statement, I would caution against making a habit of falling back on static methods. In an object-oriented program, statics should be kept to a minimum.

@OP, there are many arguments against static methods so be sure you are at least aware of the consequences of having too many static methods in your program, especially if you want to write object-oriented code.

This is one of my pet peeves about how students are taught how to program in Java: they start off being taught to write all static methods. Then, when they start learning about object-orientation, suddenly the rug gets pulled out from under them and they're told (or worse, NOT told) that instance methods are what you should be normally writing.
 
Zachary Griggs
Bartender
Posts: 242
27
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, using only static methods is definitely a bad idea, but my opinion is that is a method does not reference this, it should be static since there's no need for each instance to have its own copy (as each copy will behave identically). Is there any harm to using static like this?

Imo it's a question of having the appropriate "scope". Static/instance isn't exactly a scope, but that's the best way I can describe it. Instance methods exist to use the this reference, and if it's not used, there is simply no need to let it have this in the first place. It's a reference that the method doesn't need, so the method shouldn't have it. But this only applies when the instance and static versions behave exactly the same (as is with the method in OP). If you have to write any code in order to transform it into a static method (besides the word static) then it's a poor choice.

I'd guess that the reason some beginners are taught to use only statics is that using instances requires instantiating your own class, which is not necessarily an easy concept when you're just beginning.
 
Marshal
Posts: 78428
374
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I presume that by not referencing this, you mean that the method does not use or alter any instance fields. That would make is an xx68 in the most dubious classification of methods known to modern science.
 
Zachary Griggs
Bartender
Posts: 242
27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes - it uses no instance fields and calls no instance methods. Basically, it never uses the implied (or explicit) this reference.
 
Junilu Lacar
Sheriff
Posts: 17616
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Zachary Griggs wrote:my opinion is that is a method does not reference this, it should be static since there's no need for each instance to have its own copy (as each copy will behave identically).


That's not how it works. Object-orientation is a high-level concept/abstraction. In memory, unlike with real-world objects, each instance does not "have its own copy" of instance methods.

Is there any harm to using static like this? ... Imo it's a question of having the appropriate "scope". Static/instance isn't exactly a scope, but that's the best way I can describe it. Instance methods exist to use the this reference, and if it's not used, there is simply no need to let it have this in the first place. It's a reference that the method doesn't need, so the method shouldn't have it. But this only applies when the instance and static versions behave exactly the same (as is with the method in OP).


As I said, there are many arguments against static methods. If you read the first article returned by that search, the last sentence summarizes the objection to static methods:

Static methods are procedural! In OO language stick to OO. And as far as Math.abs(-5) goes, I think Java got it wrong. I really want to write -5.abs(). Ruby got that one right.


Some people even go so far as to say that Java isn't truly object-oriented but rather that it's class-oriented. The reasons you give are probably influenced by this nature of Java. They are also due in part to thinking about optimization (which turns out to be based on a misunderstanding of how object-oriented code works internally) and partly due to a more procedural rather than object-oriented mindset. That's a double whammy, IMO.

I'd guess that the reason some beginners are taught to use only statics is that using instances requires instantiating your own class, which is not necessarily an easy concept when you're just beginning.


Well, it seems to me that most instruction on Java out there does that, not just some. IMO, we don't give kids enough credit and they're going about it all wrong. I think that if you're going to teach an object-oriented language, the first thing you want to teach is why do you want to think in terms of objects. This is the context that kids lack and want for the most. I think this context is what older generations of programmers who grew up learning and writing procedural code first have that the many in the newer generations of programmers lack.

Older generations of programmers understand the problems that come with procedural code and therefore can put object-orientation into context. Yes, it was a paradigm shift but once the shift was made and the mindset around objects was fully grasped, the benefits were obvious. The newer generations of programmers never had to undergo that paradigm shift. All they know or are taught is that's the weird way it's supposed to be done. Therein lies the rub.

I will think nothing of writing and refactoring to methods like this:

By your reasoning, this should be a static method. I would never think twice about leaving this as an instance method though.

I don't know if this is enough to dissuade you from automatically thinking "no access to instance, then make it static" because it seems to have become a reflex for you now. And other than what I've already said and the other reasons I have cited, I can give you no other reason to avoid this kind of thinking. It's just one of those things that perhaps gets chalked up to a "difference in style" but I think really boils down to "I seen enough crap to know that this is something to avoid" and R-Mode thinking.
 
Junilu Lacar
Sheriff
Posts: 17616
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

I wrote:I think that if you're going to teach an object-oriented language, the first thing you want to teach is why do you want to think in terms of objects. This is the context that kids lack and want for the most. I think this context is what older generations of programmers who grew up learning and writing procedural code first have that the many in the newer generations of programmers lack.

Older generations of programmers understand the problems that come with procedural code and therefore can put object-orientation into context. Yes, it was a paradigm shift but once the shift was made and the mindset around objects was fully grasped, the benefits were obvious. The newer generations of programmers never had to undergo that paradigm shift. All they know or are taught is that's the weird way it's supposed to be done.


Well, in a way I guess these younger programmers do have to go through a paradigm shift. This happens when they are first taught to write static methods, then are taught about object-orientation and now have to think objects and instances. That's not the same as what we older guys went through though. When it all happens during the course of a semester of study, the shift does not happen consciously as it did for the older guys who started out in procedural languages like C, Pascal, BASIC, COBOL, Fortran, etc. If you start out writing procedural Java code, which is what code with lots of static methods really is, the shift to objects and instance methods is subtle and, yes, it can be very confusing. What makes this worse is that instructors don't seem to be explaining the why of object orientation before they make students undergo that paradigm shift.
 
Sheriff
Posts: 8786
629
Mac OS X VI Editor BSD Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Junilu Lacar wrote:I will think nothing of writing and refactoring to methods like this:
By your reasoning, this should be a static method. I would never think twice about leaving this as an instance method though.

I'm not entirely agree with that.

Because still, method isValid(..) needs to fit to class requirements. What is valid for instance in Apple class, not necessarily is valid in Peach class - apples might be valid the ones which are RED or GREEN only, while Peach the ones which are ORANGE, even tho they are not using any internal instance members. So, in my head, this method still indirectly uses some knowledge about the particular class which requirements going to satisfy, so I wouldn't even think a second about such method as static too.

Zachary Griggs's given example about randomNumber0to5() less likely going to use some knowledge of particular class, it just gives a pseudo random number, either it would for an Apple class or for a Peach class, and I'm here with Zachary, to go with static.


@Junilu
For the well experienced guys, who has extensive amount of experience in the field, yes, it causes concerns, but probably because (as you mentioned yourself) you went through all the stages starting from procedural paradigms to OO. You right away can identify actual possible pitfalls of doing things not in the most safest way you can come up with (because you have a lot to compare), BUT for the field newcomers, such problems do not even come up to head, and probably won't even come up ever.

I really think you're right, that even tho for the "Hello, World" program looks enough to have static main method to demonstrate how most simplest program works, but it seems for most of the students it gives a continuous misleading understanding that this is how it supposed to be in most programs, AND that is why every single day we see here most static methods than non static.

But if student fully understand the static context, using it carefully probably it is not an error, but rather one of the options Java programming language offers. Trying all possible ways to avoid it probably wouldn't be quite right too.
 
Zachary Griggs
Bartender
Posts: 242
27
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I don't see why Java being OOP means you can only use object oriented programming. Sometimes a procedural method is what fits best for what you want to do, if the code inside works as a simple procedure. Ignoring static altogether is just ignoring one of the options Java gave to us. You can absolutely write all your methods as instance methods and have it work, just like you can write all your fields as public ones and have it work. But in both cases, you're providing information to methods that don't need to use it. Static is a question of encapsulation to me. Something like -5.abs() would be cool, but it doesn't fit Java's style: numbers in java are not objects so they don't have methods (unless you use the wrapper class).

Even your isValid example - that does not have any context to a specific instance of your class, but to the class itself. Making it a static method in the class says exactly that, it forces it to belong to the class in general rather than each instance.
 
Junilu Lacar
Sheriff
Posts: 17616
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Let me highlight what I wrote again, just so it doesn't get misconstrued/misinterpreted as something else...

@OP, there are many arguments against static methods so be sure you are at least aware of the consequences of having too many static methods in your program, especially if you want to write object-oriented code.


To recap, I didn't say "avoid writing static methods" nor did I say "don't write static methods at all". To tell you the truth, I do write static methods once in a while. I guess there is some merit to the idea that if a method does not access anything specific to an instance then it's a candidate to be a static method but when I'm in object-oriented design thinking mode, this is probably the last thing that will enter my mind, as shown in the example I gave about a formula that I would extract to its own instance method without missing a beat to think about turning it into a static method.

Now, turning to the example of the random number generation method. Taken out of context, we could argue one side or the other until we're all blue in the face. But here's a thought: What if that method was supposed to be part of a Dice class (or if you want to be grammatically correct, a Die class)? What if that method was supposed to determine what face of the dice was up when it is tossed?

You could argue that it really should be this, in which case, it clearly needs to be an instance method:

Either implementation is valid though. However, we all know that most if not all programmers will write less than ideal code for their first cut. If you keep the "no instance access, make it a static" guideline in the forefront of your thinking, then that could lead you seriously astray from the first version. That's why refactoring and thinking about design is so critical. My main concern is around object-oriented vs procedural thinking. Since I like to err on the side of caution, I would rather err on the side of writing an instance method rather than a static to avoid any potential traps that procedural code might have in my object-oriented design.

So again, Mr. Andy Hunt's advice is proven good: Tip #2 Always Consider Context. This is in his book Pragmatic Thinking & Learning: Refactor Your Wetware. Andy also discusses L-Mode and R-Mode thinking and how many experience people can't explain why they do things in certain ways except to say something along the lines of "My experience tells me to do it this way."
 
Bartender
Posts: 732
10
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you create a static method, you should ask yourself "Why is this method in this particular class, as opposed to being in another class?" Especially if it doesn't take an instance the class as an argument. is it really a generic method that should be in a separate utility class that contains only static methods (such as Math)?

For example, take the original Dice.roll() method of this thread. My answer would be "Well, it really does belong in Dice. So why is it static? Then I would eventually realize that it should be an instance method because besides returning the roll value, it should also save that value as an instance variable to keep track of its current state.
 
Junilu Lacar
Sheriff
Posts: 17616
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks, Fred. That's exactly the kind of thinking you need to mitigate the danger of following a context-free rule like "no instance access, make it a static". Again, you need to look at the bigger picture rather than just automatically following the rule. I'm not saying that rule is bad but you should be aware of other considerations as well before making a decision. Pressed for time, I prefer to leave things as instance methods when nothing else jumps out at me.
 
Fred Kleinschmidt
Bartender
Posts: 732
10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You should also question the declaration of a method as being "static" when it takes a single instance of the current class as one of its arguments. Such a method should almost always be an instance method( eliminating that argument).
 
Junilu Lacar
Sheriff
Posts: 17616
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Zachary Griggs wrote:I don't see why Java being OOP means you can only use object oriented programming. Sometimes a procedural method is what fits best for what you want to do, if the code inside works as a simple procedure. Ignoring static altogether is just ignoring one of the options Java gave to us.


I don't necessarily disagree with that but again, if you're going to write OO programs, it's best to try to stick to OO. When you give inexperienced programmers context-free rules, it's good to balance that out with caveats because there are always exceptions to the rules. IMO, it's important to think about "sticking to OO" before thinking about "make it static if no instance access".

One of the things that I have had to deal with over the years is a preponderance of so-called "utility" classes that are full of methods that actually beg to be instance methods. It's very easy for programmers to get into the habit of thinking "let's make this static and stick it in the Utility class." The difference is recognition. Most programmers I have met are not able to recognize when the code that they're making into a global utility method actually makes more sense as an instance method. This affects the rest of the design because once you have many parts of the code base that's more procedural than OO, less experienced programmers tend to lean towards writing more procedural code that they would OO code. Let's face it, OO thinking is not that easy even though it is intended to make it easier to organize ideas and behaviors in our programs.

It's kind of like a shovel: it's meant to be used to dig dirt. Occasionally, you might be able to pound a wooden stake into the ground or use it as a lever to lift up the corner of something heavy but you probably want to do that only in a crunch when there's no sledgehammer or crowbar handy. Otherwise, to think "I need a shovel" when you see a nail instead of "I need a hammer to pound that in" or "I need a crowbar to pull that out" is just not the right way to think, right? If you start telling or showing people who have never used a shovel before that they can use it to pound on things or as a pry but don't tell them about the other options of the hammer or crowbar, then they'll go through life thinking that a shovel is something that you can use to dig, pound, and pry, and that's perfectly normal. When the shovel is used more often to pound or pry rather than to dig, then you're not making very good use of the tool and it makes the work more difficult than it needs to be. Only with software, the difficulty with dealing with a lot of procedural code in an OO language tends to spread and it affects more people.

Even your isValid example - that does not have any context to a specific instance of your class, but to the class itself. Making it a static method in the class says exactly that, it forces it to belong to the class in general rather than each instance.


But it should make you think about the design first. First questions I would ask is "What are we validating? Where are we getting this value from? What's the context in which this method will be called? Can we get rid of the parameter to make this more OO instead of making it static and more procedural?" Just following your rule eliminates this conversation and the opportunity to possibly improve the OO-ness of your code and design. This is the potential trap that I'm wary of falling into.
 
Junilu Lacar
Sheriff
Posts: 17616
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This has been an interesting discussion but I'd like to reel it back in so that OP can see its relevance with respect to what he is trying to do.

@OP Arran Farrell: What is the context in which the method you posted is used? What class contains this method? What is the purpose of that class and how does this random number generation functionality support that purpose? What are the semantics for its (the class) use? You probably should look at that besides just the method alone, whether or not it truly is a good candidate as a static method.
 
Bartender
Posts: 5448
212
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hmm... maybe OP left the building a long time ago. I think his/her question was already answered.
 
Junilu Lacar
Sheriff
Posts: 17616
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I was holding out hope, Piet. It was a long shot anyway
 
Your mind is under my control .... your will is now mine .... read this tiny ad
Low Tech Laboratory
https://www.kickstarter.com/projects/paulwheaton/low-tech-0
reply
    Bookmark Topic Watch Topic
  • New Topic