Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes 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
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

When to write static methods and non static methods?

 
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all, I am writing a web application using spring 3.x framework. I have to validate the form data. For some reason we are not using jsr 303 hibernate-validator. So we wrote our own validator class. For every request we create a validator object and pass the form object to it.

The validator mainly does two things

1. Check whether the input is empty/null/contains only white spaces
2. Match with a regular expression to validate the text

So if there are 4 fields, in the first phase I am checking whether the fields are not null/empty. In the second phase I am validating the text against a regex pattern.T am calling the methods like thisI would like to know can I declare the methods as static or not. I would also like to know when to declare a method as static.

Can anyone please tell me. Thank you all in advance, good day.
 
chaitanya karthikk
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Okay, I think I got my answer. After searching here I understood that

If any operation is not dependent on creation of an object. Since I am not creating any new object inside these two methods I can justify it can be static.

However I could not understand this point.

If the method is not using any instance variable."

and this point

If you are writing utility classes and they are not supposed to be changed.

. What does not supposed to be changed means? Does it means the code or data which is shared across different threads?
 
Marshal
Posts: 76464
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I presume you are familiar with the concept of a utility class?
 
chaitanya karthikk
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:I presume you are familiar with the concept of a utility class?

All I know about utility class is, all methods are static, takes some data as input, validates, converts from one form to other and return the converted data such as rupee to dollars, miles to kilometers etc. But which does not modify the original data, I mean it does not act on the object's directly.
 
Campbell Ritchie
Marshal
Posts: 76464
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Your getXxxFromKeyboard methods in a utility class might modify objects. For example, the input is usually in String form, but it might be converted to an int (which is a primitive) or a BigDecimal, and that int, or a reference to the BigDecimal, returned.
Having had a few hours, I think the bit about not modifying the object may be misleading. You do not usually have an object of a utility class. I seem to refer to utility classes all the time, so you can have a reference too. Try here. You can see that utility class has only static members, and no instance fields, and because of the private constructor, it cannot be instantiated (or subclassed). If it cannot be subclassed, and cannot be instantiated, then there is never anything to change. I think that is what it means.
In order to confuse you completely, I shall refer you to the Campbell Ritchie classification of methods . If you go back to what they said on SO, I think you will find the two are quite similar. Notice, if you never use or change instance data, then you can consider making a method static. An abstract method, which includes methods in interfaces, is never static.
 
chaitanya karthikk
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Notice, if you never use or change instance data, then you can consider making a method static.

What do you mean by never use instance data?

What if my static method takes an object like this

StaticClass.myStaticMethod(takesAnObjectOrInstance)

In the method I am accessing the instance data like this

takesAnObjectOrInstance.getValue()

.

Are you saying this is a bad approach? Why? Can you please explain Ritchie.

Thank you in advance.
 
chaitanya karthikk
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:
In order to confuse you completely, I shall refer you to the Campbell Ritchie classification of methods . If you go back to what they said on SO, I think you will find the two are quite similar. Notice, if you never use or change instance data, then you can consider making a method static. An abstract method, which includes methods in interfaces, is never static.


Well I am confused a bit.

5: Those which require, seek, inspect or use information from inside their own object.
6: Those which do not require any information from inside their own object.
7: Those which alter, insert or modify information inside their own object.
8: Those which do not modify insert or alter any information inside their own object.

You said that a method which does not use information inside their own object and does not modifies information inside their own object can me made as static.

What do you mean by "inside their own object"? Does inside their own object refer to the object/instance passed as an argument to the method or it is an object created inside the same method?Can you please clear my confusion? Thank you.
 
chaitanya karthikk
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
<<Deleted this quote.>>
 
Campbell Ritchie
Marshal
Posts: 76464
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Their own object means the instance on which you might call the method. It does not mean parameters arguments or local variables.
Does your method make any reference to any instance fields or instance methods? Static members do not count.
 
chaitanya karthikk
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Their own object means the instance on which you might call the method. It does not mean parameters arguments or local variables.
Does your method make any reference to any instance fields or instance methods? Static members do not count.

This is my utility classAnd I am not using any instance fields and instance methods inside the static methods. Does these methods deserve to be static now?
 
Campbell Ritchie
Marshal
Posts: 76464
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That does not look like a utility class, but a means of calling the StringUtils class and Errors class from elsewhere.
Those methods do look appropriately static. Since you have no instance fields in that class, you should give it a private constructor to prevent instantiation.
 
Campbell Ritchie
Marshal
Posts: 76464
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And why have you got two classes called StringUtils in your application? That looks like a sure‑fire recipe for confusion.
 
chaitanya karthikk
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:That does not look like a utility class, but a means of calling the StringUtils class and Errors class from elsewhere.
Those methods do look appropriately static. Since you have no instance fields in that class, you should give it a private constructor to prevent instantiation.

Yes instead of writing the code repeatedly I created my own method named hasText which will take 4 arguments and checks whether there is any text, if no text is available it adds a error message to the errors object which is passes as argument to it.

