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

jenyufu
jenyufu
3,311 Points

At 4:03 Why did we copy and paste where the String[] mFacts arrays were?

How does changing its place/refactoring help make it more efficient? It is not explained specifically why we do it and how to do it. We are just told to cut and paste it. I didn't LEARN to do it and wouldn't be able to do it again if I were to be faced with a similar situation.

1 Answer

In the video Ben says: "This object doesn't have any member variables or properties about it. It's a plain old fact book that can only do one thing. Now, we could invent some properties, like if it's a book maybe an author or a publish date, but let's convert the array of facts here into a property of this object. The list of potential facts is something about the FactBook and the object stores facts."

This step is partly just to show the process of deciding what variables should be properties of the class, and how to rename and refactor variables (4:30), and how to access public properties of our class from elsewhere in our code (5:05)

This step is not required for our project, but imagine if you wanted to be able to add new facts to the list. If the array is stored inside the getFact() method, it only exists in the scope of that method, and disappears once getFact() has finished running. You can't access the facts from anywhere else! If the array is stored as a member variable instead, you can create a new addFact() method to add new facts to the array, or access it directly as Ben shows later in the video.

Remember how at the start of the video, Ben says we don't want to create a new FactBook object every time we click on the button, because it might be slow? That is another reason it can be more efficient to create a member variable instead of inside a method. If our array of facts was very very large, it would be wasteful to create it over again every time we get a fact. Instead it is created once when our FactBook object is created, and we can call getFact() as many times as we want without changing the array.

jenyufu
jenyufu
3,311 Points

okay, got it Thank you so much!