[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

is it candidate for being static

Posted on 2004-11-22
39
Medium Priority
?
263 Views
Last Modified: 2010-03-31
Hi,
  I have a fn like this

public boolean fnA()
{

   new CommonUtil(props).validateReq(tn,tracknum,state);

}
the validateReq in CommonUtil class validates request to see if tn,tracknum and state are in valid format.Should the validateReq be defines as static? This method is called only once and not referenced anywhere else
0
Comment
Question by:skn73
  • 11
  • 10
  • 8
  • +2
39 Comments
 
LVL 92

Expert Comment

by:objects
ID: 12651674
if it doesn't require access to any of CommonUtil's member vars then yes it can be static.
If it does need to use member vars then it cannot.
0
 

Author Comment

by:skn73
ID: 12651731
by it you mean fnA()?
0
 
LVL 92

Expert Comment

by:objects
ID: 12651782
no the method you want to be static, validateReq()
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 37

Expert Comment

by:zzynx
ID: 12652307
>> validateReq ... validates request to see if tn,tracknum and state are in valid format.
>> Should the validateReq be defines as static?
if validateReq just needs tn, tracknum and state and can do what it has to on base of just that info,
yes, it is a serious candidate to be defined as static. That way you can call it like
       CommonUtil.validateReq(tn, tracknum, state);
and don't need a CommonUtil object to call it on.
0
 
LVL 92

Expert Comment

by:objects
ID: 12652427
Easiest way to check if it can be declared static is to simply declare it static and compile it.
It won't compile if it uses any instance vars or methods.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 12652815
It's not whether it (validateReq(...)) uses the instance members of *CommonUtil* or not, it's about whether it uses the vars from the *enclosing class of fnA() or not*; like zzynx says you don't need the object, you just call CommonUtil.validateReq(...).

You are maybe thinking of the case where validateReq(...) could be in the client class itself, in which case you would only make it static if the objects of that class all shared the same instance var values, otherwise you need to make the method an instance method so that it handled the current values for those instance vars using their correct values.
0
 
LVL 92

Expert Comment

by:objects
ID: 12652930
> it's about whether it uses the vars from the *enclosing class of fnA() or not

fnA() has nothing to do with it.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12652980
>> It's not whether it (validateReq(...)) uses the instance members of *CommonUtil* or not
It's - like objects said - whether CommonUtil member vars are used or not. Unless they are static too.
0
 
LVL 92

Expert Comment

by:objects
ID: 12653023
> whether CommonUtil member vars are used or not. Unless they are static too.

If they are static then they are not member vars.
And its not only member vars, but also member methods.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 12653148
That's not what I am saying.

IMHO the questioner may have a bit of confusion in his mind - CommonUtil may as well have all its members as static, since as zzynx already said, you don't need an instance of it.

What I am saying is that the question that is being asked only arises when the values of the instance vars are different, in which case they can not be static. But the reason it doesnt apply to CommonUtil, is that CommonUtil is common, and it is simply a class that exists as a utility that other classes can call on.

>> fnA() has nothing to do with it.

As for this, I never said that fnA() had anything to do with it : I said the **enclosing class** of fnnA().

0
 
LVL 92

Expert Comment

by:objects
ID: 12653180
> CommonUtil may as well have all its members as static, since as zzynx already said, you don't need an instance of it.

there is nothing posted to suggest that.

> As for this, I never said that fnA() had anything to do with it : I said the **enclosing class** of fnnA().

sorry, the **enclosing class** of fnnA() has nothing to do with it.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 12653240
There doesn't need to be anything posted to suggest it - the reason for having a CommonUtil is so that it is inclusive (common / static), and not exclusive (instance / non-static). ;)

>> sorry, the **enclosing class** of fnnA() has nothing to do with it.

The enclosing class of fnA() has a lot to do with it. That is where the values to be checked are coming from.

Having said all that, this is a peculiar question, since if "tn,tracknum,state" are instance vars, then the only place that really knows whether they are correct or not would normally be the instance itself.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12653259
skn73, can you say something? ;°)
0
 
LVL 92

Expert Comment

by:objects
ID: 12653272
> the reason for having a CommonUtil is so that it is inclusive (common / static), and not exclusive (instance / non-static).

Again there is nothing to suggest that, in fact the only mention shown for CommonZUtils suggests otherwise.

