Skip to content

add project to branch#1

Open
lerklyu wants to merge 4 commits into
mainfrom
branch
Open

add project to branch#1
lerklyu wants to merge 4 commits into
mainfrom
branch

Conversation

@lerklyu

@lerklyu lerklyu commented Feb 4, 2026

Copy link
Copy Markdown
Owner

No description provided.

@lerklyu lerklyu requested a review from kegisa February 4, 2026 14:00
Comment thread src/main/java/org/example/test/TestApp.java Outdated
Comment thread src/main/java/org/example/workingWithUserAndConsole/UserInterface.java Outdated
Comment thread src/main/java/org/example/workingWithUserAndConsole/AppFromUsers.java Outdated
Comment thread src/main/java/org/example/workingWithUserAndConsole/AppFromUsers.java Outdated
Comment thread src/main/java/org/example/workingWithUserAndConsole/AppFromUsers.java Outdated
Comment thread src/main/java/org/example/workingWithUserAndConsole/AppFromUsers.java Outdated
Comment thread src/main/java/org/example/workingWithFile/ParserFromJsonToMap.java Outdated
Comment thread src/main/java/org/example/test/TestApp.java Outdated
Comment thread src/main/java/org/example/App.java
Comment thread src/main/java/org/example/App.java Outdated
Comment thread src/main/java/org/example/userinterface/ConsoleUserInterface.java
Comment thread src/main/java/org/example/converter/Converter.java Outdated
Comment thread src/main/java/org/example/converter/DefaultConverter.java Outdated
Comment thread src/main/java/org/example/converter/DefaultConverter.java Outdated
Comment thread src/main/java/org/example/working_with_file/JsonFIleRatesGetter.java Outdated
Comment thread src/main/java/org/example/working_with_file/RatesGetter.java Outdated
Comment thread src/main/java/org/example/userinterface/UserInterface.java
Comment thread src/main/java/org/example/converter/Converter.java Outdated
Comment thread src/main/java/org/example/converter/DefaultConverter.java
Comment thread src/main/java/org/example/ratesgetter/JsonFIleRatesGetter.java
Gson gson = new Gson();
Type type = new TypeToken<Map<String, Double>>() {
}.getType();
Path filePath = Paths.get("src/main/resources/exchangeRate.json");

@kegisa kegisa Feb 7, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

mapRates = gson.fromJson(jsonContent, type);
for (Map.Entry<String, Double> entry : mapRates.entrySet()) {
if (acceptedCodeCurrency.equals(entry.getKey())) {
return entry.getValue();

@kegisa kegisa Feb 7, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

А если не найдем нужный код, что будет? Посмотри как работать с исключениями, попроси пару примеров и начни здесь выбрасывать хотя бы runtimeException с нужным сообщением

public class JsonFIleRatesGetter implements RatesGetter {

@Override
public double getExchangeRates(String acceptedCodeCurrency) throws IOException {

@kegisa kegisa Feb 7, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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

import java.io.IOException;

public interface RatesGetter {
double getExchangeRates(String acceptedCodeCurrency) throws IOException;

@kegisa kegisa Feb 7, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Перевод строки до. И опять IOException про него выше писал. Уже объяснял в тг насчеn FNF но ты продолжаешь повторяться

Comment thread src/main/java/org/example/App.java Outdated
double conversionResult = converter.convert(amountToConvert, exchangeRateByCurrency);
userInterface.showToUser("Эквивалент: " + String.format("%.2f", conversionResult));
} catch (Exception e) {
System.out.println(e.getMessage());

@kegisa kegisa Feb 7, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

А пользователь точно увидит это сообщение из исключения? Или ты не хотела, чтобы он видел ошибки?

Comment thread pom.xml
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.13.2</version>

@kegisa kegisa Feb 7, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Хорошим тоном в разработке считается выности версию в константу в начало pom. Посмотри как сделать так и сделай.


public class ConsoleUserInterface implements UserInterface {

Scanner scanner = new Scanner(System.in);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Давай попробуем инициализацию делать в конструторе. На вход конструктор ничего не придет, просто this.scanner = new Scanner(System.in); добавим в него.


public class ConsoleUserInterface implements UserInterface {

Scanner scanner = new Scanner(System.in);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Давай начинать использовать нужные модификаторы доступа. Почитай посмотри и исправь. А то получается сейчас, твой класс можно "ломануть" , создать объект ConsoleUserInterface, а потом поле scanner засетать на что то другое. И все полетит. Почитай что такое инкапусляция, попроси реальные примермы. От сложных до простых.

@@ -0,0 +1,18 @@
package org.example.communication_with_users;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

И пакет нормально назови userinterface норм, нижние подчеркивания неуместны

this.path = path;
try {
this.jsonContent = Files.readString(path, StandardCharsets.UTF_8);
} catch (Exception e) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Не понял а как это должно работать? Получается вызовем конструктор, чтобы создать объект JsonFIleRatesGetter, получим ошибку например, что такого файла нет и при этом создами объект JsonFIleRatesGetter, который не может считать данные. Проверь это у себя, запусти прилжоение с несуществующим файлом и посмотри, что будет

Gson gson = new Gson();
Type type = new TypeToken<Map<String, Double>>() {
}.getType();
mapRates = gson.fromJson(jsonContent, type);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

А зачем мы каждый раз будет преобразовыывать json в мапу? может это тоже один раз сделать, как и считаываение из файла?

String codeCurrency = userInterface.getFromUser();
try {
exchangeRateByCurrency = ratesGetter.getExchangeRates(codeCurrency);
} catch (RuntimeException e) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

А почему два trycatch? Если что то не так ты ведь все равно пропускаешь остальную логику

try {
amountToConvert = parseDouble(userInterface.getFromUser());
} catch (RuntimeException e) {
System.out.println("Неправильный формат числа");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Код здесь стал явно выглядеть хуже, ты должна была это заметить, что из красивой логики в несколько строк получается какая то хрень с try catch. Сделай один try catch в цикле и в этом try catch будет вся логика

}
}

public static void main(String[] args) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

А это что здесь делает? у нас же был Main класс для этого

try {
exchangeRateByCurrency = ratesGetter.getExchangeRates(codeCurrency);
} catch (RuntimeException e) {
System.out.println("Неправильный формат кода валюты");

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

А это для кого сообщение?

}.getType();
mapRates = gson.fromJson(jsonContent, type);
if (!mapRates.containsKey(acceptedCodeCurrency)) {
throw new RuntimeException("Код валюты не найден или не существует" + acceptedCodeCurrency);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

А зачем ты тут message задаешь в exeption если нигда не используешь?

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