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 Pukli
Balazs Pukli
46,034 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