> The enclosing class of fnA() has a lot to do with it. That is where the values to be checked are coming from.

incorrect

> since if "tn,tracknum,state" are instance vars, then the only place that really knows whether they are correct or not would normally be the instance itself.

again, they have nothing to do with it.

0
 
LVL 17

Expert Comment

by:krakatoa
ID: 12653280
>> again, they have nothing to do with it.
 LOL.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 12653307
We could use a good gc() here at the moment - skn73 - you there?
0
 
LVL 1

Expert Comment

by:Ortokobold
ID: 12653591
IMHO it's more design question, than language-syntax question. If "validateReq" is to used only once, why to put it to the "CommonUtils" class? Maybe it just should be a private member of the class where it is used (the most obvious solution).
0
 
LVL 92

Expert Comment

by:objects
ID: 12653669
The number of times it is used is not the issue here, it is whether it can be made static or not which is dictated by whether it makes any use of member vars or members. And as we don't have that information it can be determined either way.
As I said earlier an easy test is to make it static and attempt to compile it.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 12653676
It's not really to do wtih "language syntax". It could be regarded as a design issue in a way - if by design you accept that this question is predetermined by OOP principles themselves anyway.
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 12653718
It's true that *mechanically* the class will not compile properly if it makes use of instance vars with incompatible modifiers, but that is *still* not the issue - the issue is whether the utility class is using the vars of the enclosing class of fnA().

How can the utility keep track of all the instance vars from all  the objects it is supposed to check, *unless* all the checking does is to validate them against a range - or format, as the question in fact states. If it is a question of checking the *format* then that's fine, because presumably, that is at least fixed.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12653781
Hey guys, don't you think you better stop posting?
0
 
LVL 92

Expert Comment

by:objects
ID: 12653792
> the issue is whether the utility class is using the vars of the enclosing class of fnA().

sorry but thats incorrect. the utility class has no access or knowledge of the calling classes vars.

0
 
LVL 17

Expert Comment

by:krakatoa
ID: 12653875
>> sorry but thats incorrect. the utility class has no access or knowledge of the calling classes vars

Where are you saying that this function call :

>> .validateReq(tn,tracknum,state);

obtains its params from?
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 12653883
>> Hey guys, don't you think you better stop posting?

Not sure - what do you think? ;)
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 12654045
The real point is it doesn't matter whether the utility is static or not, since you call into it from outside anyway. Your concerns about "static" are only relevant if you were talking about a utility method *inside your current object class* - in which case this could very well be made static, if all the method does is to check the values against a range or a format principle.
0
 

Author Comment

by:skn73
ID: 12656224
Sorry! I am seeing this postings only now ! Thanks for all ur input ..
public  boolean fnA( String tn, String state, String txnum) throws ServicesApplicationException
{
  try {        
 new CommonUtil(props).validateReq(ServicesConstants.DATA_NOT_APPLICABLE,tn,state);
}
catch( ...)

}
0
 

Author Comment

by:skn73
ID: 12656240
common Util.java has
public class CommonUtil {
      
      private Pattern reTn;
      private Pattern reQualTrackNum;
      private Pattern reState;
      private boolean reInit;
      private Props props;
      
      public CommonUtil(Props p)
      {
            props = p;
      }
      
      private synchronized void setupRePatterns() throws ServicesApplicationException
      {
         try
         {
               TraceLog.write(TraceLog.DEBUG, "Initializing regular patterns...");
      
               if (reInit)
                  return;
               reTn = new Perl5Compiler().compile(props.getValue(ServicesConstants.REGEXP_TN_10DIGIT), Perl5Compiler.READ_ONLY_MASK);
               reQualTrackNum = new Perl5Compiler().compile(props.getValue(ServicesConstants.REGEXP_QUAL_TRACK_NO), Perl5Compiler.READ_ONLY_MASK);
               reState = new Perl5Compiler().compile(props.getValue(ServicesConstants.REGEXP_STATE_2CHAR), Perl5Compiler.READ_ONLY_MASK);

               reInit = true;
               return;
         }
        
         catch(Throwable t)
         {
               ServicesError.throwProcessingException(t, "ServiceRequestBean::setupRePatterns()", props);
         }

         return;
      }
      
