0

Command Query Separation is a useful principle, though it's not always ideal. Sometimes you need to run a process, which will result in useful data you need to return. My specific case is uploading a file to a server and getting the ID of the file (which is assigned by another system I have no control over).

In simple terms, the function is something like this:

def upload_file(filepath):
    # Set up filedata with values
    result = upload_to_server(filedata)
    return result['id']

I'm not debating whether or not to disregard CQS, but I am wondering how to make this especially clear to a user. For instance upload_file doesn't make the return value explicit, but get_upload_file is also ambiguous. A docstring is an obvious must to make the function explicit for anyone who reads that.

But I was wondering are there any other helpful patterns that can make it explicit that a function performs actions and returns a value. Or alternatively, should I just focus on making one of these aspects clear and not worry about fully informing the user?

2

I think for python the best practice available would be to note in the docstring that it is a side-effecting function.

def upload_file(filepath):
    """
    Uploads a filepath to a server and also returns the remote server id
    """

If this were a language like scala or haskell you could communicate this with the type signature of the function, for example:

type RemoteServerId = Integer
uploadToServer :: Filepath -> IO RemoteServerId

or

type RemoteServerId = Int
def uploadToServer(path: Filepath): Task[RemoteServerId]

Because python doesn't give you that option, the docstring is your main option.

A supplementary tactic would be to have a naming convention. Perhaps you could be explicit by naming the function upload_to_server_and_return_remote_id(filepath)

  • Don't forget that python3 also has function annotations, so something like def upload_file(filepath) -> "server-id" : could be done. – Glenn Rogers Feb 17 '16 at 18:22
  • @GlennRogers That makes it a little worse honestly, because that signature gives you no indication that it's a side-effecting function. A function looking up ids in a local mapping would have the same signature – Daenyth Feb 17 '16 at 18:49
  • Except then you'd call the function "get_file_locator" or such :) – Glenn Rogers Feb 17 '16 at 20:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.