Implementing Snap-To-Edge Functionality Recently I've written some code which implements snap-to-edge functionality for some windows.

There is some code duplication as you can see. I think this code can be simpler or possibly improved.

// If 'rtParent' and 'rtChild' are closed each other as 'ENABLE_STICK_VALUE', return true;  
auto IsNearEachOther = []( const QRect&amp; rtParent, const QRect&amp; rtChild ) -&gt; std::tuple&lt; bool, QPoint&gt;
{
    bool isNear = false;
    QPoint ptMoveTarget;

    // If 'rtChild's left position is closing to 'rtParent's right position.
    if ( rtChild.left() &gt; rtParent.right() )
    {
        if ( ( ( rtChild.left() - rtParent.right() ) &lt;= ENABLE_STICK_VALUE )
            &amp;&amp; ( rtChild.top() &gt;= ( rtParent.top() - ENABLE_STICK_VALUE ) )
            &amp;&amp; ( rtChild.top() &lt;= ( rtParent.bottom() + ENABLE_STICK_VALUE ) ) )
        {
            isNear = true;
            ptMoveTarget = QPoint( rtParent.right(), rtParent.top() );
        }
    }

    // If 'rtChild's right position is closing to 'rtParent's left position.
    if ( rtChild.right() &lt; rtParent.left() )
    {
        if ( ( ( rtParent.left() - rtChild.right() ) &lt;= ENABLE_STICK_VALUE )
            &amp;&amp; ( rtChild.top() &gt;= ( rtParent.top() - ENABLE_STICK_VALUE ) )
            &amp;&amp; ( rtChild.top() &lt;= ( rtParent.bottom() + ENABLE_STICK_VALUE ) ) )
        {
            isNear = true;
            ptMoveTarget = QPoint( rtParent.left() - rtChild.width() , rtParent.top() );
        }
    }

    return std::make_tuple( isNear, ptMoveTarget );
};

QRect rtParent = m_pParentChatRoom-&gt;geometry();
QRect rtCurrent = geometry();

bool result = false;
QPoint ptMoveTarget;
std::tie( result, ptMoveTarget ) = IsNearEachOther( rtParent, rtCurrent );
if ( result )
{
    move( ptMoveTarget );
}
Definitely extract method for the following code:

if ( rtChild.right() &lt; rtParent.left() )
{
    if ( ( ( rtParent.left() - rtChild.right() ) &lt;= ENABLE_STICK_VALUE )
        &amp;&amp; ( rtChild.top() &gt;= ( rtParent.top() - ENABLE_STICK_VALUE ) )
        &amp;&amp; ( rtChild.top() &lt;= ( rtParent.bottom() + ENABLE_STICK_VALUE ) ) )
    {
        isNear = true;
        ptMoveTarget = QPoint( rtParent.left() - rtChild.width() , rtParent.top() );
    }
}


Where you can pass through a left/right variable however you want and then change:

rtParent.left() - rtChild.width() to rely on the given parameter, falling back onto rtParent.right()

The same can be said for any other small changes in the code, such as

rtChild.right() &lt; rtParent.left()
versus
rtChild.left() &gt; rtParent.right()

I'm not going to give you the exact solution, but that if condition holds most of the repeated code and can be brought out into something like snapTo(right/left)