why interfaces in dynamic/loosely-typed languages?

I work in php, and the concept of interfaces seems to me a little useless here. From reading, I understand that interfaces are part of "design by contract", but without at least guaranteeing a return of a type of a particular kind, there really isn't any contract. It seems it's like a contract that reads, "We agree to do the following: '' " -- there are no terms of the agreement.

If I want a guarantee that an object has a method, it doesn't seem like interfaces are particularly useful. If I try to call a method that an object doesn't have, I get a Fatal Error, so I find out pretty quickly that that class doesn't have a method with that name. If I want to be smart and check beforehand whether a class has a method, then checking the interface, and seeing whether the object implements that interface doesn't seem to save me any more time than just checking that object directly ( which I would do anyways to see if the class had that method regardless of any interfaces it did or didn't implement).

In other words, just because I have a set of methods that have particular names, that doesn't guarantee me any particular behavior. If I'm guaranteed a return of a variable of a certain type, I at least have some inkling of what the output would be, and I can write code that uses an object with that interface, because I know what I'm getting out of it. If it returns a string, I can continue coding with at least the certainty that I'm dealing with a string output afterward. So I'm guaranteed at least some behavior when a return type is specified. Is guaranteeing behavior part of what interfaces are for, or no?

The only thing I can think of is that when I'm writing code, it serves as a post-it note to myself to be sure to create certain methods when writing that class later on. It seems more like scaffolding for when I'm writing the code; I don't see much benefit from when I'm actually using it. So it's more for me to keep the standard when I'm creating classes than when I'm writing them. This benefit doesn't really seem to be captured in the concept of design by contract.

What benefit(s) do you actually get from using an interface in dynamic/loose-typed languages like PHP? Are they great, or is it something that more robust OO languages implement, so PHP implements it also?

7
задан user151841 25 August 2010 в 16:41
поделиться

4 ответа

Дизайн по контракту усложняется без возвращаемых типов, но не забывайте отдавать предпочтение «сказать», а не «спросить».

Я считаю, что интерфейс - это что-то вроде ответственности. Вы пишете код, и вам нужен соавтор. Вы просите его сделать что-то, потому что код, над которым вы работаете, не может делать все. Итак, вы просите другой объект что-то сделать. Интерфейс гарантирует, что соавтор выполнит работу, но скрывает часть «как» это сделано.

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

1
ответ дан 7 December 2019 в 14:25
поделиться

Хочу отметить, что PHP 5.4 будет поддерживать подсказку типов. Прямо сейчас я думаю, что есть только подсказка типа для аргументов функции, но я полагаю, что она будет и для возвращаемых значений. (По крайней мере, уже есть RFC, хотя и очень старый и устаревший.)

0
ответ дан 7 December 2019 в 14:25
поделиться

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

Например, если я создаю оболочку БД и она поддерживает поведение, которое вы сами регистрируете в бутстрапе, то перед запуском вашего поведения (например, suggable) я проверю, что они реализуют мой "DB_Wrapper_Behaviour_Interface" с помощью используя:

if(!($behaviourObject instanceof DB_Wrapper_Behaviour_Interface)) {
    throw new Exception("Your behaviour doesn't implement my interface");
}
3
ответ дан 7 December 2019 в 14:25
поделиться

Получить фатальную ошибку не всегда "легко". Иногда вам нужно перейти к определенному модулю/действию, чтобы увидеть, что в вашем классе действительно чего-то не хватает. Интерфейс позволяет убедиться, что каждый метод реализован, и задокументировать этот метод (какими точно будут параметры, как должны выглядеть возвращаемые значения). Это полезно, если параметры/значения представляют собой массивы с определенной структурой, и вы не хотите вместо этого использовать классы (ради простоты).

0
ответ дан 7 December 2019 в 14:25
поделиться
Другие вопросы по тегам:

Похожие вопросы: