Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Simple Android App (2014) Improving Our Code Simple Refactoring: Using a Class

Why getFacts() methods is added inside FactBook class?

public class FactBook {

public String getFacts(){

    String[] facts = {
            "Ants stretch when they wake up in the morning.",
            "Ostriches can run faster than horses.",
            "Olympic gold medals are actually made mostly of silver.",
            "You are born with 300 bones; by the time you are an adult you will have 206.",
            "It takes about 8 minutes for light from the Sun to reach Earth.",
            "Some bamboo plants can grow almost a meter in just one day.",
            "The state of Florida is bigger than England.",
            "Some penguins can leap 2-3 meters out of the water.",
            "On average, it takes 66 days to form a new habit.",
            "Mammoths still walked the earth when the Great Pyramid was being built."
    };


    //Generate random
    Random randGenerator = new Random();
    int randomNumber = randGenerator.nextInt(facts.length);  //generate random no b/w 1 to 2



    String fact = facts[randomNumber] ;

    return  fact;
}

Is it necessary to add getFacts () methods.Can i avoid this this method?

2 Answers

Jon Kussmann
PLUS
Jon Kussmann
Courses Plus Student 7,254 Points

You're going to need a method to get a random fact from a list of facts, which is what the getFacts() method accomplishes... that's the objective of this app.

Is there a reason you don't want that method on your class?

While it's true that you could technically leave everything in MainActivity, it is not advised from a design/best practices point of view. In the long run, organizing code like this will make it easier to understand and to maintain.

Miguel Gonzalez Rocha
Miguel Gonzalez Rocha
2,849 Points

If you dont have everything under a method you would only have a class storing all the facts, that why you need the getFacts() method, to store them and be able to call any of them. I highly recommend reading the SOLID principles, the one that applies here is the S, "Single Responsability Principle", it might not seem like a big deal to make a class for each "need" your program has right now, but its just so you have good habits for when you make more complex programs so you know when to make a new class.