The second method takes a regex and checks whether the passed text matches the pattern. If it does not match again the errors object is set with the appropriate key.

I am not calling Errors. I am adding keys to it.

And yes I will declare a private constructor in it. Thanks for pointing at it.

At whole, if I declare a private constructor in it, do the methods deserve to be static and the can the class be called as utility class? Ofcourse I will change the class name also.
 
Campbell Ritchie
Marshal
Posts: 76464
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you write a private constructor, …

You will have to use the class as a utility class with static members only, and never instantiate it …

Or…

Give the class a static factory method, and use it as an ordinary object with instance methods. This sort of class cannot be subclassed, and should be marked final.
 
chaitanya karthikk
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I will declare a private constructor in it. Thank you Ritchie
 
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

chaitanya karthikk wrote:For every request we create a validator object and pass the form object to it...


I've come fairly late to this discussion, but I will say one thing: what you've written above doesn't fit with the idea of a static utility class, although one might be part of the implementation.

It seems to me far more likely that you will want a specific validator object for each form, which call methods in your utility class; but there are several ways to go about it, so don't take my word for it.

Also: your code is a bit verbose - and possibly wrong. What happens if org.springframework.util.StringUtils.hasText(value) returns false in your validateText() method?

Finally: Could you please edit your posts to break up those enormous comment lines in your code? It makes your thread very hard to read.
I'd do it myself, but there are LOTS of them.
I suggest you read the UseCodeTags page again - thoroughly.

Winston
 
chaitanya karthikk
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Okay, let me explain you how I am validating the form data.

I have a controller in place (Spring 3.0), there is an appropriate method handler which will receive a BindingResult as an argument passed by spring container. In the controller I am creating a validator object say DealerCenterValidator object which validates the dealer center form. On the DealerCenterValidator I am calling the validator method which takes the form object and BindingResult object. The validator makes use of the StringUtils class's static methods to validate the data.Inside the PreferredDealerUpdateValidatorAre you saying this is not the right approach?

Winston Gutkowski wrote:
Also: your code is a bit verbose - and possibly wrong. What happens if org.springframework.util.StringUtils.hasText(value) returns false in your validateText() method?

If it returns false I will not do the pattern matching. Simple. In fact when there is some data we have to validate the text. If there is no data what is the use in running the pattern.
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

chaitanya karthikk wrote:Are you saying this is not the right approach?


No, but I don't see how your StringUtils class - and certainly not its hasText() method - is providing you with anything more than the one from springframework already gives you.

If it returns false I will not do the pattern matching. Simple. In fact when there is some data we have to validate the text. If there is no data what is the use in running the pattern.


Right, but it also won't call errors.rejectValue(), so it will fail silently. If that's what you want, fine; just be aware of it.

Personally, I dislike methods that return void.

Winston

PS: Could you please deal with those enormous lines as I asked? I'll leave any further responses to others until you do.
 
chaitanya karthikk
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Winston Gutkowski wrote:I don't see how your StringUtils class - and certainly not its hasText() method - is providing you with anything more than the one from springframework already gives you.

Yes, my hasText method does nothing more than the method given by spring framework. Now suppose that I am having 10 fields in the ui. I will have write lots of lines like this
I have to repeat this code 10 times. Which makes a lengthy code. Instead I wrote my own method and passed the arguments and called the method 10 times.

Winston Gutkowski wrote:Right, but it also won't call errors.rejectValue(), so it will fail silently. If that's what you want, fine; just be aware of it.

In my validate method I am first checking whether the field has some text in it or not. If text is not there I am rejecting it. In the second phase I am validating the text. In the second phase I am sure that there is some text in it.

Well now you can say why dont you use an if else condition. The problem is not all fields are mandatory. I can club both using an if else condition . The only problem is not all fields are mandatory. Here arises the problem. However I can deal with that also. Only to keep the code simple I wrote it like this for understandability.

PS: Could you please deal with those enormous lines as I asked? I'll leave any further responses to others until you do.

Well I removed all code.
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

chaitanya karthikk wrote:Well I removed all code.


You missed one, which I've now fixed. See how much easier it is to read now?

Winston
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

chaitanya karthikk wrote:In my validate method I am first checking whether the field has some text in it or not. If text is not there I am rejecting it. In the second phase I am validating the text. In the second phase I am sure that there is some text in it.


In which case the check is redundant. Personally, I think that's a dangerous assumption and, if you really feel you need void methods, I'd probably do it something like:you could even make the first of those private (although it still looks redundant to me).

I'd also give your class a different name, as Campbell suggested.

Winston
 
chaitanya karthikk
Ranch Hand
Posts: 806
MySQL Database Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Winston Gutkowski wrote:I'd also give your class a different name, as Campbell suggested.

Winston

Yes I changed the name to VWStringUtils. I will change the code not to be redundant. Thanks for your suggestions Winston.
 
Winston Gutkowski
Bartender
Posts: 10780
71
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

chaitanya karthikk wrote:Thanks for your suggestions Winston.


You're most welcome.

Winston
 
The only thing that kept the leeches off of me was this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic