aspose file tools*
The moose likes Java in General and the fly likes How to Generalize the code? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to Generalize the code?" Watch "How to Generalize the code?" New topic
Author

How to Generalize the code?

Farakh khan
Ranch Hand

Joined: Mar 22, 2008
Posts: 732
Hello,


I am repeating code every time that looks odd and also if there are 100 elements then a long document. How can I generalize the following code?

Thanks & best regards
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4391
    
    8

Firstly, there seems to be a consistent error in your code. Take the first loop. You are assigning the text you get out of each node to the same variable. In other words, only the final value is kept, and the rest are thrown away. Is that really what you want? I would expect that either you should be adding them to a list, or at the least appending them all.

Once you've fixed that, you're right - you can factor out the bits that are the same into a method, with arguments for those things that are different in each case and those things that need to be passed in. For instance, something like:
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19695
    
  20

The common parts are these:
So turn that into a method, with doc and the XPath expression as parameters and the node value as the return value:
I've chosen to also include the XPath object as a parameter to avoid having to recreate it each time.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Farakh khan
Ranch Hand

Joined: Mar 22, 2008
Posts: 732
Matthew Brown wrote:Firstly, there seems to be a consistent error in your code. Take the first loop. You are assigning the text you get out of each node to the same variable. In other words, only the final value is kept, and the rest are thrown away.
Is that really what you want? I would expect that either you should be adding them to a list, or at the least appending them all.


No not at all.

Once you've fixed that, you're right

Actually this is the first time I am working with XPath API. Please correct me where I am wrong that'll be your kind enough


Best regards & thanks for helping
Farakh khan
Ranch Hand

Joined: Mar 22, 2008
Posts: 732
Hello,

Thanks for your reply.

Its throwing following errors:


Best regards
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4391
    
    8

You need to declare nodes within the method, so that it's in scope when you try to use it.
Farakh khan
Ranch Hand

Joined: Mar 22, 2008
Posts: 732
Thanks Matthew. Now its compiled and working fine. How will I deal with this:



Thanks again for helping
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to Generalize the code?