      public void validateReq(String qualTrackNo, String tn, String state) throws ServicesApplicationException
      {
            String fctStr = "ServiceRequestBean::checkReq()";
      
            PatternMatcher re = new Perl5Matcher();

            if (!reInit)
                  setupRePatterns();
      
            try
            {
               // EDIT THE TELEPHONE NUMBER
               if ( (tn == null) ||
                        (!re.matches(tn, reTn)) )
                        ServicesError.throwServicesException(props.getValue(ServicesConstants.INVALID_DATA_ERROR_CODE),
                                                                         props.getValue(ServicesConstants.INVALID_DATA_ERROR_MSG) + " -- Invalid TN",
                                                                         "The request data is invalid -- TN", fctStr);

               // EDIT THE QUALIFICATION TRACKING NUMBER
              if ( (( qualTrackNo == null) ||  (!re.matches(qualTrackNo, reQualTrackNum)) ) &&
                        (!qualTrackNo.equals(ServicesConstants.DATA_NOT_APPLICABLE)))
                        ServicesError.throwServicesException(props.getValue(ServicesConstants.INVALID_DATA_ERROR_CODE),
                                                                               props.getValue(ServicesConstants.INVALID_DATA_ERROR_MSG) + " -- Invalid Qualification Tracking Number",
                                                                               "The request data is invalid -- Qualification Tracking Number", fctStr);
      

                  // EDIT THE STATE
                  if ( state == null ||
                        (!re.matches(state, reState)) )
                        ServicesError.throwServicesException(props.getValue(ServicesConstants.INVALID_DATA_ERROR_CODE),
                                                                               props.getValue(ServicesConstants.INVALID_DATA_ERROR_MSG) + " -- Invalid State",
                                                                               "The request data is invalid -- State", fctStr);
            }
            catch(ServicesApplicationException sae)
            {
               throw sae;
            }
            catch(Throwable t)
            {
                  ServicesError.throwProcessingException(t, "ServiceRequestBean::checkReq()", props);
            }
            return;
      }
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12656413
Well, what does it give if you make it static? Does it compile?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12656453
No, it won't.
Since in validateReq() you call setupRePatterns(); which is not static.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12656483
Main conclusion: you can't (easily) make it static, so better leave it as it is.
0
 

Author Comment

by:skn73
ID: 12656676
can I make commonUtil a singleton
0
 

Author Comment

by:skn73
ID: 12657422
the big problem is many dont like this statement "new CommonUtil(props).validateReq(ServicesConstants.DATA_NOT_APPLICABLE,tn,state);"   starting with new and I am wondering how to make it better?

public  boolean fnA( String tn, String state, String txnum) throws ServicesApplicationException
{
  try {        
 new CommonUtil(props).validateReq(ServicesConstants.DATA_NOT_APPLICABLE,tn,state);
}
catch( ...)

}
0
 
LVL 92

Assisted Solution

by:objects
objects earned 1000 total points
ID: 12659127
To make it static you'd need to change it to something like:

public class CommonUtil {
     
     private static Pattern reTn;
     private static Pattern reQualTrackNum;
     private static Pattern reState;
     
     private static void setupRePatterns(Properties props) throws ServicesApplicationException
     {
        try
        {
             TraceLog.write(TraceLog.DEBUG, "Initializing regular patterns...");
     
             reTn = new Perl5Compiler().compile(props.getValue(ServicesConstants.REGEXP_TN_10DIGIT), Perl5Compiler.READ_ONLY_MASK);
             reQualTrackNum = new Perl5Compiler().compile(props.getValue(ServicesConstants.REGEXP_QUAL_TRACK_NO), Perl5Compiler.READ_ONLY_MASK);
             reState = new Perl5Compiler().compile(props.getValue(ServicesConstants.REGEXP_STATE_2CHAR), Perl5Compiler.READ_ONLY_MASK);

             reInit = true;
             return;
        }
       
        catch(Throwable t)
        {
             ServicesError.throwProcessingException(t, "ServiceRequestBean::setupRePatterns()", props);
        }

        return;
     }
     
     public static void validateReq(Properties props, String qualTrackNo, String tn, String state) throws ServicesApplicationException
     {
          String fctStr = "ServiceRequestBean::checkReq()";
     
          PatternMatcher re = new Perl5Matcher();

         setupRePatterns(props);
     
          try
          {
             // EDIT THE TELEPHONE NUMBER
             if ( (tn == null) ||
                    (!re.matches(tn, reTn)) )
                    ServicesError.throwServicesException(props.getValue(ServicesConstants.INVALID_DATA_ERROR_CODE),
                                                             props.getValue(ServicesConstants.INVALID_DATA_ERROR_MSG) + " -- Invalid TN",
                                                             "The request data is invalid -- TN", fctStr);

             // EDIT THE QUALIFICATION TRACKING NUMBER
            if ( (( qualTrackNo == null) ||  (!re.matches(qualTrackNo, reQualTrackNum)) ) &&
                    (!qualTrackNo.equals(ServicesConstants.DATA_NOT_APPLICABLE)))
                    ServicesError.throwServicesException(props.getValue(ServicesConstants.INVALID_DATA_ERROR_CODE),
                                                                  props.getValue(ServicesConstants.INVALID_DATA_ERROR_MSG) + " -- Invalid Qualification Tracking Number",
                                                                  "The request data is invalid -- Qualification Tracking Number", fctStr);
     

               // EDIT THE STATE
               if ( state == null ||
                    (!re.matches(state, reState)) )
                    ServicesError.throwServicesException(props.getValue(ServicesConstants.INVALID_DATA_ERROR_CODE),
                                                                  props.getValue(ServicesConstants.INVALID_DATA_ERROR_MSG) + " -- Invalid State",
                                                                  "The request data is invalid -- State", fctStr);
          }
          catch(ServicesApplicationException sae)
          {
             throw sae;
          }
          catch(Throwable t)
          {
               ServicesError.throwProcessingException(t, "ServiceRequestBean::checkReq()", props);
          }
          return;
     }
0
 
LVL 92

Expert Comment

by:objects
ID: 12659164
> can I make commonUtil a singleton

thats another option, you'd need to add something like the following to your existing code to achieve that:


private static CommonUtils instance = null;

public static CommonUtils getCommonUtils(Properties props)
{
   if (instance==null)
   {
      instance = new CommonUtils(props);
   }
   return instance;
}


then to call it you would use:

CommonUtil.getInstance(props).validateReq(ServicesConstants.DATA_NOT_APPLICABLE,tn,state);
0
 
LVL 1

Accepted Solution

by:
Ortokobold earned 1000 total points
ID: 12659862
So, it IS a design question after all (thanks for telling us! ;-))

Here's my proposition:

1. CommonUtil should be pure helper class. So it should contain only common "static" methods, be delcared as "final", and have private constructor (no instances of this class are allowed).

2. You should create another class for matching you regular expressions. Let's call it "DataValidator". It should have the following methods:

public DataValidator(props); // pass the props to the constructor, set members with regular expressions
boolean isValidQualTrackNum(String qualTrackNum); // return true, if this qual track num is valid
boolean isValidState(String state);
boolean isValidTn(String tn);

// AND:
boolean isValidRequest(String qualTrackNum, state, tn)
{
  return isValidQualTrackNum()
    && isValidState(state)
    && isValidTn(td);
}

3. Now you can call the validateReq like this:

DataValidator dataValidator = new DataValidator(props);

if (!dataValidator.isValidRequest(null, tn, state))
{
  String errorMsg = props.getValue(ServicesConstants.INVALID_DATA_ERROR_MSG)
  String errorCode = props.getValue(ServicesConstants.INVALID_DATA_ERROR_CODE)

  CommonUtils.logError(errorMsg, errorCode);
}

4. Read "Code complete" by Steve McConnell. ;-)
0
 

Author Comment

by:skn73
ID: 12666515
Thanks for all the suggestions guys!! I think I am going to follow Ortokobold and Objects suggestions
0
 

Author Comment

by:skn73
ID: 12666575
and thanks for suggesting that book ! I will give it a try!
0
 

Author Comment

by:skn73
ID: 12667530
so ae you saying the CommonUtil will not have anything to do with Datavalidations except logError?
0
 
LVL 1

Expert Comment

by:Ortokobold
ID: 12673265
Yes. In my opinion - it shouldn't have anything with data validation.
If you name your class "CommonUtil", it means that this class should hold general-purpose methods, widely used by your other classes. There should be such methods like: "logError", "convertDateToString", "getDBConnection", etc. When you start the new project, you should be able to copy the "CommonUtil" (and similar) classes, and use most of its methods. Will you need the "validateReq" method in your other projects? I don't think so.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
Suggested Courses
Course of the Month18 days, 10 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question