JavaRush /Java Blog /Random EN /What is interface programming? Let's play architect

What is interface programming? Let's play architect

Published in the Random EN group
Maybe you once heard that there is such a thing as “interface programming”. It's time to get to know this better. There will be little text and a lot of code (without logic). I couldn't find when the first interfaces appeared. It was probably a very long time ago, and the Internet forgot about it. Anyway. The idea of ​​the interface is simple: describe what we will do without going into details. Those. it doesn't matter how you do it, it matters what you do. But after I wrote this article, I found a good one on a similar topic here in groups. Click on the link and read, the more the better! Content:

Why is this necessary?

When the code consists of one class, this is not really necessary. But when classes must interact with each other, and their number exceeds several dozen, then it’s time to think about design. First, think through the entire structure of the project from top to bottom (from maximum abstraction to implementation). If several people are working on a project, then it is very convenient to agree, describe the interaction interfaces of classes, then disassemble these interfaces and start implementing them. The result is good parallelism of tasks; they are easy to divide, because everyone has agreed on everything, but no one cares about the details.

What does this give to the developer?

The developer does not need an implementation of the class. This means that after everyone has agreed, he takes the interfaces he needs and uses them. The implementation will be substituted when it is ready. Let me show you my example, and then we’ll talk further. I decided to write a small cash register project. She will help choose tickets, sell them, give money to and take money from the bank, change money for those who come in large numbers. So, my architectural exhalation: PS there is no need to copy and create a structure, for the sake of laziness I have attached an archive with code at the end of the article ;) Structure:
What is interface programming?  Let's play architect - 1
A bunch of models:
package cashbox.model;

public enum Currency {
    USD,
    EUR,
    RUR
}
package cashbox.model;

public interface Direction {
    /**
     * @return город How цель направления, куда едем/летим/двигаемся
     */
    String getCity();
}
package cashbox.model;

/**
 * модель денег
 */
public interface Money {
    /**
     * @return тип валюты
     */
    Currency getCurrency();

    /**
     * @return сумма денег
     */
    long getAmount();
}
package cashbox.model;

public interface Ticket {
    /**
     * @return направление куда двигаемся
     */
    Direction getDirection();

    /**
     * @return цена билета
     */
    Money getPrice();

    /**
     * @return транспорт на котором передвигаемся
     */
    Transport getTransport();
}
package cashbox.model;

public interface Transport {
}
Exception pair:
package cashbox.exception;

public class NoSoMuchMoneyException extends RuntimeException {
}
package cashbox.exception;

import cashbox.model.Money;

public class NoSuchCurrencyException extends RuntimeException {
    private Money money;

    public NoSuchCurrencyException(Money money) {
        this.money = money;
    }

    public NoSuchCurrencyException(String message, Money money) {
        super(message);
        this.money = money;
    }

    public Money getMoney() {
        return money;
    }
}
The cash register is the most important part:
package cashbox;

import cashbox.exception.NoSoMuchMoneyException;
import cashbox.exception.NoSuchCurrencyException;
import cashbox.model.*;
import javafx.util.Pair;

import java.util.List;
import java.util.Map;

public interface CashBox {

    /**
     * @param direction направление билета
     * @return Стоимость проезда по видам транспорта
     */
    Map<Transport, Money> getPrice(Direction direction);

    /**
     * Продать билет
     * @param money деньги за билет
     * @return пару из билета и сдачи
     */
    Pair<Ticket, Money> sellTicket(Money money);

    /**
     * обмен валюты
     * @param moneyFrom валюта, которую передает клиент
     * @param currency валюта, которую клиент хочет получить, тут будет учитываться только тип валюты,
     *                 количество будет проигнорировано
     * @return Требуемая валюта
     * @throws NoSoMuchMoneyException если недостаточно денег в кассе для обмена
     * @throws NoSuchCurrencyException если нет такой валюты, отсутствующая валюта передается How атрибут
     */
    Money change(Money moneyFrom, Currency currency) throws NoSoMuchMoneyException, NoSuchCurrencyException;

    /**
     * Инкасация - отправить деньги в банк
     * @param money - сумма и валюта, можно передать несколько
     */
    void sendToBank(Money... money);

    /**
     * Запрос денег из банка
     * @param money - сумма и валюта необходимая кассе
     */
    void requestFromBank(Money... money);

    /**
     * Подбор билета.
     * В метод передается либо одно, либо другое, либо вместе.
     * Если оба атрибута null значит вызов некорректный
     * @param transport - желаемый транспорт
     * @param direction - желаемое направление
     * @return список подходящих билетов
     */
    List<Ticket> chooseBy(Transport transport, Direction direction);
}
The first thing that catches the eye of an unprepared developer is javadoc. Although, probably, they are familiar to an untrained developer. Some people are lazy sometimes, but my code is already good, without a document ;) Even now I don’t want to write a document about some things. Well, why write to transport that it is transport? Let's leave that for later! I tried to describe in documents everything that was needed. Now I’ll explain why it’s more convenient to write code this way. Look, now I can give you an interface CashBoxand ask you to implement it. Isn't he difficult? Plus the required behavior is described in the documentation. You won't have to wait for someone to write models or anything else. You take interface models and start working based on them. Now you're programming in interfaces, congratulations. And now the main thing. I can give you the task to implement CashBox, as well as someone else, so that we have 2 implementations. For example, suburban and international ticket office. You will be able to write code in parallel and any team member who will write code based on CashBoxcan already start and build on the interface. It is very comfortable. Multitasking, to hell with it. Link to the code on Google Drive -> here
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION