From c984500e427f3493f0f3f0e8c7822531cb7ee7ab Mon Sep 17 00:00:00 2001
From: Web-Sheriff <35970102+Web-Sheriff@users.noreply.github.com>
Date: Fri, 21 Jun 2019 19:00:25 +0300
Subject: [PATCH 1/2] Add files via upload
---
README.md | 8 +-
pizza-order-training.iml | 13 +
pom.xml | 46 ++--
src/main/java/PizzaOrder.java | 254 ++++++++++----------
src/main/java/controller/CliController.java | 156 ++++++------
src/main/java/model/DefaultStorage.java | 150 ++++++------
src/main/java/model/Ingredient.java | 78 +++---
src/main/java/model/Pizza.java | 205 ++++++++--------
src/main/java/model/PizzaException.java | 28 +--
src/main/java/model/Storage.java | 30 +--
src/main/java/model/StorageException.java | 28 +--
11 files changed, 504 insertions(+), 492 deletions(-)
create mode 100644 pizza-order-training.iml
diff --git a/README.md b/README.md
index 8f8bebb..ae379ba 100644
--- a/README.md
+++ b/README.md
@@ -1,4 +1,4 @@
-# Проект для практики исправления плохого кода (java)
-## 1. Импортируйте как maven проект
-## 2. В методе removeIngredient класса Pizza найдите плохие практики
-## 3. Попробуйте переписать метод более качественно
+# Проект для практики исправления плохого кода (java)
+## 1. Импортируйте как maven проект
+## 2. В методе removeIngredient класса Pizza найдите плохие практики
+## 3. Попробуйте переписать метод более качественно
diff --git a/pizza-order-training.iml b/pizza-order-training.iml
new file mode 100644
index 0000000..4069457
--- /dev/null
+++ b/pizza-order-training.iml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 3e9851b..3dde887 100644
--- a/pom.xml
+++ b/pom.xml
@@ -1,24 +1,24 @@
-
-
- 4.0.0
-
- com.simbirsoft
- pizza-order-training
- 1.0-SNAPSHOT
-
-
-
- org.apache.maven.plugins
- maven-compiler-plugin
-
- 1.7
- 1.7
-
-
-
-
-
-
+
+
+ 4.0.0
+
+ com.simbirsoft
+ pizza-order-training
+ 1.0-SNAPSHOT
+
+
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+ 1.7
+ 1.7
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/main/java/PizzaOrder.java b/src/main/java/PizzaOrder.java
index b24274d..06011fc 100644
--- a/src/main/java/PizzaOrder.java
+++ b/src/main/java/PizzaOrder.java
@@ -1,127 +1,127 @@
-import controller.CliController;
-import model.*;
-
-import java.util.Scanner;
-
-public class PizzaOrder {
-
- private static final String HELP_COMMAND = "?";
-
- private static final String ANOTHER_HELP_COMMAND = "help";
-
- private static final String STORE_COMMAND = "-store";
-
- private static final String SIZE_COMMAND = "-size";
-
- private static final String ANOTHER_SIZE_COMMAND = "--S";
-
- private static final String ADD_COMMAND = "-add";
-
- private static final String ANOTHER_ADD_COMMAND = "--A";
-
- private static final String REM_COMMAND = "-rem";
-
- private static final String ANOTHER_REM_COMMAND = "--R";
-
- private static final String OK_COMMAND = "-ok";
-
- private static Storage storage;
-
- private static Pizza pizza;
-
- public static void main(String[] args) {
- CliController.printHelloMessage();
- initDefaultStorage();
- try {
- while (true) {
- String input = new Scanner(System.in).nextLine();
- if (input != null && !input.isEmpty()) {
- if (HELP_COMMAND.equals(input) || ANOTHER_HELP_COMMAND.equals(
- input)) {
- CliController.printHelpMessage();
- } else if (STORE_COMMAND.equals(input)) {
- CliController.printStoreMessage(storage.getStorageIngredients());
- // Если присутствуют команды, необходимые для указания размера,
- // добавления/удаления ингридиентов
- } else if (input.startsWith(SIZE_COMMAND)
- || input.startsWith(ANOTHER_SIZE_COMMAND)
- || input.startsWith(ADD_COMMAND)
- || input.startsWith(ANOTHER_ADD_COMMAND)
- || input.startsWith(REM_COMMAND)
- || input.startsWith(ANOTHER_REM_COMMAND)) {
- String s = input.replaceAll(",", "");
- s = s.replaceAll("\"", "");
- String[] commands = s.split(" ");
- pizza = parseCommands(commands);
- System.out.println("Данные обновлены");
- } else if (OK_COMMAND.equals(input)) {
- if (pizza != null)
- CliController.printOkMessage(pizza);
- else {
- System.out.println("Неизвестная команда\n Ознакомьтесь со справкой");
- CliController.printHelpMessage();
- }
- } else {
- System.out.println("Неизвестная команда\n Ознакомьтесь со справкой");
- CliController.printHelpMessage();
- }
- }
- }
- } catch (StorageException | PizzaException e) {
- System.out.println(e.getMessage());
- } catch (Exception e) {
- System.out.println("Произошла ошибка, ещё раз проверьте вводимые данные");
- }
- }
-
- public static void initDefaultStorage() {
- storage = new DefaultStorage();
- try {
- storage.addIngredient(new Ingredient("Сыр"), 200);
- storage.addIngredient(new Ingredient("Перец"), 100);
- storage.addIngredient(new Ingredient("Колбаса"), 50);
- storage.addIngredient(new Ingredient("Соус"), 500);
- } catch (StorageException e) {
- System.out.println(e.getMessage());
- }
- }
-
- private static Pizza parseCommands(
- String[] commands
- ) throws PizzaException, StorageException {
- if (commands != null && commands.length > 0) {
- pizza = pizza != null ? pizza : new Pizza();
- for (int i = 0; i < commands.length; i++) {
- String command = commands[i];
- if (SIZE_COMMAND.equals(command) || ANOTHER_SIZE_COMMAND
- .equals(command)) {
- pizza.setSize(Integer.valueOf(commands[i + 1]));
- } else if (ADD_COMMAND.equals(command)
- || ANOTHER_ADD_COMMAND.equals(command)) {
- for (int j = i + 1; j < commands.length; j += 2) {
- Ingredient ingredient = new Ingredient(commands[j]);
- int count = Integer.valueOf(commands[j + 1]);
- pizza.addIngredient(
- ingredient,
- count
- );
- storage.removeIngredient(ingredient, count);
- }
- } else if (REM_COMMAND.equals(command)
- || ANOTHER_REM_COMMAND.equals(command)) {
- for (int j = i + 1; j < commands.length; j += 2) {
- Ingredient ingredient = new Ingredient(commands[j]);
- int count = Integer.valueOf(commands[j + 1]);
- pizza.removeIngredient(
- ingredient,
- count
- );
- storage.addIngredient(ingredient, count);
- }
- }
- }
- return pizza;
- } else
- throw new PizzaException("Неверная команада");
- }
-}
+import controller.CliController;
+import model.*;
+
+import java.util.Scanner;
+
+public class PizzaOrder {
+
+ private static final String HELP_COMMAND = "?";
+
+ private static final String ANOTHER_HELP_COMMAND = "help";
+
+ private static final String STORE_COMMAND = "-store";
+
+ private static final String SIZE_COMMAND = "-size";
+
+ private static final String ANOTHER_SIZE_COMMAND = "--S";
+
+ private static final String ADD_COMMAND = "-add";
+
+ private static final String ANOTHER_ADD_COMMAND = "--A";
+
+ private static final String REM_COMMAND = "-rem";
+
+ private static final String ANOTHER_REM_COMMAND = "--R";
+
+ private static final String OK_COMMAND = "-ok";
+
+ private static Storage storage;
+
+ private static Pizza pizza;
+
+ public static void main(String[] args) {
+ CliController.printHelloMessage();
+ initDefaultStorage();
+ try {
+ while (true) {
+ String input = new Scanner(System.in).nextLine();
+ if (input != null && !input.isEmpty()) {
+ if (HELP_COMMAND.equals(input) || ANOTHER_HELP_COMMAND.equals(
+ input)) {
+ CliController.printHelpMessage();
+ } else if (STORE_COMMAND.equals(input)) {
+ CliController.printStoreMessage(storage.getStorageIngredients());
+ // Если присутствуют команды, необходимые для указания размера,
+ // добавления/удаления ингридиентов
+ } else if (input.startsWith(SIZE_COMMAND)
+ || input.startsWith(ANOTHER_SIZE_COMMAND)
+ || input.startsWith(ADD_COMMAND)
+ || input.startsWith(ANOTHER_ADD_COMMAND)
+ || input.startsWith(REM_COMMAND)
+ || input.startsWith(ANOTHER_REM_COMMAND)) {
+ String s = input.replaceAll(",", "");
+ s = s.replaceAll("\"", "");
+ String[] commands = s.split(" ");
+ pizza = parseCommands(commands);
+ System.out.println("Данные обновлены");
+ } else if (OK_COMMAND.equals(input)) {
+ if (pizza != null)
+ CliController.printOkMessage(pizza);
+ else {
+ System.out.println("Неизвестная команда\n Ознакомьтесь со справкой");
+ CliController.printHelpMessage();
+ }
+ } else {
+ System.out.println("Неизвестная команда\n Ознакомьтесь со справкой");
+ CliController.printHelpMessage();
+ }
+ }
+ }
+ } catch (StorageException | PizzaException e) {
+ System.out.println(e.getMessage());
+ } catch (Exception e) {
+ System.out.println("Произошла ошибка, ещё раз проверьте вводимые данные");
+ }
+ }
+
+ public static void initDefaultStorage() {
+ storage = new DefaultStorage();
+ try {
+ storage.addIngredient(new Ingredient("Сыр"), 200);
+ storage.addIngredient(new Ingredient("Перец"), 100);
+ storage.addIngredient(new Ingredient("Колбаса"), 50);
+ storage.addIngredient(new Ingredient("Соус"), 500);
+ } catch (StorageException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private static Pizza parseCommands(
+ String[] commands
+ ) throws PizzaException, StorageException {
+ if (commands != null && commands.length > 0) {
+ pizza = pizza != null ? pizza : new Pizza();
+ for (int i = 0; i < commands.length; i++) {
+ String command = commands[i];
+ if (SIZE_COMMAND.equals(command) || ANOTHER_SIZE_COMMAND
+ .equals(command)) {
+ pizza.setSize(Integer.valueOf(commands[i + 1]));
+ } else if (ADD_COMMAND.equals(command)
+ || ANOTHER_ADD_COMMAND.equals(command)) {
+ for (int j = i + 1; j < commands.length; j += 2) {
+ Ingredient ingredient = new Ingredient(commands[j]);
+ int count = Integer.valueOf(commands[j + 1]);
+ pizza.addIngredient(
+ ingredient,
+ count
+ );
+ storage.removeIngredient(ingredient, count);
+ }
+ } else if (REM_COMMAND.equals(command)
+ || ANOTHER_REM_COMMAND.equals(command)) {
+ for (int j = i + 1; j < commands.length; j += 2) {
+ Ingredient ingredient = new Ingredient(commands[j]);
+ int count = Integer.valueOf(commands[j + 1]);
+ pizza.removeIngredient(
+ ingredient,
+ count
+ );
+ storage.addIngredient(ingredient, count);
+ }
+ }
+ }
+ return pizza;
+ } else
+ throw new PizzaException("Неверная команада");
+ }
+}
diff --git a/src/main/java/controller/CliController.java b/src/main/java/controller/CliController.java
index 2414ab0..ccc9d26 100644
--- a/src/main/java/controller/CliController.java
+++ b/src/main/java/controller/CliController.java
@@ -1,78 +1,78 @@
-package controller;
-
-import model.Ingredient;
-import model.Pizza;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class CliController {
-
- public static void printHelloMessage() {
- System.out.println("Добро пожаловать в приложением \"Pizza " +
- "Order\".\nС его помощью вы можете осуществить " +
- "процесс заказа пиццы, выбрав подходящий размер " +
- "пиццы и ингридиенты.\nДля получения более полной " +
- "информации о приложении введите команду \"?\" " +
- "или \"help\".\"");
- }
-
- public static void printHelpMessage() {
- System.out.println("Команды:\n" +
- "\t-store - получить информацию о наличии " +
- "ингридиентов.\n" +
- "\t-size, --S - установить размер пиццы " +
- "(целочисленное, положительное).\n" +
- "\t-add <\"название ингридиента\" количество>, --A" +
- " <\"название ингридиента\" количество> - добавить" +
- " ингридиент к пицце (число ингридиентов в пицце -" +
- " целочисленное, положительное). Пример: -add " +
- "\"сыр\" 2 (-A \"сыр\" 2). При множественном " +
- "добавлении: -add \"сыр\" 2, \"колбаса\" 3 (-A " +
- "\"сыр\" 2, \"колбаса\" 3).\n" +
- "\t-rem <\"название ингридиента\" количество>, --R" +
- " <\"название ингридиента\" количество> - удалить " +
- "ингридиент из пиццы (число удаляемых ингридиентов" +
- " из пиццы - целочисленное, положительное). " +
- "Пример: -rem \"сыр\" 2 (-R \"сыр\" 2). При " +
- "множественном удалении ингридиентов: -rem \"сыр\"" +
- " 2, \"колбаса\" 3 (-R \"сыр\" 2, \"колбаса\" 3)" +
- ".\n" +
- "\t-ok, --OK - выдача заказа (печать информации о " +
- "заказанной пиццы).");
- }
-
- public static void printStoreMessage(HashMap ingredients) {
- if (ingredients != null && ingredients.size() > 0) {
- StringBuilder message = new StringBuilder(
- "На данный момент в хранилище имеются следующие ингриденты:\n");
- for (Map.Entry entry : ingredients.entrySet()) {
- Ingredient ingredient = entry.getKey();
- Integer count = entry.getValue();
- message.append("- ").append(ingredient.getName())
- .append(" (количество: ").append(count).append(")\n");
- }
- System.out.println(message.toString());
- } else
- System.out.println("Хранилище пусто");
- }
-
- public static void printOkMessage(Pizza pizza) {
- if (pizza != null) {
- StringBuilder message = new StringBuilder("Заказ на пиццу:\n")
- .append("Размер: ").append(pizza.getSize()).append(" см\n");
- HashMap ingredients = pizza.getIngredients();
- if (ingredients != null && !ingredients.isEmpty()) {
- for (Map.Entry entry : ingredients.entrySet()) {
- Ingredient ingredient = entry.getKey();
- Integer count = entry.getValue();
- message.append("- ").append(ingredient.getName())
- .append(" (Количество: ").append(count).append(")\n");
- }
- System.out.println(message.toString());
- } else
- System.out.println("Вы не выбрали ингредиенты для пиццы");
- } else
- System.out.println("Ошибка при печати информации по пицце");
- }
-}
+package controller;
+
+import model.Ingredient;
+import model.Pizza;
+
+import java.util.HashMap;
+import java.util.Map;
+
+public class CliController {
+
+ public static void printHelloMessage() {
+ System.out.println("Добро пожаловать в приложением \"Pizza " +
+ "Order\".\nС его помощью вы можете осуществить " +
+ "процесс заказа пиццы, выбрав подходящий размер " +
+ "пиццы и ингридиенты.\nДля получения более полной " +
+ "информации о приложении введите команду \"?\" " +
+ "или \"help\".\"");
+ }
+
+ public static void printHelpMessage() {
+ System.out.println("Команды:\n" +
+ "\t-store - получить информацию о наличии " +
+ "ингридиентов.\n" +
+ "\t-size, --S - установить размер пиццы " +
+ "(целочисленное, положительное).\n" +
+ "\t-add <\"название ингридиента\" количество>, --A" +
+ " <\"название ингридиента\" количество> - добавить" +
+ " ингридиент к пицце (число ингридиентов в пицце -" +
+ " целочисленное, положительное). Пример: -add " +
+ "\"сыр\" 2 (-A \"сыр\" 2). При множественном " +
+ "добавлении: -add \"сыр\" 2, \"колбаса\" 3 (-A " +
+ "\"сыр\" 2, \"колбаса\" 3).\n" +
+ "\t-rem <\"название ингридиента\" количество>, --R" +
+ " <\"название ингридиента\" количество> - удалить " +
+ "ингридиент из пиццы (число удаляемых ингридиентов" +
+ " из пиццы - целочисленное, положительное). " +
+ "Пример: -rem \"сыр\" 2 (-R \"сыр\" 2). При " +
+ "множественном удалении ингридиентов: -rem \"сыр\"" +
+ " 2, \"колбаса\" 3 (-R \"сыр\" 2, \"колбаса\" 3)" +
+ ".\n" +
+ "\t-ok, --OK - выдача заказа (печать информации о " +
+ "заказанной пиццы).");
+ }
+
+ public static void printStoreMessage(HashMap ingredients) {
+ if (ingredients != null && ingredients.size() > 0) {
+ StringBuilder message = new StringBuilder(
+ "На данный момент в хранилище имеются следующие ингриденты:\n");
+ for (Map.Entry entry : ingredients.entrySet()) {
+ Ingredient ingredient = entry.getKey();
+ Integer count = entry.getValue();
+ message.append("- ").append(ingredient.getName())
+ .append(" (количество: ").append(count).append(")\n");
+ }
+ System.out.println(message.toString());
+ } else
+ System.out.println("Хранилище пусто");
+ }
+
+ public static void printOkMessage(Pizza pizza) {
+ if (pizza != null) {
+ StringBuilder message = new StringBuilder("Заказ на пиццу:\n")
+ .append("Размер: ").append(pizza.getSize()).append(" см\n");
+ HashMap ingredients = pizza.getIngredients();
+ if (ingredients != null && !ingredients.isEmpty()) {
+ for (Map.Entry entry : ingredients.entrySet()) {
+ Ingredient ingredient = entry.getKey();
+ Integer count = entry.getValue();
+ message.append("- ").append(ingredient.getName())
+ .append(" (Количество: ").append(count).append(")\n");
+ }
+ System.out.println(message.toString());
+ } else
+ System.out.println("Вы не выбрали ингредиенты для пиццы");
+ } else
+ System.out.println("Ошибка при печати информации по пицце");
+ }
+}
diff --git a/src/main/java/model/DefaultStorage.java b/src/main/java/model/DefaultStorage.java
index cc60d79..e2063e0 100644
--- a/src/main/java/model/DefaultStorage.java
+++ b/src/main/java/model/DefaultStorage.java
@@ -1,75 +1,75 @@
-package model;
-
-import java.util.HashMap;
-
-public class DefaultStorage extends Storage {
-
- private HashMap ingredients;
-
- public DefaultStorage() {
- initIngredients();
- }
-
- @Override
- public void addIngredient(
- Ingredient ingredient,
- int count
- ) throws StorageException {
- if (!ingredientsNotNull())
- initIngredients();
- if (ingredient != null && count > 0) {
- HashMap ingredients = getStorageIngredients();
- // Если ингредиент уже существует
- if (ingredients.containsKey(ingredient)) {
- int alreadyExistIngredientCount = ingredients.get(
- ingredient);
- ingredients.put(
- ingredient, alreadyExistIngredientCount + count);
- // Если не существует
- } else
- ingredients.put(ingredient, count);
- } else
- throw new StorageException(
- "Введён некорректный ингредиент или его количество");
- }
-
- @Override
- public void removeIngredient(Ingredient ingredient, int count)
- throws StorageException {
- if (!ingredientsNotNull())
- initIngredients();
- if (ingredient != null && count > 0) {
- HashMap ingredients = getStorageIngredients();
- // Если ингридиент уже существует
- if (ingredients.containsKey(ingredient)) {
- int alreadyExistIngredientCount = ingredients.get(
- ingredient);
- // Если количество уже существующих элементов больше либо
- // равно количеству удаляемых
- if (Math.abs(count) >= alreadyExistIngredientCount)
- ingredients.remove(ingredient);
- else
- ingredients.put(
- ingredient, alreadyExistIngredientCount - count);
- // Если не существует
- } else
- throw new StorageException(
- "Вы пытаетесь удалить несуществующий ингридиент в хранилище");
- } else
- throw new StorageException(
- "Введён некорректный ингридиент или его количество");
- }
-
- @Override
- public HashMap getStorageIngredients() {
- return ingredients;
- }
-
- private boolean ingredientsNotNull() {
- return ingredients != null;
- }
-
- private void initIngredients() {
- ingredients = new HashMap<>();
- }
-}
+package model;
+
+import java.util.HashMap;
+
+public class DefaultStorage extends Storage {
+
+ private HashMap ingredients;
+
+ public DefaultStorage() {
+ initIngredients();
+ }
+
+ @Override
+ public void addIngredient(
+ Ingredient ingredient,
+ int count
+ ) throws StorageException {
+ if (!ingredientsNotNull())
+ initIngredients();
+ if (ingredient != null && count > 0) {
+ HashMap ingredients = getStorageIngredients();
+ // Если ингредиент уже существует
+ if (ingredients.containsKey(ingredient)) {
+ int alreadyExistIngredientCount = ingredients.get(
+ ingredient);
+ ingredients.put(
+ ingredient, alreadyExistIngredientCount + count);
+ // Если не существует
+ } else
+ ingredients.put(ingredient, count);
+ } else
+ throw new StorageException(
+ "Введён некорректный ингредиент или его количество");
+ }
+
+ @Override
+ public void removeIngredient(Ingredient ingredient, int count)
+ throws StorageException {
+ if (!ingredientsNotNull())
+ initIngredients();
+ if (ingredient != null && count > 0) {
+ HashMap ingredients = getStorageIngredients();
+ // Если ингридиент уже существует
+ if (ingredients.containsKey(ingredient)) {
+ int alreadyExistIngredientCount = ingredients.get(
+ ingredient);
+ // Если количество уже существующих элементов больше либо
+ // равно количеству удаляемых
+ if (Math.abs(count) >= alreadyExistIngredientCount)
+ ingredients.remove(ingredient);
+ else
+ ingredients.put(
+ ingredient, alreadyExistIngredientCount - count);
+ // Если не существует
+ } else
+ throw new StorageException(
+ "Вы пытаетесь удалить несуществующий ингридиент в хранилище");
+ } else
+ throw new StorageException(
+ "Введён некорректный ингридиент или его количество");
+ }
+
+ @Override
+ public HashMap getStorageIngredients() {
+ return ingredients;
+ }
+
+ private boolean ingredientsNotNull() {
+ return ingredients != null;
+ }
+
+ private void initIngredients() {
+ ingredients = new HashMap<>();
+ }
+}
diff --git a/src/main/java/model/Ingredient.java b/src/main/java/model/Ingredient.java
index 4c436af..50424bd 100644
--- a/src/main/java/model/Ingredient.java
+++ b/src/main/java/model/Ingredient.java
@@ -1,39 +1,39 @@
-package model;
-
-import java.util.Objects;
-
-/**
- * Класс-модель, описывающая ингридиент
- */
-public class Ingredient {
-
- private String name;
-
- public Ingredient(String name) {
- this.name = name.toLowerCase();
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o == null || getClass() != o.getClass())
- return false;
- Ingredient that = (Ingredient) o;
- return Objects.equals(name, that.name);
- }
-
- @Override
- public int hashCode() {
-
- return Objects.hash(name);
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-}
+package model;
+
+import java.util.Objects;
+
+/**
+ * Класс-модель, описывающая ингридиент
+ */
+public class Ingredient {
+
+ private String name;
+
+ public Ingredient(String name) {
+ this.name = name.toLowerCase();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o)
+ return true;
+ if (o == null || getClass() != o.getClass())
+ return false;
+ Ingredient that = (Ingredient) o;
+ return Objects.equals(name, that.name);
+ }
+
+ @Override
+ public int hashCode() {
+
+ return Objects.hash(name);
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+}
diff --git a/src/main/java/model/Pizza.java b/src/main/java/model/Pizza.java
index 8096217..cc4e9d9 100644
--- a/src/main/java/model/Pizza.java
+++ b/src/main/java/model/Pizza.java
@@ -1,103 +1,102 @@
-package model;
-
-import java.util.HashMap;
-
-/**
- * Класс-модель, который описывает сущность типа "пицца".
- */
-public class Pizza {
-
- private int size;
-
- private HashMap ingredients;
-
- public Pizza() {
-
- }
-
- public Pizza(
- int size, HashMap ingredients
- ) {
- this.size = size;
- this.ingredients = ingredients;
- }
-
- public void addIngredient(
- Ingredient ingredient,
- int count
- ) throws PizzaException {
- if (ingredient != null && count > 0) {
- // Проверка на существование коллекции
- if (!ingredientsCollectionNotNull())
- initIngredientsCollection();
- // Если элемент уже существует
- if (ingredients.containsKey(ingredient)) {
- int alreadyExistIngredientCount = ingredients.get(
- ingredient);
- ingredients.put(
- ingredient, alreadyExistIngredientCount + count);
- // Если не существует
- } else {
- ingredients.put(ingredient, count);
- }
- } else
- throw new PizzaException(
- "Указан некорректный ингредиент или его количество");
- }
-
- public void removeIngredient(
- Ingredient ingredient,
- int count
- ) throws PizzaException {
- if (ingredient != null && count > 0) {
- // Проверка на существование коллекции
- if (!ingredientsCollectionNotNull())
- initIngredientsCollection();
- // Если элемент уже существует
- if (ingredients.containsKey(ingredient)) {
- int alreadyExistIngredientCount = ingredients.get(
- ingredient);
- // Если количество уже существующих элементов больше либо
- // равно количеству удаляемых
- if (Math.abs(count) >= alreadyExistIngredientCount)
- ingredients.remove(ingredient);
- else
- ingredients.put(
- ingredient, alreadyExistIngredientCount - count);
- // Если элемента не сущетсвует
- } else
- throw new PizzaException(
- "Вы пытаетесь удалить ингредиент, который не существует в пицце");
- } else
- throw new PizzaException(
- "Указан некорректный ингредиент или его количество");
- }
-
- private boolean ingredientsCollectionNotNull() {
- return ingredients != null;
- }
-
- private void initIngredientsCollection() {
- ingredients = new HashMap();
- }
-
- // -- Getters & Setters --
-
- public int getSize() {
- return size;
- }
-
- public void setSize(int size) {
- this.size = size;
- }
-
- public HashMap getIngredients() {
- return ingredients;
- }
-
- public void setIngredients(
- HashMap ingredients
- ) {
- this.ingredients = ingredients;
- }
-}
+package model;
+
+import java.util.HashMap;
+
+/**
+ * Класс-модель, который описывает сущность типа "пицца".
+ */
+public class Pizza {
+
+ private int size;
+
+ private HashMap ingredients;
+
+ public Pizza() {
+
+ }
+
+ public Pizza(
+ int size, HashMap ingredients
+ ) {
+ this.size = size;
+ this.ingredients = ingredients;
+ }
+
+ public void addIngredient(
+ Ingredient ingredient,
+ int count
+ ) throws PizzaException {
+ if (ingredient != null && count > 0) {
+ // Проверка на существование коллекции
+ if (!ingredientsCollectionNotNull())
+ initIngredientsCollection();
+ // Если элемент уже существует
+ if (ingredients.containsKey(ingredient)) {
+ int alreadyExistIngredientCount = ingredients.get(
+ ingredient);
+ ingredients.put(
+ ingredient, alreadyExistIngredientCount + count);
+ // Если не существует
+ } else {
+ ingredients.put(ingredient, count);
+ }
+ } else
+ throw new PizzaException(
+ "Указан некорректный ингредиент или его количество");
+ }
+
+ public void removeIngredient(
+ Ingredient ingredient,
+ int count
+ ) throws PizzaException {
+ // Проверка входных значений
+ if (ingredient == null || count <= 0) {
+ throw new PizzaException("Указан некорректный ингредиент или его количество");
+ }
+
+ // Проверка на существование коллекции
+ if (!ingredientsCollectionNotNull())
+ initIngredientsCollection();
+
+ // Проверка наличия ингридиента в пицце
+ if (ingredients.containsKey(ingredient)) {
+ throw new PizzaException("Вы пытаетесь удалить ингредиент, который не существует в пицце");
+ }
+
+ // Изменяем количество ингридиентов
+ int ingredientCount = ingredients.get(ingredient);
+ if (count >= ingredientCount) {
+ ingredients.remove(ingredient);
+ } else {
+ ingredients.put(ingredient, ingredientCount - count);
+ }
+ }
+
+ private boolean ingredientsCollectionNotNull() {
+ return ingredients != null;
+ }
+
+ private void initIngredientsCollection() {
+ ingredients = new HashMap();
+ }
+
+ // -- Getters & Setters --
+
+ public int getSize() {
+ return size;
+ }
+
+ public void setSize(int size) {
+ this.size = size;
+ }
+
+ public HashMap getIngredients() {
+ return ingredients;
+ }
+
+ public void setIngredients(
+ HashMap ingredients
+ ) {
+ this.ingredients = ingredients;
+ }
+}
diff --git a/src/main/java/model/PizzaException.java b/src/main/java/model/PizzaException.java
index 70d1fa6..a37a772 100644
--- a/src/main/java/model/PizzaException.java
+++ b/src/main/java/model/PizzaException.java
@@ -1,14 +1,14 @@
-package model;
-
-public class PizzaException extends Exception {
-
- private static final String DEFAULT_MESSAGE = "Произошла ошибка при создании пиццы";
-
- public PizzaException(String message) {
- super(message);
- }
-
- public PizzaException() {
- super(DEFAULT_MESSAGE);
- }
-}
+package model;
+
+public class PizzaException extends Exception {
+
+ private static final String DEFAULT_MESSAGE = "Произошла ошибка при создании пиццы";
+
+ public PizzaException(String message) {
+ super(message);
+ }
+
+ public PizzaException() {
+ super(DEFAULT_MESSAGE);
+ }
+}
diff --git a/src/main/java/model/Storage.java b/src/main/java/model/Storage.java
index 2e3c8a9..e9b0bc9 100644
--- a/src/main/java/model/Storage.java
+++ b/src/main/java/model/Storage.java
@@ -1,15 +1,15 @@
-package model;
-
-import java.util.HashMap;
-
-public abstract class Storage {
-
- public abstract void addIngredient(Ingredient ingredient, int count)
- throws StorageException;
-
- public abstract HashMap getStorageIngredients()
- throws StorageException;
-
- public abstract void removeIngredient(Ingredient ingredient, int count)
- throws StorageException;
-}
+package model;
+
+import java.util.HashMap;
+
+public abstract class Storage {
+
+ public abstract void addIngredient(Ingredient ingredient, int count)
+ throws StorageException;
+
+ public abstract HashMap getStorageIngredients()
+ throws StorageException;
+
+ public abstract void removeIngredient(Ingredient ingredient, int count)
+ throws StorageException;
+}
diff --git a/src/main/java/model/StorageException.java b/src/main/java/model/StorageException.java
index 072c3f1..ffbb34a 100644
--- a/src/main/java/model/StorageException.java
+++ b/src/main/java/model/StorageException.java
@@ -1,14 +1,14 @@
-package model;
-
-public class StorageException extends Exception {
-
- private static final String DEFAULT_MESSAGE = "Произошла ошибка при работе с хранилищем";
-
- public StorageException(String message) {
- super(message);
- }
-
- public StorageException() {
- super(DEFAULT_MESSAGE);
- }
-}
+package model;
+
+public class StorageException extends Exception {
+
+ private static final String DEFAULT_MESSAGE = "Произошла ошибка при работе с хранилищем";
+
+ public StorageException(String message) {
+ super(message);
+ }
+
+ public StorageException() {
+ super(DEFAULT_MESSAGE);
+ }
+}
From 75107d4cfeb017f5f53c95af50372e9f4db5f640 Mon Sep 17 00:00:00 2001
From: Web-Sheriff <35970102+Web-Sheriff@users.noreply.github.com>
Date: Mon, 24 Jun 2019 19:43:39 +0300
Subject: [PATCH 2/2] Force push
---
pizza-order-training.iml | 2 +
pom.xml | 8 +++
src/main/java/model/Pizza.java | 2 +-
src/main/java/test/AddIngredientTest.java | 59 ++++++++++++++++++++
src/main/java/test/RemoveIngredientTest.java | 59 ++++++++++++++++++++
5 files changed, 129 insertions(+), 1 deletion(-)
create mode 100644 src/main/java/test/AddIngredientTest.java
create mode 100644 src/main/java/test/RemoveIngredientTest.java
diff --git a/pizza-order-training.iml b/pizza-order-training.iml
index 4069457..0d8502f 100644
--- a/pizza-order-training.iml
+++ b/pizza-order-training.iml
@@ -9,5 +9,7 @@
+
+
\ No newline at end of file
diff --git a/pom.xml b/pom.xml
index 3dde887..82d79d7 100644
--- a/pom.xml
+++ b/pom.xml
@@ -19,6 +19,14 @@
+
+
+ junit
+ junit
+ 4.12
+ compile
+
+
\ No newline at end of file
diff --git a/src/main/java/model/Pizza.java b/src/main/java/model/Pizza.java
index cc4e9d9..915721c 100644
--- a/src/main/java/model/Pizza.java
+++ b/src/main/java/model/Pizza.java
@@ -59,7 +59,7 @@ public void removeIngredient(
initIngredientsCollection();
// Проверка наличия ингридиента в пицце
- if (ingredients.containsKey(ingredient)) {
+ if (!ingredients.containsKey(ingredient)) {
throw new PizzaException("Вы пытаетесь удалить ингредиент, который не существует в пицце");
}
diff --git a/src/main/java/test/AddIngredientTest.java b/src/main/java/test/AddIngredientTest.java
new file mode 100644
index 0000000..de2c19c
--- /dev/null
+++ b/src/main/java/test/AddIngredientTest.java
@@ -0,0 +1,59 @@
+package test;
+
+import model.Ingredient;
+import model.Pizza;
+import model.PizzaException;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class AddIngredientTest {
+
+ @Test
+ public void whenAddNotNullIngredient_itInPizza() throws PizzaException {
+ // given
+ Pizza pizza = new Pizza();
+ Ingredient ingredient = new Ingredient("Cheese");
+
+ // when
+ pizza.addIngredient(ingredient, 1);
+
+ // then
+ Assert.assertTrue(pizza.getIngredients().containsKey(ingredient) &&
+ pizza.getIngredients().get(ingredient) == 1);
+ }
+
+ @Test
+ public void whenAddMultipleSameIngredients_itInPizza() throws PizzaException {
+ // given
+ Pizza pizza = new Pizza();
+ Ingredient ingredient = new Ingredient("Cheese");
+
+ // when
+ pizza.addIngredient(ingredient, 1);
+ pizza.addIngredient(ingredient, 1);
+
+ // then
+ Assert.assertTrue(pizza.getIngredients().containsKey(ingredient) &&
+ pizza.getIngredients().get(ingredient) == 2);
+ }
+
+ @Test(expected = PizzaException.class)
+ public void whenAddNullIngredient_exception() throws PizzaException {
+ // given
+ Pizza pizza = new Pizza();
+ Ingredient ingredient = null;
+
+ // when
+ pizza.addIngredient(ingredient, 1);
+ }
+
+ @Test(expected = PizzaException.class)
+ public void whenAddNonPositiveNumberIngredient_exception() throws PizzaException {
+ // given
+ Pizza pizza = new Pizza();
+ Ingredient ingredient = null;
+
+ // when
+ pizza.addIngredient(ingredient, -1);
+ }
+}
diff --git a/src/main/java/test/RemoveIngredientTest.java b/src/main/java/test/RemoveIngredientTest.java
new file mode 100644
index 0000000..fc0dca9
--- /dev/null
+++ b/src/main/java/test/RemoveIngredientTest.java
@@ -0,0 +1,59 @@
+package test;
+
+import model.Ingredient;
+import model.Pizza;
+import model.PizzaException;
+import org.junit.Assert;
+import org.junit.Test;
+
+public class RemoveIngredientTest {
+
+ @Test
+ public void whenRemoveNotNullIngredient_itInPizza() throws PizzaException {
+ // given
+ Pizza pizza = new Pizza();
+ Ingredient ingredient = new Ingredient("Cheese");
+ pizza.addIngredient(ingredient, 1);
+
+ // when
+ pizza.removeIngredient(ingredient, 1);
+
+ // then
+ Assert.assertFalse(pizza.getIngredients().containsKey(ingredient));
+ }
+
+ @Test
+ public void whenAddMultipleSameIngredients_itInPizza() throws PizzaException {
+ // given
+ Pizza pizza = new Pizza();
+ Ingredient ingredient = new Ingredient("Cheese");
+ pizza.addIngredient(ingredient, 10);
+
+ // when
+ pizza.removeIngredient(ingredient, 1);
+
+ // then
+ Assert.assertTrue(pizza.getIngredients().containsKey(ingredient) &&
+ pizza.getIngredients().get(ingredient) == 9);
+ }
+
+ @Test(expected = PizzaException.class)
+ public void whenRemoveNullIngredient_exception() throws PizzaException {
+ // given
+ Pizza pizza = new Pizza();
+ Ingredient ingredient = null;
+
+ // when
+ pizza.removeIngredient(ingredient, 1);
+ }
+
+ @Test(expected = PizzaException.class)
+ public void whenRemoveNonPositiveNumberIngredient_exception() throws PizzaException {
+ // given
+ Pizza pizza = new Pizza();
+ Ingredient ingredient = null;
+
+ // when
+ pizza.addIngredient(ingredient, -1);
+ }
+}