Question

Suppose I have the following definitions:

namespace test
{
    class Test1
    {
        void someMethod(double a);
        void someOtherMethod(double a);
        //...
    };

    class Test2
    {
        void someMethod(double a);
        void someOtherMethod(double a);
        //...
    };
}

Here's an example implementation (method 1):

namespace test
{
    // Test1
    // ----------------

    void Test1::someMethod(double a){
        // do something
    }

    void Test1::someOtherMethod(double a){
        // do something else
    }


    // Test2
    // ----------------

    void Test2::someMethod(double a){
        // do something
    }

    void Test2::someOtherMethod(double a){
        // do something else
    }

}

Here's an alternative implementation (method 2):

// Test1
namespace test
{
    void Test1::someMethod(double a){
        // do something
    }

    void Test1::someOtherMethod(double a){
        // do something else
    }
}

// Test2
namespace test
{
    void Test2::someMethod(double a){
        // do something
    }

    void Test2::someOtherMethod(double a){
        // do something else
    }
}

The usual way to implement things is via method 1. The upshot of method 2 is that all implementation code for each class can be folded away in many editors, a feature that I'm quite fond of.

I was wondering if there is any more elegant way to do this, e.g., without having to re-open the namespace for each new class? I tried this:

{
    void Test1::someMethod(double a){}
}
{
    void Test2::someMethod(double a){}
}

But that doesn't work (for reasons that aren't entirely obvious to me I have to admit...). Is there something valid, similar, without any effect other than make the code foldable?

Obviously, it should be as portable as possible and not depend on any specific editor.

Was it helpful?

Solution

There is no editor-independent way.1 Just close and re-open the namespace.

That said, I think foldability is overrated. In particular, your use-case is simply a symptom of another problem: your files are too long. Do not define more than one class per file (unless the classes are quite small or intrinsically related). This is a simple rule of thumb that works quite well and solves your problem.

If your code files exceed more than a couple hundred lines, split them up.


1 That said, different editors offer different solutions. For instance, in Vim you could do:

namespace test {
    // Test 1 {{{

    void Test1::someMethod(double a){
        // do something
    }
    …

    // }}}


    // Test2 {{{

    void Test2::someMethod(double a){
        // do something
    }
    …

    // }}}
}

({{{,}}} is the default, but configurable, foldmarker.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top