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!

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

C# C# Basics (Retired) Prepare and Plan Program Structure

Vic Mercier
Vic Mercier
3,276 Points

Why would we need more than one method?

Why couldn't we put all of our code into the same method?

2 Answers

Balazs Peak
Balazs Peak
46,160 Points

This is a fabulous question! You are getting started with understanding the deep layers of the OO concepts, right now! :D

We could, and in fact, we did put everything into one algorithm. Several decades ago. But then we figured out that if we want to do the same thing several times, then the necessary part has to be present many times in the code (redundantly). But if we put the code which is used many times into a method, that method can be called anytime from anywhere and the code is written only once. There is a principle in programming which is called DRY - don't repeat yourself. The idea of methods is perfectly serving this principle from a technological stand of point.

Let's suppose you write a program which makes a tableau for a class of students who are currently graduating! You have an array of photo objects. The program supposed to format these photos so that they all would have a blue border, which will fit perfectly into the tableau design. You can add borders to all photos inside a for loop, which will repeat through the elements of the array - or... you can put a method into the Photo class, called addBorderToPhoto(), which would add the border any time you call it on an object. This way, you would just call that method inside the for loop, and it would add border to all photos in the array automatically.

Real life example: think of it like this. You go to a restaurant and you eat something new, some food which tastes really good. You look up the recipe on the internet. You do not cook, so you teach the recipe to your girlfriend, wife, boyfriend, husband, mother, father, etc. You have to teach them once, how to cook that recipe, but after that, you would just say "Cook the XY recipe, please", instead of going into the details.

Randy Eichelberger
Randy Eichelberger
445 Points

In short, readability and the ability to make changes in one place. I can change a method in one place that's used in 40 different places. BAck in the day you'd have to change it 40 different times. Not only is it more work, but you'll probably miss one and thus have a bug