• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Values generated by method to be used outside of the method

 
Ranch Hand
Posts: 333
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I apologize for the poor subject line.  I wasn't sure how to explain myself.     I have a method which I created to build up a json string I need for testing.  In this method I am generating a random requestNumber value.   The method returns a String but I would like to also like to have access to the requestNumber value(s) .  I'm not sure how to do this since it generated inside this method.

One thought I had was to use substring but because the the number of times the requestNumber value can vary I'm not sure how to make that work.    Can someone suggest an option that may work?

 
Saloon Keeper
Posts: 10705
86
Eclipse IDE Firefox Browser MySQL Database VI Editor Java Windows ChatGPT
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
When you want to return more than one piece of data, the common approach is to create a small class that can hold all the pieces you wish to return.

An alternative is to break your method into two methods, one which creates a list of N random number, and the other that takes this list and returns a JSON string.

And yet another way is to pass in an empty List<Integer> as a parameter and have the method add to the list as it goes and also return the JSON string.
 
Lisa Austin
Ranch Hand
Posts: 333
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Carey Brown wrote:When you want to return more than one piece of data, the common approach is to create a small class that can hold all the pieces you wish to return.

An alternative is to break your method into two methods, one which creates a list of N random number, and the other that takes this list and returns a JSON string.

And yet another way is to pass in an empty List<Integer> as a parameter and have the method add to the list as it goes and also return the JSON string.



Thank You Carey.  I tried to break this into two methods but not as you described.  Thank You.  I'll try that approach or I'll try the class approach.  I really appreciate the direction.  
 
Sheriff
Posts: 17644
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

Lisa Austin wrote:I would like to also like to have access to the requestNumber value(s) .  I'm not sure how to do this since it generated inside this method.


You are having difficulty because the creation/generation of the requestNumber is very tightly coupled to the code that generates the result String. You need to loosen that coupling. So, instead of creating it as you have on line 3, you need to be able to call on something to provide the value instead.

The code you want to have on line 13 would be something like this instead:

What type would requestNumberProvider have? You can define either an abstract class or interface:

So your declaration would be:

Now you have loose coupling. When testing, you can inject an implementation that allows you to specify what numbers to return, like so:

To get the same kind of behavior you had before with a Random generator, you'd have this implementation:

For testing, you pass an instance of TestRequestNumberProvider to the setRequestNumberProvider() method. For production, you inject and instance of the production provider implementation.

So, when testing and you know you're going to need to generate several request numbers, you can do this:

Your testing becomes very deterministic now because you know exactly what request numbers you should expect the class under test will use to generate the result of the newMapping() call.
 
Saloon Keeper
Posts: 15510
363
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
In this particular case, it's probably best to generate the random numbers first, then get the data for each one, and then turn it all into JSON.

There are many problems with your code:

  • You are declaring variables in scopes where they're not needed. Always declare them in the deepest scope possible, and only at the time they're needed.
  • Don't create random number generators on the fly. Pass them in a method call, or assign them to a field from a constructor.
  • You're not using your string builder effectively. There's no point in using a string builder if you're gonna preform string concatenation anyway.
  • Don't use special cases to avoid appending a separator character you the last case. Use String.join() instead.
  • Build JSON using a JSON object model, not with string operations.
  •  
    Lisa Austin
    Ranch Hand
    Posts: 333
    6
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Junilu Lacar wrote:

    Lisa Austin wrote:I would like to also like to have access to the requestNumber value(s) .  I'm not sure how to do this since it generated inside this method.


    You are having difficulty because the creation/generation of the requestNumber is very tightly coupled to the code that generates the result String. You need to loosen that coupling. So, instead of creating it as you have on line 3, you need to be able to call on something to provide the value instead.



    Thank You!!  I was able to get what I need with this.  
     
    Lisa Austin
    Ranch Hand
    Posts: 333
    6
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Stephan van Hulst wrote:In this particular case, it's probably best to generate the random numbers first, then get the data for each one, and then turn it all into JSON.

    There are many problems with your code:

  • You are declaring variables in scopes where they're not needed. Always declare them in the deepest scope possible, and only at the time they're needed.
  • Don't create random number generators on the fly. Pass them in a method call, or assign them to a field from a constructor.
  • You're not using your string builder effectively. There's no point in using a string builder if you're gonna preform string concatenation anyway.
  • Don't use special cases to avoid appending a separator character you the last case. Use String.join() instead.
  • Build JSON using a JSON object model, not with string operations.


  • Thank you and I appreciate you pointing out the problems with my code.  I've been slowly going through your list trying to fix it.  I do want to keep practicing my work using best practice.  My only issue is I can't figure out the JSON object model part.  I found a tutorial  but the jar file (json-simple-1.1.1.jar ) is a broken link.  I also tried adding it as a compile dependency and it doesn't seem to be working.

    https://code.google.com/archive/p/json-simple/
    https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1

    Is there a different JSON object that I should be using?
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 15510
    363
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Well, it all kinda depends on what kind of application you are making. If it's a web application, you can just use the built in serialization mechanism of your web application container. If it's a desktop application, you need to explicitly call the JSON library yourself. Either way, you need a dependency on a JSON library. I can strongly recommend Jackson.

    If you have a Maven project, all you need to do is add a dependency to your POM:

    If you need to explicitly call the JSON library, you need to remove the <scope> element.

    If you don't have a Maven project, you need to download the Jackson jar and add it to the class path of your application.

    Here's a tutorial how you can use ObjectMapper to read and write objects from and to JSON: http://tutorials.jenkov.com/java-json/jackson-objectmapper.html

    Here's the ObjectMapper API: http://fasterxml.github.io/jackson-databind/javadoc/2.9/com/fasterxml/jackson/databind/ObjectMapper.html
     
    Marshal
    Posts: 79177
    377
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Slight tangent:
    This is how I would create a List<Integer> to contain “random” numbers. If you want something better than java.util.Random, try its subclass SecureRandom, or some other random number generator.Note that supplying a seed will cause the random number generator to produce the same sequence of numbers every time; delete the seed from the constructor call to get different sequences. The ints() method (which has four overloadings) here produces a 100‑element IntStream handling ints betwen 100 and less than 200. The boxed() method creates a Stream<Integer> and that can be collected with the collect(Collector) method. You can get away with not writing your own Collector because the Collectors class has methods which each create a ready‑made Collector for a frequently‑used task: this method provides exactly what you want.
     
    With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
    reply
      Bookmark Topic Watch Topic
    • New Topic