Showing posts with label Naming Conventions; Coding Standards. Show all posts
Showing posts with label Naming Conventions; Coding Standards. Show all posts

Thursday, 29 January 2015

C++ Alias rather than Typedef Example

I've been reading through Scott Meyers latest book, and one item I picked up on, which had passed by my eyes before; but I'd not noted, was the use of alias instead of typedef.

I used typedefs a lot in my code, to try and simplify things, well today I've created my first piece of code which would have used a typedef, but which I've used alias "using" statements for:

void ConsolePause(const unsigned int& p_Seconds,
const bool& p_Show = false,
const std::string& p_Legend = "")
{
if (p_Seconds > 0)
{
using Time = std::chrono::high_resolution_clock;
using MS = std::chrono::milliseconds;
using FSEC = std::chrono::duration<float>;
using TimePoint = std::chrono::system_clock::time_point;
using MSCount = long long;

TimePoint l_start = Time::now();
bool l_exit = false;
do
{
TimePoint l_end = Time::now();
FSEC l_duration = l_end - l_start;
MS l_durationValue = std::chrono::duration_cast<MS>(l_duration);
MSCount l_count = static_cast<MSCount>(std::round((l_durationValue.count() / 1000)));

if (l_count >= p_Seconds)
{
break;
}

if (p_Show )
{
std::setfill(' ');
std::setw(30);
std::cout << "\r" << l_count;
if (!p_Legend.empty())
{
std::cout << " " << p_Legend;
}
}
}
while (true);
}
}

The code counts down on the console for the set number of seconds.

I like this, I think it's neater than the typedef system, though when I first wrote one instead of "using NAME = TYPE;"  I actually did "using TYPE = NAME;" on sort of autopilot.

Code derived from answer here: 

Thursday, 3 April 2014

Code Line Numbers

I had a programmer sat with me the other day, he seems a good one too, though I've not seen his actual code.  And he surprised me by peering at my development environment and saying...

"How can you program without line numbers on?"

He was serious, we were exchanging information to ensure I wrote code to meet his coding standards... So why not program with line numbers... Well, I could be annoying and say, I don't write BASIC, so I don't need line numbers... I also don't count K-Locs as a form of reward as to how busy I've been, nor use it as a measure of how productive I am... So really I have to ask myself the opposite, "Why don't you program with line numbers on Xel?"

And the simple answer for me is experience.  Maybe you're different, and you like line numbers, if so "This is not the article you are looking for, move along... Move along"... But to answer for myself, it is simply because I'm human, and the human mind likes to see patterns, it likes to see things and tries it's hardest to impose some semblance of meaning into them.  And for me, if I turn line numbers on then I expect 5 to follow 4, and 4 to have followed 3, and 2 to have come before 3 but after 1... It's an order, and in modern code it is an incorrect order because we should be writing, if not object orientated, then at least functional code.

Functions can be called in any order, objects can be instantiated and used differently by different users, your code itself might do one sequence one way today but a different sequence tomorrow.  The functions themselves still do the same single job with the same input, as per their definition, but code as a whole is no longer linear.

So over time my personal experience has told me to group my code into a simple, but not formal - until this blog post - order, which is "Constructors at the top", then the functions defined "in order of frequency of use", so if you have an update function called all the time in a class, put it at the top, so its easy to spot after your constructors.  Especially in a language like C++ where your constructors can be very brief - or should be very brief, if they're not go rear Scott Meters & Bjarne Stroustrop on the topic!

And then functions are laid out in order of use, least used or single call functions are at the bottom.  I've just come to this pattern, its quite hard to even define it here in words, I suppose I should give code examples, but I'll leave this for another day and come full circle to answer the question "How can you program without line numbers on?"

"Code/Function use is not linear, don't give any indicates to your mind that it is, and if you're going to argue about the contents of one function, your function is too long, break it down into sub-functions which will fit onto the screen as a whole and so you don't need line numbers you can see the whole function in a single pass of the eye".

Wednesday, 19 March 2014

Why I don't like Lambda's (C++)

