PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Style

Adde posted a link to his(?) library and I took a look at it and wanted to comment on the coding style.

This is not a post polling everyone and their opinions, you're welcome to post if you have something constructive to say. If you use a style without understanding why, or without considering others that may improve your programming performance or skill, then please don't post. I don't want this to be a pissing contest, and neither do I care if every person in existance does it a different way.

Like what the other thread became, if all you have to say is "I use blah" don't bother, make a poll instead. Thanks.

Here is the same code:
Code:

namespace Pluto
{
Button::Button(Frog::DisplayDevice* display, const TCHAR* filename
,const int& button_width, const int& button_height) :
m_pDisplay(display)
, m_pButton(NULL)
, m_ButtonWidth(button_width)
, m_ButtonHeight(button_height)
, m_bIsDown(false)
, m_bState(false)
{
#if _WIN32_WCE
std::wstring fname = L"\\";
fname += std::wstring(filename);
m_pButton = Frog::LoadImage(m_pDisplay, fname.c_str());
#else
m_pButton = Frog::LoadImage(m_pDisplay, filename);
#endif
if (m_pButton == 0)
{
::MessageBox(0, _T("Unable to load button."), _T("Button Initialization Error:"), MB_OK);
}
}
Button::~Button()
{
delete m_pButton;
}
void Button::BlitSurface(const int& x, const int& y)
{
using namespace Frog;

// First, draw the button
if (m_bIsDown)
m_pDisplay->Blit(x, y, m_pButton, &Rect(m_ButtonWidth,0,2*m_ButtonWidth,m_ButtonHeight));
else
m_pDisplay->Blit(x, y, m_pButton, &Rect(0,0,m_ButtonWidth,m_ButtonHeight));

// Then, draw the border
m_pDisplay->DrawRect(x,y,x+m_ButtonWidth-1,y+m_ButtonHeight-1,Frog::Color(0,0,0));

// Finally, clear down flag
m_bIsDown = false;
}
void Button::PushDown()
{
// Flip/toggle state
m_bIsDown = true;
if (m_bState)
m_bState = false;
else
m_bState = true;
}
bool Button::GetState() const
{
return m_bState;
}


Its a fairly simple class, its just a button after all. But there is a problem, he is allocating memory in his constructor, so if the constructor fails, that memory is never freed, ie the destructor is not called.

Personally I view accessors as the interface of the class, so I use what you would assume to be normal variable names for the accessors, in this case it would simply be myButton->state().

I don't particularily care for the m_/m notation, at least at the beginning of the name, since its the first thing you read and impacts readability, I use a trailing _ since it does not affect readability. But the real problem to me is that this is a programmer constructed device, and there is no method in which to enforce it, this goes for comments and a number of other things. Comments become out of date, often. While I think doxygen is great for open source, I would never use that internally at a company or on my own code, because once they are out of date they are no longer useful and can actually be harmful. And without turning the code into a bulky behemoth there is no simple way to version the documentation, whereas a seperate document can. Not to mention on a real project you may have someone suited for technical documentation (who is paid to write it, so its gets written).


There is a consistency problem with the BlitSurface method, I don't often use "using" but he has within a method but still used Frog::Color, I would assume that isn't needed. I originally viewed using as a tool to help update C code and keep it running, so never use it myself. In addition why call that method BlitSurface, when Blit is more consistent with the parent class?


As a side note I despise Hungarian notation. And its unfortunate that is bled from C into C++ where it shouldn't be needed. And because of its very nature should be ignored, its another programmer construct that doesn't offer any verification, so may or may not be valid. In addition the class writer should know what he is doing when he is modifing a class, so type information with a variable name gives him a false sense of confidence, when the person should look at the class definition anyway. When writing a button class, if my state is down or up, I know this and need no notation.

This type notation advances to other sorts as you see in the above example, the overuse of the word button, in a button class. To me thats like saying the the. I know, and you know, that it a button class, so naturally by context I figure that a surface is the button's surface. And the width and height are the button's width and height. For instance I imagine seeing this sort of code using your button class "exitButton->GetButtonWidth()", whereas to me it would be much clearer like "exitButton->width()". This is less a consideration of style than design, in the first example I read the the word word button twice. The operative words are get and width, acting on the name I would be more familar with (since I am writing it) exitButton.
Ok.. Allow me to respond.

First of all, the objects in my project are far from flawless even by my standards. And there is a reason for this, time. This Button class (and it's successor ArrowButton) was whipped up really fast. That doesn't mean one should ignore style because that will only get you to do double work (at best). Might as well do it right the first time.

Ok.. a few comments.

he is allocating memory in his constructor, so if the constructor fails, that memory is never freed, ie the destructor is not called.

Normally I would agree with you, but in this case I don't. Maybee I lack some vital knowledge about constructors here, but why would this constructor fail? Memory is allocated by the LoadImage() function, and if that fails it doesn't allocate any memory (or so I would like to think since it returns a NULL pointer). If the constructor fails to allocate memory for the object, then the body of the constructor is never called and hence, not a problem. BUT, I do agree that in the destructor one should test to see if the surface m_pButton is not NULL before deleting it just to be safe.

Personally I view accessors as the interface of the class, so I use what you would assume to be normal variable names for the accessors, in this case it would simply be myButton->state().

Shure. I've seen this notation, and as with every other notation one could argue who's best. I've done a lot of Java coding, and in that world the Get/Set/Has/Is notation for object modifiers is very common. I adapted it to C++ after seeing that atleast some people use it (I think it was in one of those standard documents I posted on the other thread). Why I use GetX and not getX I can't motivate in any other way than that it gives an extra clue that this is in fact a function and not a data member.

I don't particularily care for the m_/m notation,

I didn't either at first, but after coding a few months with it it grew on me. It is a windows (MFC I think) standard so I figured I could adopt it since I'm writing windows code. And my motivation is that in a member function, it's easy to see what variables are data members, who is local and who is parameters (I'll get back to this one at the end).

I use a trailing _ since it does not affect readability.

And to me that looks stupid. But hey, maybe that's just me. I do agree that mVariableName affects readability, but I don't think m_VariableName does as much. As I said earlier, it's a matter of getting used to it (and this is true for almost any coding notation since they all have arguments for and against).

And without turning the code into a bulky behemoth there is no simple way to version the documentation, whereas a seperate document can.

I'm not even gonna try to get into the documentation part. If I work on a large company then I guess they have a policy standard for documentation (and coding for that matter) so.... I just wanted to point out that there is a great tool out there called Doxygen, and I bet that it would remain usefull atleast as long as your own project will. And it saves a lot of time when doing documentation and reference manuals, plus it ensures that the manual is up to date because the comments are tied to the code. Version info can be included, but I'm not going further into this hole. If you don't like Doxygen, that's fine with me.

I don't often use "using" but he has within a method but still used Frog::Color, I would assume that isn't needed

You are right. Thanks for noticing. This is a good example of a copy-paste error. I don't use the using namespace command everywhere. If the code is short, or if its made from many different namespaces I don't. As you might have noticed I put the using namespace within each function (where I find it useful to do so) unlike the PF Blit sample who makes a global using namespace Frog define for the whole file. If you're going to use the using command, then atleast use it as local as possible.

In addition why call that method BlitSurface, when Blit is more consistent with the parent class?

The parent class? Button is a standalone class and is itself the parent class for ArrowButton but that's a whole other story. Anyways, it is pretty obvious that it is a Surface that is being drawn/blitted so Blit would be better. I'm not shure but I think it has to do with some other object in my project where I found that BlitSurface was less confusing than Blit, and then all the other objects that enclosed a Frog::DisplayDevice object would use this style for consistency. One could also argue that since Button is not a Rasterizer or anything remotely alike, it should not have a functions called Blit since that could fool the user/client to think that Button is a rasterizer and has all the other functions aswell. But since the user is me, and I wrote the class this argument is kind of silly but never the less valid.

As a side note I despise Hungarian notation.

Yes, it must be used with care. I only use it for pointers and boolean types (and for consistency with some windows classes, like h for handle for example). And the reason for this is, believe it or not, readability. I find it helpful when debugging code if I don't have to keep track of which members are pointers and who're not. Also, when checking conditions it helps to know if a variable is boolean or integer. I know you are going to argue that one should always explicitly test for a value, but with the 'b' marking I don't have to and the code looks cleaner. I do test for value for non boolean values though and this might seem inconsistent but hey, that what I do ok =)

This type notation advances to other sorts as you see in the above example, the overuse of the word button, in a button class.

What I'm about to say might seem strange and inconsistent to you but I totally agree. It's funny you should pick this class as an example but that's good, because then this can be discussed. Methods and data members (Functions and variables) of a class (in this case Button) should NOT include the name Button unless it is to resolve a name clash or when it is not 100% clear what it does. In this case it is and hence I should remove all the Button stuff. Like I said before I wrote this class really fast and I think I had some grand illusion of a bigger more general class design where it was motivated to use ButtonWidh instead of just Width. Thats my only defence. Normally I don't reuse the object name in methods and data members.

And while we're on the subject I might as well point out a few faults in this code that I recently changed my opinion about.

Local variables should be all lowercase and word separated by '_'. BUT, function parameters should start with a lowercase and be word separated by a capital letter. This way it's easy to see what variables comes from where.. m_ is part of the object/class, first_second is local and firstSecond is supplied from the outside world. Global variables should not be used at all.

The PushDown function could return the new state. Perhapps this would be useful in some other project. It's a flaw not to make a class as general as it could be, but time is always a factor.

And then there is all the stuff you should build in but don't since it takes a lot of time. Like writing a proper copy constructor for the object or deny the user/client access to it to prevent unlawful usage. Again, since I'm the user and writer of the class this is not a problem for my project. But in general, it is.

Pew.. this must be a new record for long notes. Sorry about that.
adde wrote:
Maybee I lack some vital knowledge about constructors here, but why would this constructor fail? Memory is allocated by the LoadImage() function, and if that fails it doesn't allocate any memory (or so I would like to think since it returns a NULL pointer).


I think I read that in one of the Scott Myer's books, or some other C++ gotchas sort of thing. There are other problems with that, if the Load does fail, then what can you do? Maybe exceptions could save it, but not on ppc yet.



BUT, I do agree that in the destructor one should test to see if the surface m_pButton is not NULL before deleting it just to be safe.


Well if you prefer it for some style reason, but C++ doesn't require it.



"trailing _ "

And to me that looks stupid. But hey, maybe that's just me. I do agree that mVariableName affects readability, but I don't think m_VariableName
[/quote]

I agree it looks stupid, but so does m_, all of it just screams language flaw to me.


In either version (m, m_), the first thing you see is m_, so the m_ synapses in your brain are strengthened each time you read a variable. To me this is like mental pollution. In other words your brain thinks "member" first, then "VariableName". As for the _, I don't like it much better but it doesn't purposely distract me from what the variable has been named. I use it *only* when I have to, which is generally rare since code such as this works fine:
Code:

void Button::setWidth(int width, int height)
{
this->width = width;
this->height = height;
}


Coming from Java you may appreciate that.

The only conflict, and one I wish they would fix, is method names and data. I couldn't use the above in a class where the accessors were width() and height(). There is no way I know of to get around that one.



I know you are going to argue that one should always explicitly test for a value, but with the 'b' marking I don't have to and the code looks cleaner. I do test for value for non boolean values though and this might seem inconsistent but hey, that what I do ok =)


I came to C++ with lengthy C experience, I am at one with zero and have no qualms about not testing against a value. As far as I can see, not testing a value saves you from the ever present assignment in expression bug. In other words I never test against zero (!=, ==), this goes for bool, int, pointer, enum or whatever.

It should be an idiom in any shop, bool or not. I'm surpised to hear you speak of concern over the matter, I didn't read all the links you posted, did any of them admonish doing that?
if the Load does fail, then what can you do?

True, and this has been bugging me. To get around it, I could have implemented a LoadImage function and then tested its return value and take appropriate actions.

Well if you prefer it for some style reason, but C++ doesn't require it.

You are right. My bad. C++ will just ignore trying to delete a NULL pointer.

Coming from Java you may appreciate that.

Yes, this is exactly the way I wrote my code before.

The only conflict, and one I wish they would fix, is method names and data. I couldn't use the above in a class where the accessors were width() and height(). There is no way I know of to get around that one.

Since this would be very error prone I wouldn't wish for it. One way to get around it is to adapt the 'classes and functions begin with a capital letter' style because C++ is case-sensitive.

As far as I can see, not testing a value saves you from the ever present assignment in expression bug.

Which is why most of the standards recommend that you test the other way around, for instance
Code:
if (1 == value)
{ /* do something */ }
if (1 = value) // assignment error caught at compile time
{ /* do something */ }


didn't read all the links you posted, did any of them admonish doing that?

As a matter of fact, one did and here's a quote:
C++ Coding Standard wrote:The non-zero test is often defaulted for predicates and other functions or expressions which meet the following restrictions:

* Returns 0 for false, nothing else.
* Is named so that the meaning of (say) a true return is absolutely obvious. Call a predicate IsValid(), not CheckValid().
adde wrote:
Since this would be very error prone I wouldn't wish for it. One way to get around it is to adapt the 'classes and functions begin with a capital letter' style because C++ is case-sensitive.


Why do you think it would be error prone? I typically use the caps thing for a class.


Which is why most of the standards recommend that you test the other way around, for instance

Code:

if (1 == value)
{ /* do something */ }


That to me is a bit extreme, ok these bugs happen every so often, but the fix in this case is worse than the cure. Besides that this isn't such an issue as it once was, because it is not difficult for a compiler to see an assignment and warn about it. VC++ does this.
Why do you think it would be error prone?

As with everything else, as long as you are consistent there won't be any errors. A lot of the recommendations in various standards are redundant, in the sence that you could manage with just a few as long as you are consistent. Having more is just a way of increasing security and alowing many people to unite their code on a larger project (havn't been in one yet so I wouldn't know, but it sounds fair).

But, there is always a trade off between readability and productivity. Mostly, the readability factor is a matter of getting used to a perticular style. As I said earlier I didn't understand the m_ style at first either and I'm not saying THAT'S THE WAY YOU HAVE TO DO, I'm just saying that's the way I do when writing C++ code for windows systems. This goes for the everlasting debate about braces at the end of the function line or alone on the next. I tend to use different styles for different languages, where I adopt the most common style for that particular language (and modify it as I see fit).

Productivity is yet another factor. There is no point in putting to much effort into writing everything as perfect as you can. Better to write the stuff you actually need as perfect as you can instead. But tracing faults made from beeing inconsistent or using a bad standard doesn't help productivity either =)

Besides that this isn't such an issue as it once was, because it is not difficult for a compiler to see an assignment and warn about it. VC++ does this.

So true. But you asked and I answered.
m_ is a standard MFC thing. (along w/ CClassName and other stupid conventions). I hold to it, however, b/c you cannot have an inst var named "abcdefg" AND an inst method "abcdefg()" (in C++). i have forsaken get and set prefixes in my Java code and naturally do the same in C++. so i use m_. after writting MFC C++ code for years, it is hardly confusing. caps methods are gross! of course that comes from my Java experience, as does my view that you should assume that the language works. (ive seen C++ programmers assert(this); in inst methods. how can you assume that assert works if you cant assume that you exist?)

BTW: Hungarian notation is useless, if you use precise naming it will be pretty obvious what sort of var it is. MSVC++ (and eVC++ for that matter) is generally pretty helpful in this regard (esp when debugging)