way to separate non-class library into header and implementation


way to separate non-class library into header and implementation



Let's say there is a library named test, the header "test.hpp" is like follows:


namespace test
{
int myfun(int a);
}



And as for the implementaion, which style is better?


#include"test.hpp"
int test::myfun(int a){
return a*a;
}



or


#include"test.hpp"
namespace test
{
int myfun(int a){
return a*a;
}
}





Second one is more better. As it is easy to maintain.
– coder3101
Jul 3 at 4:16





Too opinion based, methinks. That said, I agree with @coder3101 .
– user4581301
Jul 3 at 4:29




1 Answer
1



Suppose you have multiple namespaces or nested namespaces in your header as :


namespace test{
namespace subtest{
int Foo(int);
//many other functions go here
} //namespace subtest
} //namespace test



And


namespace test1{
int Foo(int);
}
namespace test2{
int Bar(int);
}



In these cases you should always go with Second implementation as it makes your code more readable and easy to debug.



First one :


#include "test.hpp"
int test::subtest::Foo(int x){return x;}
//many other goes here



Look as the nesting increase everytime to define a function, you need to write fully specified name of the function (repeating namespaces again again).



Second one :


#include "test.h"
namespace test{
namespace subtest{
int Foo(int x){return x;}
//other go here
}
}



This solves namespace name repetition also you can easily refactor things. To debug or refactor a namespace's content simply jump to it's first declaration and change the things. You can also collapse the code under single namespace. (With most ide) making you code more beautiful.



Similarly for multiple namespaces



First one :


#include "test.hpp"
int test1::Foo(int x){return x;}
int test2::Bar(int x){return x;}



How difficult it gets to debug things. Moreover if under two namespace same function name occurs you will have good time debugging.



Second one :


#include "test.hpp"
namespace test1{
int Foo(int x){return x;}
}
namespace test2{
int Bar(int x){return x;}
}



All the declaration within a namespace will be together. So debugging and jumping within namespace will be ease.



Also most open source projects use second implementation






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages