I am learning Swift now and I am at the very beginning. My question contains Swift code but I suppose it is more general question and could be applied to any language.
I had this task:
- Write a function which check whether our given number is even or not.
- Write a function which checks whether our given number could be divided by 3 or not.
For #1 I made this:
func isEven(_ number: Int) -> Bool {
number % 2 == 0
}
For #2 I made this:
func isDividedByThree(_ number: Int) -> Bool {
number % 3 == 0
}
At the lesson we were told by the teacher that it's not good to write similar code in different parts. I noted that I had 2 functions which were doing the same job - to check whether this number could be divided by another number or not. That's why I merged my 2 functions into 1 which checks if the given number could be divided by another given number. So I added one more parameter and got this instead of those 2 functions:
func isDividedBy(dividend x: Int, divisor y: Int) -> Bool {
x % y == 0
}
My teacher told me: "Don't try to make swiss-army-knife-functions. I want you to make 2 different functions for 2 cases: % 2 and % 3.
After that we were supposed to use these functions as closures in the another function, which was intended to filter array of numbers and give us filtered array without even or divided by 3 numbers.
My last function was like this:
func filterByDivisor(range numbers: [Int], divisor d: Int, closure: (Int, Int) -> Bool) -> [Int] {
var filteredRange: [Int] = []
for number in numbers {
if !closure(number, d) {
filteredRange.append(number)
}
}
return filteredRange
}
print(filterByDivisor(range: numbersRange, divisor: 2, closure: isDividedBy))
print(filterByDivisor(range: numbersRange, divisor: 3, closure: isDividedBy))
My teacher expected to see:
- Two functions to check by divisor.
- Final filtering function with 2 parameters: range and closure.
I made:
- One function to check by divisor.
- Final filtering function with 3 parameters: range, divisor to check and closure.
My teacher was little bit upset but I honestly can't realize if it's really such a big deal? As I've just started my learning path I don't want to argue with him but deep inside I am not agree :)
I want to know opinion of another experienced programmers, could you please share?
Aucun commentaire:
Enregistrer un commentaire