Why I don't like Lambda's (C++)
I think I'm going to be in the minority of programmers when I say that I don't like Lambda's, in case  you don't know, a Lambda is a piece of code you an run inline, so you can create it and run it where you're working... like this:

#include <iostream>

int main ()
{
int sum10 = []
{
int i = 0;
for (int k = 0; k < 10; ++k)
{
i += k;
}
return i;
}();
}

When the code here is compiled & run, the value entered into "sum10" is the result of the function which follows, traditionally we'd write this code like this:

#include <iostream>

int Sum10Function ();

int main ()
{
int sum10 = Sum10Function();
}

int Sum10Function ()
{
int i = 0; 
for (int l = 0; k < 10; ++k)
{
i += k;
}
return i;
}

You can see this "Sum10Function" is actually a function, it has a declaration and a definition.  And this is how I'd always prefer to do work with functions, I do not like Lambda's because they ignore the greatest power of functions like "Sum10Function".

And that power is having a known location, a location you can find and a location which one can easily find all references to, you know if you have a problem in the function that you have one body to find and you can find it easily.  Finding a Lambda, written inline, in a mass of source is not a boon, it is in fact a major headache.

Other authors on the topic, such as "Alex Allain" (http://www.cprogramming.com/c++11/c++11-lambda-closures.html) actually have the balls to intimate that the fact you can write the function inline like the lambda, without having to stop and go create a prototype and a body declaration is a strength, but he; like many others; totally ignores the elephant in the room and that is the maintainability of code.

Alex's other examples on that page also start to use function pointer or functor examples, the first "AddressBook" class example he gives is taking a type, and yes we can assign a lambda to a type "auto"... but we can also assign a function pointer to an "auto", so there's no difference in using a function pointer or using a lambda in that example, except the Lambda falls foul of my point, it's harder to find and manage the source for the function.

The article linked there is also one of the major references if one googles for Lambda's in C++.  And it has code examples, which work, but which he describes as "pretty good looking", but which I see as horrible... here's the examples, cleaned up in the same program:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
using namespace std;

vector<int> v;
v.push_back(1);
v.push_back(2);
//...
for (auto itr = v.begin(), end = v.end(); itr != end; itr++)
{
cout << *itr << endl;
}
vector<int> vw;
vw.push_back(1);
vw.push_back(2);
//...
for_each(vw.begin(), vw.end(), [](int val)
{
cout << val << endl;
});

return 1;
}

They both do the same thing, they output the vector, but I don't think the second code looks better, I in fact think both examples need cleaning up, because to my eye they're miss leading, but my argument about the maintainability of Lambda's aside the second example does hint at the only use for them.  It hints that they can take the loop variable "val" as an input from the left, i.e. from the iteration over the vector in the "for_each" loop, rather than need to declare that iterator as in the first loop "auto itr = v.begin()"...

But I would still argue that this ease of throwing the code in there, leads to hard to maintain code, I think the first example cleaned up would leave a much more wholesome and maintainable code base...

#include <iostream>
#include <vector>

int main()
{
using namespace std;
vector<int> v = { 1, 2 };
for (auto itr = v.begin(); itr != v.end; ++itr)
{
cout << (*itr) << endl;
}
}

And there is my preferred implementation of that example, I find it simpler and easier to understand, and as you can see I'm using the C++11 declaration of the vector contents to ease understanding, so I'm not throwing an anti C++11 rant here, far from it, I've looked at Lambda's in Python and C# as well as here in C++ and I really don't like the syntax maintenance questions they bring up.

Sometimes they look and can behave very powerfully, but even with the for_each example above, I'd still much prefer this:

#include <iostream>
#include <vector>
#include <algorithm>

void Output (int p_Value)
{
std::cout << p_Value << std::endl;
}

int main ()
{
std::vector<int> v = { 1, 2 };
for_each (v.begin(), v.end(), Output);
}

I can see the "for_each" I can see it calls Output with each iteration, that code clearly has a semi-colon, and I can go find "Output" very easily.  I find this code is much cleaner and simpler to follow.

Tuesday, 17 December 2013

Using the Singleton Pattern

We all know and love the singleton pattern, whereby you can ensure you only have one instantiated copy of a class, and can refer to that instance of the class at will?  Yes... Very useful for holding configuration if you're not totally familiar with the pattern.

In C++ we might have a singleton like this:

---- Singleton.hpp ----

#ifndef SINGLETON_CLASS
#define SINGLETON_CLASS

template <class C>
class Singleton
{

protected:
Singleton() {}
~Singleton() {}
private:
static C* s_Instance;
// Prevent copy
Singleton(Singleton&);
// Prevent assign
void operator=(Singleton&);

public:
inline static C& Instance()
{
if ( !s_Instance )
{
s_Instance = new C;
}
return *s_Instance;
}
inline static void DestroyInstance()
{
if ( s_Instance )
{
delete s_Instance;
s_Instance = NULL;
}
}
};

template <class C>
C* Singleton<C>::s_Instance = NULL;

#endif

----------

So this class gives us a basic singleton build into a class, so if we code:

-- Config.hpp --

#ifndef Config_CLASS
#define Config_CLASS

#include "Singleton.hpp"

#include <string>

// Forward declaration
class Config;

// Actual declaration
class Config : public Singleton<Config>
{
friend class Singleton<Config>;
private:
std::string m_Path;
/// Constructor is private
/// as the friend singleton
/// instantiates your class
/// with no params
Config ()
:
m_Path("C:\\HelloWorld")
{
}
public:
const std::string& Path()
{
return *m_Path;
}

};

#endif

-------------------

Nothing majorly wrong with this - I've not run this code through a compiler, to it just looks right and hopefully you get what I'm on about so far.

So our class derived from the singleton uses it, but each time we need to write a singleton we need to include this construction, and I've seen some people using macro's to replace that... so you might have:

#define SINGLETON_START (class_name) \
class class_name : public Singleton<class_name> \
{ \
friend class Singleton<class_name>;
And then:

#define SINGLETON_END() };

So forearmed we can now have our config look like this:

-- Config.hpp --

#ifndef Config_CLASS
#define Config_CLASS

#include "Singleton.hpp"

#include <string>

// Forward declaration
class Config;

SINGLETON_START(Config)
private:
std::string m_Path;
/// Constructor is private
/// as the friend singleton
/// instantiates your class
/// with no params
Config ()
:
m_Path("C:\\HelloWorld")
{
}
public:
const std::string& Path()
{
return *m_Path;
}

SINGLETON_END()

#endif

-------------------

Now, there's nothing wrong with this code-wise, its big crimes however are not obvious and in my opinion out way the benefit of using it.

So the benefits are the ease of declaring the inheritance and the friendship, it smooths that all out to a single line.

But the drawbacks, lets start with the plain text, code completion instantly breaks, it does not expand the Macro for the class definition.

Next, the physical act of using a Macro like this obfuscates away some code, and we're not talking about a trivial piece of maths we're talking about our class definition, so we instantly can't really use any of the decent document generators on our code, we could after using our own pre-processor to expand the macro ourselves, but its a real pain in the bum.

So this pattern is of use, and the macro can be of use, but using it is really a case of DO, or DO NOT... I'm on the DO NOT side, and I'll be adding this to my personal coding standards document soon.

Monday, 29 April 2013

Don't Interface just Encapsulate!

One of the major projects at my place of work came into my sphere of influence recently, and importantly it came to me with no restrictions on what I could do with it.  Unfortunately, so far, all I've been doing is sorting out horrible implementation and code weirdness.  Now, I can't go into specifics, my employer would not thank me, however, I can and intend to document one of the major problems.

This is a problem born out of the project developer - the guy who sat down and thought it up then set his fingers to the keyboard - being out of date, you see this chap has never had a formal introduction to object orientated programming.  He has a semi-idea of the uses of OOP, but he's never really put it into decent practice.

I always knew this, speaking to him at times I with an OOP eye would see things one very clear way, a clarion thought of how the structure of the class hierarchy would, and perhaps should, layout.  However, I would get a dull eyes stare back, something like a dog being shown a card trick.  I've used that statement on this blog before so I won't continue, what I will do is given an example of what I found and removed from one of the most major critical systems.

The system forms a set of classes, each have to contain the same flags and values as the others so they're mutable, but each is a different class.  So, say you have a "Person" and then you have "Staff", "Drivers" and "Servants" derived from them.. You could easily see these as objects.

What I was not expecting was a very strange use of interfaces... So, enough talk, some code, and this is C# folks... I'm sorry!


public interface Person
    {
        string Name
        {
            get;
            set;
        }

        int Age
        {
            get;
            set;
        }
    }

Given this, you can now implement this interface in other classes, and those classes will be forced to use define those elements... Right.  So, this code:

public class Driver : Person
    {
    }


Fails, with the messages: "Error 1 'Driver' does not implement interface member 'Person.Name'" and "Error 2 'Driver' does not implement interface member 'Person.Age'"... And I can see what the chap who wrote this was thinking... It went down something like this... "GREAT, Now everyone trying to use my Person interface is forced to define Name and Age"... And that is what Interfaces are for, but that's not what these classes are used like, what they need is to encapsulate a name and age which are already defined.

In the interface above each and every class has to define the function, but that means there's a copy of the same code being written over and over and over, that's useful if you need those overrides to define different behaviour, but this person class, just like the class in the software I was working on, are used for the same thing each and every time.... This makes repeating the code over and over wasteful, and hard to maintain.

What should have been done is encapsulation, the base class should provide the functionality and then the derived classes just  have it, they inherit it, the base class encapsulates the common functionality and then the derived classes don't have to worry, you've written one set of code for the equivalent of this interface and instead of rewriting it you just put the inherit into your derived class...

class Person
{
     private string m_Name;
     public string Name { get; set; }

     private int m_Age;
     public int Age { get; set; }
}

class Driver : Person
{
}

So, I showed this the chap in question, and  you know what he said... He got quite shirty in fact... "Well I can't stop people just creating instances of the "Person" class, that makes my derived classes pointless!"

Oh yeah buddy, let me show you the way...

class Person
{
     private string m_Name;
     public string Name { get; set; }

     private int m_Age;
     public int Age { get; set; }

     private Person () { }
}

class Driver : Person
{
}

With a private constructor now no-one can create the Person class itself - create private copy & move constructors too for good measure!

The silence which ensued was palpable, about twenty minutes later, after staring and staring the guy came back with this:

class A
{
    private string m_Value;
    public string Value { get; set; }

    private A () { }
}

class B : A
{
}

B bInstance = new B();

"Right, now I got that, but Value is undefined in B, I need it to have a default value"... I swear to you now, I stared past his left shoulder and just shivered as I did this for him:

class A
{
    private string m_Value = string.Empty;
    public string Value { get; set; }

    private A () { }
}

class B : A
{
}

B bInstance = new B();

"No no" he screamed with glee, giggling, "I mean a value so I know its a B!" or whatever, so I did this:

class A
{
    private string m_Value;
    public string Value { get; set; }

    protected A (string p_Value)
    {
        m_Value = p_Value;
    }
}

class B : A
{
    private static readonly string c_Name = "BValue";

