What is the importance of the interface in this particular code?

Asked

Viewed 148 times

2

If we will put the interface functions, also inside the class, then create interface?

Example:

Interface

interface Teste {
    function olaMundo($texto);
}

Class

class Testando implements Teste {
    function olaMundo($texto); //Método da interface
}

Index.php

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Teste</title>
    </head>
    <body>
        <?php
            require_once 'Testando.php';
            $i = new Testando;
            $i->olaMundo("Ola mundo!");
        ?>
    </body>
</html>

Then, in this case, what was the role of the interface in this code?

Show 3 more comments

1 answer

8


In this specific example it apparently has no role. Too many abstract examples do not teach the use of something, except in rare cases. The example may be fictitious, but when you analyze whether the concept is being followed, it can simply put any nonsense. It’s not just putting any set of words. Context programming is very important. The detail is what defines what to do. Meaningful names are documentation and can explain what is taking place there. This code says nothing unless it is a test, it gives no context.

This is a case where the interface is not being useful because it was put in place to illustrate something meaningless. Interfaces are useful to abstract ideas, to establish contracts when necessary. This case is not necessary.

If it was a real case she’d have one or more method signatures which would serve as a contract, so the type of interface could be used somewhere and any class that implements the interface could be used in a given algorithm. Which is very weird in a language that preaches dynamic typing, worse, weak typing, but we already know, it’s PHP, it’s part of the unofficial philosophy to do weird things.

If you don’t have an advantage, a specific function, don’t use it. That goes for anything. Utility occurs in complex systems where contracts need to be respected.

Some interface questions available on the site that should help you understand:

  • Thank you, Bigown, I know I made a silly code, but with your answer and LINQ’s, I could understand.

  • 2

    Exemplos abstratos não costumam ensinar o uso de algo, salvo raros casos I wish I could upvote again just for that sentence.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.