Skip to content

Hw2 bor#3

Open
AnNyiiik wants to merge 9 commits intomainfrom
HW2_Bor
Open

Hw2 bor#3
AnNyiiik wants to merge 9 commits intomainfrom
HW2_Bor

Conversation

@AnNyiiik
Copy link
Copy Markdown
Owner

@AnNyiiik AnNyiiik commented Mar 9, 2023

No description provided.

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
Comment on lines +30 to +31
}
public int Size()
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Между методами нужна пустая строка

Comment thread HW2_Bor/HW2_Bor/Trie.cs
Comment on lines +34 to +35
}
private bool AddToVertex(Vertex vertex, string element, int position)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Снова не хватает пустой строки между методами

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
Comment on lines +198 to +199
var vertex = FindVertex(prefix);
if (FindVertex(prefix) != null)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

В if стоит vertex передать, а не второй раз FindVertex(prefix) вычислять :)

Comment thread HW2_Bor/HW2_Bor/Trie.cs
return true;
}

public bool Add(string element)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

В публичный метод могут передать что угодно. Стоит проверить, не null ли строка.
Ваш класс кто-то может решить использовать в своем проекте, например. Будет неприятно свалиться с NullReferenceExpression при передаче некорректного значения в метод класса :)

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
Comment on lines +14 to +18
public Dictionary<char, Vertex> NextVertices;

public int NumberOfTerminalVertices;

public bool IsTerminal;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если поле назвать с заглавной буквы от этого оно не станет свойством :) А публичные поля - зло.

Вам подойдут свойства со стандартным getter и setter:

public bool IsTerminal { get; set; }

Comment thread HW2_Bor/HW2_Bor/Trie.cs
return isAdded;
}

public bool Contains(string element)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Сюда тоже в качестве аргумента могут передать null. Нужна проверка на то, что переданный аргумент не null

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

А проверка так и не появилась... Теперь нужно еще добавить тесты, где вы в качестве аргументов в публичные методы Бора передаете null :)

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
return current;
}

private Tuple<bool, bool> RemoveFromVertex(Vertex vertex, string element, int position)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Не очень очевидно без копания в коде, что вообще вы возвращаете из этого метода. Во все неочевидные на ваш взгляд места добавляйте, пожалуйста, комментарии. Разработчик, который будет сопровождать написанный вами код, не будет вас поминать плохим словом в таком случае :)
Если кратко, то по названию метода RemoveFromVertex непонятно, что он делает. Может быть Remove что-то FromVertex? И еще сложно понять, что же метод возвращает. Полезны будут комментарии

Comment thread HW2_Bor/HW2_Bor/Trie.cs
Comment on lines +48 to +62
if (vertex.NextVertices.ContainsKey(element[position]))
{
try
{
var isAdded = AddToVertex(vertex.NextVertices[element[position]], element, ++position);
if (isAdded)
{
++vertex.NumberOfTerminalVertices;
return true;
}
}
catch
{
return false;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Блок try ... catch используется, когда вы ожидаете, что вызываемый код может выбросить исключение. Ваш метод никакие исключения не бросает.
Представьте, вы написали метод не очень корректно и на самом деле падаете периодически с NullReferenceExpression, но из-за блока try ... catch вы можете долго пытаться понять в чем проблема

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Все еще не понимаю: зачем вам здесь try ... catch? :)

Comment thread HW2_Bor/HW2_Bor/Program.cs Outdated
return;
}

