Skip to content

Comments

Hwork3#3

Open
medvedevvu wants to merge 20 commits intomasterfrom
hwork3
Open

Hwork3#3
medvedevvu wants to merge 20 commits intomasterfrom
hwork3

Conversation

@medvedevvu
Copy link
Owner

No description provided.

Copy link

@JekaMas JekaMas left a comment

Choose a reason for hiding this comment

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

Код, насколько я вижу, должен работать, но есть несколько замечаний. Большей частью они связаны с нейдачным выбором структур данных.

)

/* Добавление нового товра в справочник - если есть измениться цена */
func addItemsPrice(itemsPrice map[int]*mu.ItemPrice, item *mu.ItemPrice) string {
Copy link

Choose a reason for hiding this comment

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

Проясни, зачем item *mu.ItemPrice по указателю нужно тут.

Copy link

Choose a reason for hiding this comment

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

Этот вопрос сохранился и в новом коде

func addItemsPrice(itemsPrice map[int]*mu.ItemPrice, item *mu.ItemPrice) string {
/* проверим наличие в каталоге */
fnd := false
vIdx := 0
Copy link

Choose a reason for hiding this comment

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

Не понял идею itemsPrice map[int]*mu.ItemPrice. Зачем map[int]*mu.ItemPrice, ключами у тебя int, которые порядковые индексы. Но это усложняет поиск по map и сводит ее к slice []int. Почему бы не сделать map[string]*mu.ItemPrice, где string - это название товара? Тогда циклы с поиском исчезнут полностью.

if fnd {
msg += "--обновиление--цены--старая:" + fmt.Sprintf("%.2f", oldPrice) +
" новая:" + fmt.Sprintf("%.2f", item.ItemPrice)
itemsPrice[vIdx] = item
Copy link

Choose a reason for hiding this comment

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

Несколько неудачное название itemsPrice - оно говорит о том, что это цены товаров, а там товары целиком. Может попробовать items?

@@ -0,0 +1,19 @@
package structsdef

// ItemPrice - описание товара
Copy link

Choose a reason for hiding this comment

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

type Item struct {
	Name  string
	Price float32
}

Может так? Выразительность даже лучше.

}

// User - описание пользователя
type User struct {
Copy link

Choose a reason for hiding this comment

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

ype User struct {
	Name string  // Имя пользователя
	Account  float32 // остаток на счету
}

*/
func getOrderCost(itemsList map[int]*mu.ItemPrice, shopList mu.Order) float32 {
var ordrCost float32 = 0
for _, shopName := range shopList.Items { // бегу по списку товаров в заказе
Copy link

Choose a reason for hiding this comment

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

Этот вложенный цикл тоже упрастится, если поменять тип itemsList, как описал выше.

сохраним список товаров с ценой во время запроса от пользователя
*/

func compStrArr(in1, in2 []string) bool {
Copy link

Choose a reason for hiding this comment

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

Неясно, зачем эта функция. Комментарий, как мне кажется, не от неё.

func orderRegister(acountList map[int]*mu.User, // список пользователей
ordersPrice *[]mu.Order, // списки товаров с ценами
itemsPrice map[int]*mu.ItemPrice, // справочник товаров
billList map[int]map[int]float32, // список счетов
Copy link

Choose a reason for hiding this comment

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

по описанию неясно, что это за map и что у неё за ключи

return
}
// проверим кредитоспособность
if ostatok <= 0 {
Copy link

Choose a reason for hiding this comment

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

float32 точно всегда будет проходить это сравнение корректно?

// добавить ветку просмотра

tmp := seveListwithCost(ordersPrice, itemsPrice, itemsList)
var saldo float32 = ostatok - tmp.TotalSum
Copy link

Choose a reason for hiding this comment

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

saldo := ostatok - tmp.TotalSum

fnd := false
vIdx := 0
msg := item.ItemName
var oldPrice float32 = 0
Copy link

Choose a reason for hiding this comment

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

В golang это var oldPrice float32
А скорее var oldPrice float

vIdx := 0
msg := item.ItemName
var oldPrice float32 = 0
for cidx, citem := range itemsPrice {
Copy link

Choose a reason for hiding this comment

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

По прежнему не хватает items map[string]Item, если принимать такой и подобные параметры, то уйдут всй эти куски кода с поиском item, user

break
}
}
if fnd {
Copy link

Choose a reason for hiding this comment

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

found немного лучше - более полные имена предпочтительнее.

Общее правило таково: чем больше время жизни переменной и шире ее контекст, тем более распространенное имя стоит сделать. Короткоживущая переменная одного цикла - подойдёт i, idx, k, v; переменная для использования в нескольких проверках, в среднем куске кода на десяток и более строк кода - лучше чтобы это было полное слово index, validator, config, item, price; сложное понятие или переменная в большом методе или тем более уровня пакета - несколько слов: lowestPrice, areItemsSorted, SortByItemName.

for _, shopName := range shopList.Items { // бегу по списку товаров в заказе
fond := false
for _, item := range itemsList { // бегу по списку товаров в каталоге
if shopName == item.ItemName {
Copy link

Choose a reason for hiding this comment

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

От этого стоит избавиться полностью - от цикла с поиском.

Copy link

Choose a reason for hiding this comment

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

Может стоит сделать новые методы у shop - getUser, getItem, которые возвращают пользователя и товар по соответствующим именам.

}

func seveListwithCost(
ordersPrice *[]mu.Order, // списки товаров с ценами
Copy link

@JekaMas JekaMas Jan 21, 2020

Choose a reason for hiding this comment

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

зачем тут слайсы по указателю? по названию фукнции не очень понятно, что она должна делать

var ostatok float32 = 0
//var totalCost float32 = 0
var vIxd int = -1
for idx, iUser := range acountList {
Copy link

Choose a reason for hiding this comment

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

Этот цикл надо убрать, как и вспомогательные к нему переменные.

func showAccount(acountList map[int]*mu.User, p int) {
switch p {
case 0:
{
Copy link

Choose a reason for hiding this comment

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

Тут не нужны {}

Copy link

Choose a reason for hiding this comment

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

Этим константам стоит дать имена и тип, чтобы было очевидно при использовании

type sortDirection uint8

const (
    ByNameAsc sortDirection = iota
    ByNameDesc
// и так далее
)

func (a ByAcc) Less(i, j int) bool { return a[i].Account < a[j].Account }
func (a ByAcc) Swap(i, j int) { a[i].Account, a[j].Account = a[j].Account, a[i].Account }

func showAccount(acountList map[int]*mu.User, p int) {
Copy link

Choose a reason for hiding this comment

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

Посмотри, какое более очевидное имя можно дать для p


ordersPrice := []mu.Order{} // список заказов с посчитанной общей ценой

fmt.Println(seveListwithCost(&ordersPrice, itemsPrice, mu.Order{[]string{"Хлеб", "Сосиски"}, 0}))
Copy link

Choose a reason for hiding this comment

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

Посмотри, как происходит заказ и все операции с магазином. Они очень много заставляют пользователя делать, создавать корректные данные, передавать их куда надо. Лучше было бы, чтобы это было скрыто от пользователя кодом Shop. Посмотри на предложенный интерфейс магазина, возможно это подскажет направление.

}

// Order - описание заказа
type Order struct {
Copy link

Choose a reason for hiding this comment

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

Комментарий всё ещё в силе.

@@ -0,0 +1,19 @@
package structsdef
Copy link

Choose a reason for hiding this comment

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

названия пакетов лучше делать по задачам или типам, которые определены в пакете. то же и про файлы.
item.go shop.go в пакете shop будут более понятны (это просто пример, возможно ты найдешь лучшее устройство кода).

//SaveAcountList - схраним пользователей
func SaveAcountList(vacountList map[string]*User) {
if len(vacountList) == 0 {
panic(collectionEmpty)
Copy link

Choose a reason for hiding this comment

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

То же про паники

Copy link
Owner Author

Choose a reason for hiding this comment

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

ок


// SetDiscount - устанавливаем скидку на заказ в зависимости от пользователя
// типов товаров и заказов
func (order *Order) SetDiscount(userName string,
Copy link

Choose a reason for hiding this comment

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

Возможно я неверно понял, но это больше похоже на подсчёт скидки, чем на ее установку в order данных.

Copy link
Owner Author

Choose a reason for hiding this comment

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

получилось путано - там есть комментарий
244 Воспользуемся SetDiscount - сделаем скидку
тут собственно скидка устанавливается

itemsPrice[itemName] = item
msg += "--новый--товар--по цене--:" + fmt.Sprintf("%.2f", item.ItemPrice)
} else { // нашли - обноавляем цену и тип
msg += "--обновиление--цены--старая:" + fmt.Sprintf("%.2f", vItemPrice.ItemPrice) +
Copy link

Choose a reason for hiding this comment

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

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

Copy link
Owner Author

Choose a reason for hiding this comment

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

ok

vitemsList, ok := itemsList[name]
if ok {
switch vitemsList.ItemType {
case 2:
Copy link

Choose a reason for hiding this comment

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

Трудно понять, что тут происходит. попробуй добавить имена константам, выделить подобные куски кода в отдельные функции.

Copy link
Owner Author

Choose a reason for hiding this comment

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

ok

если больше 1,2,...,4....> товаров - то вернуть список без пробника
*/
switch {
case (len(probnik) == 1 && len(tovar) == 2):
Copy link

Choose a reason for hiding this comment

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

Внешние скодки () лишние

if r := recover(); r != nil {
switch r {
case openFileError:
{
Copy link

Choose a reason for hiding this comment

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

Лишние {}

Copy link
Owner Author

Choose a reason for hiding this comment

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

если оператор один , то {} - можно опускать ?

Copy link

Choose a reason for hiding this comment

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

Даже если их много в конструкции switch внутри каждого case фигурные скобки не нужны

}
}
} else {
f.Close()
Copy link

@JekaMas JekaMas Jan 21, 2020

Choose a reason for hiding this comment

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

может в начале функции сделать

defer func() {
    if f != nil {
        f.close()
    }
}()

Copy link
Owner Author

Choose a reason for hiding this comment

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

не знаю почему , но go ругалась - дескать не вижу f !

import "fmt"

// ItemPrice - описание товара в дальнейшем map[ItemName] *ItemPrice
type ItemPrice struct {
Copy link

Choose a reason for hiding this comment

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

По сути, это не ItemPrice, а Item, который включает в себя не только цену.
Префикс Item- для полей структуры лишний, он не добавляет смысла.

// 0 - обычный товар 1 - премиум товар 2 - пробник с нулевой ценой
лучше сделать новый тип и для него определить эти три константы и дать им имена.

Copy link
Owner Author

@medvedevvu medvedevvu Jan 21, 2020

Choose a reason for hiding this comment

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

полагаю это надо было сделать через iota


func addItemsPrice(itemsPrice map[string]*mu.ItemPrice,
itemName string,
item *mu.ItemPrice) string {
Copy link

Choose a reason for hiding this comment

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

зачем item *mu.ItemPrice, равно как и itemsPrice - по указателю?

Copy link
Owner Author

Choose a reason for hiding this comment

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

ну я раньше задавал вопрос - у меня не получалось обновить значение в структуре
было так acountList *map[int]mu.User , и я не мог выполнить (*acountList)[vIxd].Account = 10.
Ты рекомендовал acountList map[int]*mu.User - чтоб можно было это сделать , и я ещё
попробовал и спросил https://play.golang.org/p/YhSH0hAHHiX - верно или нет.
Получив утвердительный ответ, я рассудил , что если в структуре надо что-то менять, то нужно ставить * - по этому map[string]*mu.ItemPrice - а там я как раз меняю цену.

вернуть заказ с посчитанной ценой
*/
func getOrderCost(itemsList map[string]*mu.ItemPrice, shopList mu.Order) float32 {
var ordrCost float32 = 0
Copy link

Choose a reason for hiding this comment

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

инициализация нулевым значением не нужна

Copy link
Owner Author

Choose a reason for hiding this comment

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

это остаточное - со временем буду опускать, просто до автоматизма отработано - если завел переменную - присвой значение.

Copy link

@JekaMas JekaMas left a comment

Choose a reason for hiding this comment

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

к новому коду комментарии

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.

2 participants