How to get a post from another site in the network

Let’s say we have a site id and a post id. The source doesn’t matter, it could be a database, user input, whatever. Now we want to get a WP_Post object from that site.

A first idea might look like this:

switch_to_blog( $site_id );
$post = get_post( $post_id );
restore_current_blog();

But this is not necessary, there is already a function in WordPress for that:

function get_blog_post( $blog_id, $post_id ) {
    switch_to_blog( $blog_id );
    $post = get_post( $post_id );
    restore_current_blog();

    return $post;
}

Nice, but there is an important, subtle bug in that function: it is using get_post( $post_id ) without a check on the post id. If $post_id is 0, NULL or "", get_post() will use an existing global post object or id. But the current global post is from the source site, not from the target site! The id on site 1 references a completely different post than on site 2.
WordPress doesn’t care. So we have to do that check:

$post = NULL;

if ( ! empty ( $post_id ) )
    $post = get_blog_post( $site_id, $post_id );