Console.WriteLine("To add an element press 1\nTo remove press 2\nTo check if the particular word contains press 3\n" +
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно:

Console.WriteLine("""
    To add an element press 1
    To remove press 2
    To check if the particular word contains press 3
    To count words with the same prefix press 4
    To quit press 0
    """);

Comment on lines +31 to +45
var word = Console.ReadLine();
if (word == null)
{
Console.WriteLine("A null-reference");
return;
}
var isAdded = trie.Add(word);
if (isAdded)
{
Console.WriteLine("A new word has been just added");
}
else
{
Console.WriteLine("A word hasn't been added, it already exists");
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

А здесь пользователь может ввести Enter, в таком случае Console.ReadLine вернет пустую строку. А вы напишите: A word hasn't been added, it already exists. Что не является правдой. Поправьте, пожалуйста

Comment thread HW2_Bor/HW2_Bor/Trie.cs
Comment on lines +48 to +62
if (vertex.NextVertices.ContainsKey(element[position]))
{
try
{
var isAdded = AddToVertex(vertex.NextVertices[element[position]], element, ++position);
if (isAdded)
{
++vertex.NumberOfTerminalVertices;
return true;
}
}
catch
{
return false;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Все еще не понимаю: зачем вам здесь try ... catch? :)

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
Comment on lines +148 to +150
///<summary> Recursively checks if the given element exists in the tree. If it does, returns a pair of bool values: 1st -
/// true, 2nd - if there is no other elements after the current. If the second value is true, we can delete a
/// branch. </summary>
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

У вас тут комментарий поехал, нужно:

/// <summary>
/// Recursively checks if the given element exists in the tree. If it does, returns a pair of bool values: 1st - 
/// true, 2nd - if there is no other elements after the current. If the second value is true, we can delete a branch. 
/// </summary>

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
///<summary> Recursively checks if the given element exists in the tree. If it does, returns a pair of bool values: 1st -
/// true, 2nd - if there is no other elements after the current. If the second value is true, we can delete a
/// branch. </summary>
private Tuple<bool, bool> RemoveWordFromVertex(Vertex vertex, string element, int position)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Этот метод берет на себя слишком много: и удаляет слово, и еще какую-то дополнительную информацию возвращает, не относящуюся напрямую к операции удаления. В общем, он разве что кофе не варит :)
Метод все-таки должен идейно что-то одно делать: пускай он удаляет слово и возвращает bool - индикатор успешности проведенной операции.
Декомпозируйте, пожалуйста :)

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
return isAdded;
}

public bool Contains(string? element)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Из-за того, что вы позволяете в качестве аргумента в метод Contains передавать null, nullability-анализ не выдаст пользователю warning при попытке передачи null в качестве аргумента.
Это плохо, потому что в целом аргумент Contains не должен быть null, хорошо бы, чтобы nullability-анализ имел возможность пользователю об этом напомнить

Comment thread HW2_Bor/HW2_Bor/Program.cs Outdated
{
Console.WriteLine("Not a number");
return;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Нужно все на 4 пробела влево сместить

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
Comment on lines +20 to +23
public Dictionary<char, Vertex> NextVertices
{
get => this.nextVertices;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Стоит использовать auto-implemented properties

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
Comment on lines +31 to +35
public int NumberOfTerminalVertices
{
get => numberOfTerminalVertices;
set => numberOfTerminalVertices = value;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

И даже тут :)

Comment thread HW2_Bor/HW2_Bor/Trie.cs
Comment on lines +211 to +214
if (prefix.Length == 0)
{
return _sizeOfTrie;
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

С чего бы? :) Пустая строка в Боре не содержится

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Все еще пустая строка в Боре не содержится. Поправьте, пожалуйста

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
return isDeleted.Item1;
}

public int HowManyStartsWithPrefix(String prefix)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

А тут вам null могут передать, нужна проверка на null

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
return new Tuple<bool, bool>(false, false);
}

public bool Remove(string? element)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Тут то же самое, что и в методе Contains, нужно string element вместо string? element

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
Comment on lines +38 to +39
_sizeOfTrie = 0;
Size = _sizeOfTrie;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Так поле _sizeOfTrie на самом деле вам не нужно (кроме того, инициализировать поле нулем было не нужно, в .NET итак все объекты имеют значения по умолчанию, у int это как раз 0). А не нужно потому, что auto-implemented property можно создать так:
public int Size { get; private set; }.
С приватным set вы сможете поддерживать значение свойства Size в актуальном состоянии

Comment thread HW2_Bor/HW2_Bor/Trie.cs Outdated
return true;
}

public bool Add(string? element)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Из-за того, что вы позволяете в качестве аргумента в метод Add передавать null, nullability-анализ не выдаст пользователю warning при попытке передачи null в качестве аргумента.
Это плохо, потому что в целом аргумент Add не должен быть null, хорошо бы, чтобы nullability-анализ имел возможность пользователю об этом напомнить.

Кстати, уже была пара комментариев об этом :) Все-таки ожидается, что вы внимательно изучаете комментарии и исправляете свои ошибки

Comment thread HW2_Bor/HW2_Bor/Trie.cs
return isAdded;
}

public bool Contains(string element)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

А проверка так и не появилась... Теперь нужно еще добавить тесты, где вы в качестве аргументов в публичные методы Бора передаете null :)

Comment thread HW2_Bor/HW2_Bor/Trie.cs
Comment on lines +211 to +214
if (prefix.Length == 0)
{
return _sizeOfTrie;
}
Copy link
Copy Markdown

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