Skip to content

Conversation

@sofiiakulish
Copy link
Owner

Домашнее задание №9 «Валидатор структур»

Чек-лист студента (Что это?)

Критерии оценки

  • Пайплайн зелёный - 3 балла
  • Добавлены юнит-тесты - до 4 баллов
  • Понятность и чистота кода - до 3 баллов

Зачёт от 7 баллов


func (v ValidationErrors) Error() string {
panic("implement me")
var result string
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для сборки строк лучше использовать strings.Builder это более оптимальный по памяти способ. Пример:

var b strings.Builder
for i := 0; i < 10; i++ {
    b.WriteString("foo")
}
return b.String()

По ссылке есть ещё пример использования, который подойдёт к вашей ситуации.

go 1.16

require (
github.com/fatih/structs v1.1.0
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Обратите внимание, что данный репозиторий заархивирован и более не поддерживается. Таких зависимостей лучше избегать или быть готовыми их поддерживать своими силами.

return nil
}

return errors.New(result.Error())
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно просто вернуть result так, как он у нас реализует интерфейс error. Это так же позволит нам избавится от проверки if len(result) == 0

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если я возвращаю просто result, то не срабатывает мой метод Error
expected: *errors.errorString(&errors.errorString{s:"Validation error for field "Email": Value should match regexp "^\\w+@\\w+\\.\\w+$". Value "1gmail.com" is not match\n"})
actual : hw09structvalidator.ValidationErrors(hw09structvalidator.ValidationErrors{hw09structvalidator.ValidationError{Field:"Email", Err:(*errors.errorString)(0xc000298070)}})

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, всё верно. Вы сравниваете два разных типа, они никогда не будут одинаковыми. Вы можете либо сравнивать строковое представление ошибки используя assert.EqalError, либо вместо errors.New в тестах конструировать ValidationErrors

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Я в тестах сравниваю только тексты ошибок. Но проверку на длину и возврат nil я оставила, так как в противном случае вместо nil в result было hw09structvalidator.ValidationErrors(nil)


type ValidationErrors []ValidationError

type ValidatorType int
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Намного более удобно когда у нас объявлен типа ValidationErrors и сразу после этого идут методы этого типа, в нашем случае func (v ValidationErrors) Error() string.


delimiterPos := strings.Index(str, ":")
if delimiterPos == -1 {
panic("Incorrect validator definition. Semicolon should be present")
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тут лучше вернуть ошибку: return errors.New("Incorrect validator definition. Semicolon should be present"). Старайтесь не использовать panic в коде, это затрудняет его поддержку. Замените все паники на ошибки.


const VALIDATE_TAG_NAME = "validate"

var NilValidationError = ValidationError{"", nil}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Немного не точно. Это не nil ошибка, а пустая ошибка. Это немного разные вещи.


type ValidatorType int

const (
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это очень круто, что вы создали тип под возможные типы валидаторов и добавили для них константы. Только тут будет более удобно использовать не числовые константы а строки. Это позволит нам избавится от getValidatorTypeByString.

}
}

func getValidatorValueByString(ruleString string) ValidatorValue {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше будет просто привести тип в коде. Не принято создавать отдельный функций для этого.


// Place your code here.
Validate(tt.in)
_ = tt
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно удалить строчку _ = tt.

stT := reflect.TypeOf(v)
stV := reflect.ValueOf(v)

for i:=0; i<stT.NumField(); i++ {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Перед тем как вызвать NumField нужно убедится что v это структура иначе мы получим панику.

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

Successfully merging this pull request may close these issues.

3 participants