    public B ()
       :
       base(c_Name)
    {
    }
}

The silence was all encompassing by now, and I left him to it.  I had by the end of my programming session - before I went for my afternoon break - created around 12 versions of his derived class from the new base and totally removed his interfaces which were so ugly.  I don't think he'll forgive me, but the code was a lot smaller and easier to read, and in my opinion more correct.

The only reason the chap did not get to the same conclusion as me was a lack of understanding of the object model & hierarchy, a professional programmer foxed by this, and a more senior programmer than me... Really makes me wonder why I'm earning so little!

Friday, 12 April 2013


Today I've been looking at a C++ problem, well when I say problem, I think there are no problems you can't work around in C++, but this particular problem relies on someone spotting a compiler error and acting correctly.

The trouble I have is that the compiler error is pretty obscure - this I will admit as a problem with C++ compilers in general - and that the error really has no meaning in the context of the solution I am trying to make the programmer come to.

Let me explain with a little code, I have a class a base class in fact, we'll call this A, and this class has a constant inside, lets say the "Name"... Now we don't want the base class to define a value for this constant we just want it to make all classes which derive from it realise they must define a value for this constant... So the code might look like this;

#include <string>

using namespace std;

class A
{
public:
static const string c_Name;
};

Now, normally here we'd then have:

const string A::c_Name ("DefaultValue");

And if we did nothing untoward would happen at this point, the derived classes could all use c_Name, just it would have only this default value, and the static instance of c_Name in one derived class would NOT be the same string as in another class, they are separate values... so there's no problems.

class B : public A
{
};

Now this derived class has a c_Name, but its "DefaultValue", so you would expect to just define a new instance:

const string B::c_Name ("New Value For Constant");

Unfortunately, this is totally wrong, because the new definition of the constant in B causes a redefinition of the constant in the base class, and multiple initization is not allowed.

So, we remove the default value...

#include <string>

using namespace std;

class A
{
public:
static const string c_Name;
};

//const string A::c_Name ("DefaultValue");

class B : public A
{
};

const string B::c_Name ("New Value For Constant");

And everything now compiles, there's no problem... Except that the base class does not provide a default name, so we're relying on the programmer to spot when they miss the definition of name and not assume they've got to define it in the base class and so stop our intended operation...

But the compiler error is horrible... lets take a look at it from Visual Studio 2010:

"error LNK2001: unresolved external symbol" and then the hell that is the output... 



The error makes sense, we've defined a static in the base class and not defined it anywhere, my problem is how do I educate a programmer - whom will most likely not read my documentation - to NOT define one in the base and so break hundreds of classes in the future - but know to define it in the class they just wrote and give it a meaningful name?

Monday, 7 January 2013

Python - Warning Lessons


Over the last fortnight I've been dabbling with Python, the seemingly ubiquitous language seeping into every nook and cranny not containing a dedicated C++ follower, like myself.

Its on the Pi, its behind a lot of research work and big companies, like Google (before they worked on Go - lots of their stuff was Python, and perhaps still is).

So, I took a look... Its a powerful language, I don't doubt, it reminds me very much of writing procedural Pascal form the mid 1990's, but most importantly it looks like psuedo code, other authors mention this (http://www.jayconrod.com/posts/37/a-simple-interpreter-from-scratch-in-python-part-1) and others even crow about the syntax and structure being so simple.  But I hate it.

It leaves so many stones unturned, so many open ends, and I have to say it makes me cringe.

In C++ one has to definiately define the article of the body of a class, for example:

class Alpha
{
private:
int m_Value;
};

Now, the value of Alpha can only be set by functions which are part of this class, it is totally private:

class Alpha
{
private:
int m_Value;
public:
Alpha (const int& p_Value)
: m_Value (p_Value)
{
}
};

We can all agree this is a powerful tool, it lets us change and range and control the use of variables in the class, it can make our code safe and remove bugs, also the type of m_Value is implicitly defined one can't define m_Value and then start to point values at m_value by mistake, the compiler tells you to go away, this in my opinion is correct programming, I agree there's a lot of overhead (if you let the compiler create all that code) but there are far less potential bugs.

In Python we can get the same class:

class Alpha:
    def __init__(self,p_Value):
        self.m_Value = p_Value

And I find this abhorrently dangerous, first off, I didn't have to create "m_Value" the interpreter simply saw the name and invented it, if I then use "m_value" or any typo the interpreter does not thing, Ah hang on I don't know what this value is, it thinks "Ah a new thing to work with" and creates said typo as a new value.  Debugging such things is an utter nightmare.

Then the syntax itself, its clean, though not neat the reliance on tabbing to define structure annoys me.  I already have a big bee in my bonnet about different indentation styles in the C language family, so to see indentation made a part of the language, white space defining function, is scarey as hell.

But, Python is out there, and its a language I don't know an aweful lot about, so I'm learning it, gradually on the side.  Just you guys and gals out there learning it be very wary of its pit falls!