marie.ellaZ
marie.ellaZ

Reputation: 45

Why do I have to use an extra method in this code?

I don't get why I have to use square() in this code? Why can't I just add n times n to the String s?

static int square(int n){
   return n*n;
}
static void ausgabe(int n){
   String s;
   int i = n;
   s = "SquareOf" + i + " = " + square(i);
   Sysout(s);
}

my solution would be to miss out the square method and just add like this

s = "SquareOf" + i + " = " + i*i;

I tried and the result is always right. But our book suggests the first way and I would just like to know why they make it more complicated in my eyes.

Thanks in advance.

Upvotes: 1

Views: 63

Answers (2)

Well, you are partially right, BUT software is developed better when you split thing according of what they do...

The method Ausgabe have a job: display the result only

The method square have a job: do the math operation only

So the whole point behind soft development is not that the code works

we try to do something else:

  • it must work
  • it must be easy to maintain
  • it must be easy to improve

all those requirements are related to the project's complexity and can be reached based on a single responsibility principle

Upvotes: 3

Syn
Syn

Reputation: 776

For something as trivial as i*i you wouldn't need a method. However if instead have to do a more complicated operation which would require quite a few lines of code, then it would be a good idea to put that in its own method in order to keep your code clean and easy to read, understand and maintain. Moreover if you need to do the same operation at multiple points in your program, then a method would be beneficial as you do not have to copy/paste the same code over and over again in different places.

Upvotes: 2

Related Questions