mercredi 14 février 2018

OOP: When to check for

Imagine a social media application where users can join certain groups in order to interact with its members. So in my business logic I have a function which creates such a new group:

 public void createGroup(String groupname)
    {
        //check if group with the specified name already exists
        if (!groupnameAlreadyExists(groupname))
        {
            //...code creating a new group with the specified name
        }

    }

When you look at the code closely you see that before I create a new Group I check if there already is a group with the specified name.

My Problem: At the place in the code I invoke the above function, I also check if a group with the specified name already exist and based on that i decide what to do next:

public void doStuff(String groupname) {

        if (groupnameAlreadyExists(groupname)) {
            joinGroup(groupname);
        }
        else {
            createGroup(groupname)
        }
    }

So in fact I double check, if the group already exists or not. What is the appropriate programming style for this szenario? Is there a way to be safe of errors, but without double-checking?

Aucun commentaire:

Enregistrer un commentaire