Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Arrays and Slices. A better refactor can be given #627

Open
Brivan-26 opened this issue Dec 25, 2022 · 1 comment
Open

Arrays and Slices. A better refactor can be given #627

Brivan-26 opened this issue Dec 25, 2022 · 1 comment

Comments

@Brivan-26
Copy link

In this code (link: https://github.com/quii/learn-go-with-tests/blob/main/arrays-and-slices.md#write-enough-code-to-make-it-pass-4):

func SumAllTails(numbersToSum ...[]int) []int {
	var sums []int
	for _, numbers := range numbersToSum {
		if len(numbers) == 0 {
			sums = append(sums, 0)
		} else {
			tail := numbers[1:]
			sums = append(sums, Sum(tail))
		}
	}

	return sums
}

We can refactor it, so we can omit the else block by introducing the statement continue:

func SumAllTails(numbersToSum ...[]int) []int {
	var sums []int
	for _, numbers := range numbersToSum {
		if len(numbers) == 0 {
			sums = append(sums, 0)
                        continue
		}
	       tail := numbers[1:]
	       sums = append(sums, Sum(tail))	
	}

	return sums
}
@jaymorelli96
Copy link
Contributor

I disagree with that. I think the first approach has more clarity and reads pretty well

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants