Displee
Displee

Reputation: 720

The logic of programming

I have a question about the logic of programming, checkout the following example:

public function logout() {
     if (Auth::user()) {
         Auth::logout();
     }
}

In the above example we first check if the user is logged in. In this function we can say that only a logged in user is able to logout, but if you only can access the 'logout' function if you are logged in, then it's the same thing. Which one is better and why? I come across a lot of these things, and I never know which one to choose.

Upvotes: 1

Views: 117

Answers (1)

David Hoelzer
David Hoelzer

Reputation: 16331

While it may be true that you should only be able to access this function if you are already logged in, this is just good practice in your code. Here the encapsulated method is making sure that it is being called in a context that makes sense.

The reason this really matters can be illustrated by the many examples of flawed web applications (and others) where the code assumes that users can only select options that they are presented with. However, users can really call any publicly exposed function in the web application regardless of whether or not the function is shown in the HTML interface.

For this reason, the developer must ensure that the context in which a function is called makes sense. In the case you have presented, the class creator has a particular usage in mind and you and I can understand that this should only be accessible if you are logged in, but the developer cannot enforce this on other users unless he includes logic like this (or, perhaps, a check to see if the access is permitted rather than if the user is logged on) within his exposed methods.

Upvotes: 3

Related Questions