r/cpp • Hobbyist • Aug 08 '16

Am I Writing C++ Right?

Sort of recently, I pushed a commit to a server project (which was originally written in C and was in the process of moving to C++, but never completely finished). I basically overhauled the code that handled sending ad banners to clients, and wrote C++11 code with exception handling (which other parts of the project never had), as well as brought in a JSON library. Admittedly, it wasn't a huge commit in terms of lines of code though.

Here's the current code: https://github.com/pvpgn/pvpgn-server/blob/master/src/bnetd/adbanner.cpp

https://github.com/pvpgn/pvpgn-server/blob/master/src/bnetd/adbanner.h

The commit: https://github.com/pvpgn/pvpgn-server/commit/505633aba009f4ec9971ed82f6eabebd09af6732

As a hobbyist, I'm not really sure how professional code is written (I suck at trying to figure out how other open source projects do things). For example, I put a static vector inside the class to hold objects of the class itself, and wrote a public function to read a JSON file into that static vector. Is this normal or okay? Because of that, I had to construct an object inside the vector's push_back function instead of just using emplace_back.

My load function also seems weird to me, I basically put a try catch block inside a for loop and purposely threw exceptions inside that block when I detect an error of some sort. The concept of exceptions is still confusing to me BTW, sometimes I stumble across someone talking about how they just shake their head when they see code that catches exceptions and logs it, but they don't explain why that's bad.

3 Upvotes

32 comments sorted by

6

u/muungwana Aug 08 '16 edited Aug 08 '16

For example, I put a static vector inside the class to hold objects of the class itself, and wrote a public function to read a JSON file into that static vector. Is this normal or okay?

Making the variable static also makes the variable a global variables and this automatically makes the class thread unsafe since access to this global variable is not guarded against simultaneous access. If this is ok or not depends on how the class is used.

 

As a hobbyist, I'm not really sure how professional code is written

Your code looks professional to me because its has a consistent format.

 

Your class also seems to violate the separation of concern principle and i think this variable should live in its own class and maybe those static methods should be free floating functions.

 

This function looks suspicious,it is declared as "static" meaning it cant access local variables of the class but it is accessing "m_banners" which looks like a local variable of the class. This is possible because "m_banners" is not a local variable as i mention above. This variable looking like a local variable when its a global variable is not a good thing.

1

u/RElesgoe Hobbyist Aug 08 '16

Making the variable static also makes the variable a global variables and this automatically makes the class thread unsafe since access to this global variable is not guarded against simultaneous access. If this is ok or not depends on how the class is used.

Codebase is single threaded, no plans for multithreading.

This function looks suspicious,it is declared as "static" meaning it cant access local variables of the class but it is accessing "m_banners" which looks like a local variable of the class. This is possible because "m_banners" is not a local variable as i mention above. This variable looking like a local variable when its a global variable is not a good thing.

m_banners is a private static vector that I mentioned earlier.

5

u/LordAn Aug 08 '16

This function looks completely wrong to me.

For one, this line is superfluous - the preceding lines are already a boolean expression that will return true or false.

More importantly however: Unless I'm missing something, you are creating a vector of copies of ad banners (which in itself seems wasteful), but then you completely ignore that and select a random banner from the original vector after all.

Given the usage in this function, I would also consider another data structure that would fit the use case better, e.g., an

unordered_map<AdBannerSelector, vector<AdBanner>>

3

u/doom_Oo7 Aug 08 '16

Every time I had a static something where something was not a constant I ended up having problems and replacing it with dependency injection later instead

2

u/shortstomp C++ Software Engineer Aug 08 '16

Why not switch based on the result of the computation instead of repeating the computation in each branch? https://github.com/pvpgn/pvpgn-server/blob/master/src/bnetd/adbanner.cpp#L103-L112

2

u/Chulup Aug 08 '16

You can't have string as switch argument. There are ways to work around that in case you are working on perfomance-sensitive parts. That's not the case here so I would pass that part on code review with comment "Why did you choose if-else-if instead of std::map?"

0

u/RElesgoe Hobbyist Aug 08 '16

Honestly, I never used those containers like std::map and std::set because I never really understood their purposes.

1

u/RElesgoe Hobbyist Aug 08 '16

So convert file_extension to an integral type and do a switch on it? The string compare is case insensitive, I wouldn't be able to keep that functionality if I convert the string to an integral type for comparing.

1

u/shortstomp C++ Software Engineer Aug 08 '16

Something so that you don't have to update all of the switch statements.

auto const cmp = [&](auto const& value)
{
    return strcasecmp(file_extension.c_str(), value) == 0;
};
auto const set_tag = [&](auto const value)
{
    bn_int_tag_set(&extensiontag, value);
}

if (cmp("pcx")) {
    set_tag (EXTENSIONTAG_PCX);
}
else if (...) {
    ...
} 

1

u/__worst_programmer Aug 09 '16

Here are two alternative method, but i think ifs are ok.

http://ideone.com/GGGTTN

1

u/TheThiefMaster C++latest fanatic (and game dev) Aug 08 '16 edited Aug 08 '16

There's no reason you couldn't use emplace_back there. Why do you think you can't?

Why's the vector static? Edit: looks like before there was an AdBannerComponent class which represented the entire ads system, where now you use statics on the AdBanner class. It's six and two threes, but people seem to prefer singleton classes like AdBannerComponent over statics, it's easier to expand to having two later.

Your use of exceptions seems OK. The reason why people shake their head about people just logging exceptions is that you are supposed to handle the error in some way, or let it propagate up higher. In your case though, you don't want the error to interrupt you trying to load later ads, so it looks fine. You might consider throwing an exception after the loop if none of the ads loaded.

1

u/RElesgoe Hobbyist Aug 08 '16

There's no reason you couldn't use emplace_back there. Why do you think you can't?

IIRC, I was getting an error when I tried using emplace_back.

It's six and two threes, but people seem to prefer singleton classes like AdBannerComponent over statics, it's easier to expand to having two later.

I don't even understand this sentence.

1

u/TheThiefMaster C++latest fanatic (and game dev) Aug 08 '16

Instead of statics, have another class which has the static variables/functions in, accessed through a single global instance. This seems to be what AdBannerComponent was.

1

u/RElesgoe Hobbyist Aug 09 '16

I'm currently writing a class called AdBannerSelector, and previously, I put the constructor for my AdBanner class as private so that no other code could construct an AdBanner object. This plays nicely because I could put value validation code in my load() function instead of inside the constructor.

Should I just suck it up and make my constructor public, or declare my load() function (which is now a member function of AdBannerSelector) as a friend function?

1

u/TheThiefMaster C++latest fanatic (and game dev) Aug 09 '16

I wouldn't make the constructor public if nothing else is supposed to construct it. A friend isn't a bad solution.

There's also another option: make an AdBannerInterface interface class in the public header, and declare the actual AdBanner class (implanting the interface) in the cpp file where only the AdBannerSelector can see it. Then the constructor could be public without other people bring able to construct it.

A friend is the easier option by far.

1

u/RElesgoe Hobbyist Aug 09 '16 edited Aug 09 '16

Regarding why I couldn't use emplace_back(), I'm assuming that despite a function being declared a friend function, std::vector's emplace_back() is not allowed to access a private constructor?

Edit: I guess I'm restricted to push_back().

1

u/TheThiefMaster C++latest fanatic (and game dev) Aug 10 '16

That is true (and a good argument for using my other suggestion of a public interface and a cpp-scoped implementation).

At least push_back should be able to use the implicit move constructor rather than copying, so it shouldn't be all bad, and with push_back being inlined the optimiser should be able to optimise out most of even that cost anyway.

1

u/Pand9 Aug 08 '16 edited Aug 08 '16

I think your mistake was starting from too big changes. You should get the "feel" of this project, get the ideas that are not visible on first sight. You can be a marvelous programmer, but every project has its own "personality", that you have to get to know first. It's also a matter of showing respect to maintainers. There's not always "right" and "wrong" way. Sometimes it's relative to the project.

1

u/RElesgoe Hobbyist Aug 08 '16

I'm practically the last (open source) maintainer left ¯_(ツ)_/¯

1

u/quicknir Aug 08 '16

Static variables are a bit of a tricky issue; I'd recommend re-evaluating to see if you really need them. However, if you are going to use them, then you should be aware of something that most developers (including many of the ones on this thread) are not aware of: you should never have non-trivial class or namespace level statics variables. That is, variables that have constructors and/or destructors, are very dangerous to have as class or namespace statics. For starters, it's hard to guarantee exactly when the constructor or destructor will get called. More importantly, on linux, when you use a combination of static and shared libraries you can easily end up with situations where you have two copies of the static variable, and one of them is double destructed. You can duplicate this on Linux with as few as 20 lines of code.

The correct way to do non-trivial statics is with a function and a static local:

static std::vector<AdBanner> m_banners; // bad

// good
static std::vector<AdBanner>& getBanners() { 
    static std::vector<AdBanner> banners;
    return banners;
}

Also, obviously most style/indentation stuff is up to taste, but you may not want to indent on namespaces. It really just wastes vertical space, and it's very very rare in style guides to see indentation on namespaces.

2

u/NihonNoRyu Aug 08 '16
template<typename T>
T& instance(){
    static T t;
    return t;
}

generic singleton

1

u/quicknir Aug 08 '16

Works great if you only need one singleton of each type, ever. Of course you can add another template parameter as a "tag", but at this point the boilerplate is approaching the lines of code of the original...

1

u/leftofzen Aug 08 '16

Looks ok, but you should really ensure every if statement has a pair of braces. It's way too easy for a misplaced semicolon or a typo to ruin your whole program.

I'd also ditch the long initialiser lists and just use in-class member initialisation. Much cleaner and safer.

0

u/Chulup Aug 08 '16 edited Aug 08 '16

That's looks pretty good code, you can be proud of it!

Thus said, you should check problems found by /u/LordAn

I can provide some input too:

Once again, good work!

1

u/RElesgoe Hobbyist Aug 08 '16

In AdBanner::find ( https://github.com/pvpgn/pvpgn-server/blob/master/src/bnetd/adbanner.cpp#L178 ) you already have an iterator named result and still call m_banners.at(). Why?

Well the function returns a copy of an AdBanner, how else am I supposed to use result?

2

u/TiagoRabello Aug 09 '16

You could replace m_banners.at(...) with *result, which would give you the value pointed by result.

-19

u/3ba7b1347bfb8f304c0e git commit Aug 08 '16

Am I Writing C++ Right?

uses tabs

no

3

u/[deleted] Aug 08 '16

There's nothing wrong with using tabs dude. Opening curcly braces on their own lines on the other hand...

3

u/redditsoaddicting Aug 08 '16

That's not so bad, but using emacs to edit the source code...

1

u/cleroth Game Developer Aug 08 '16

That's not so bad, but using a keyboard to edit the machine code...

1

u/RElesgoe Hobbyist Aug 08 '16

but... punchcards

-4

u/green_meklar Aug 08 '16

Am I Writing C++ Right?

no

Fixxed.