Is there a way to writes Reuseable code(Traits) like PHP or Javascript in Coldfusion
As this seems to be a great idea of writing Traits and using in Different Classes where they are needed.
I looked at: http://php.net/manual/en/language.oop5.traits.php
And I found the following PHP code to be interesting:
<?php
trait A {
public function smallTalk() {
echo 'a';
}
public function bigTalk() {
echo 'A';
}
}
trait B {
public function smallTalk() {
echo 'b';
}
public function bigTalk() {
echo 'B';
}
}
class Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
}
}
class Aliased_Talker {
use A, B {
B::smallTalk insteadof A;
A::bigTalk insteadof B;
B::bigTalk as talk;
}
}
?>
My take on things like this.
CFML is different from other programming languages in that it has lots of built-in functions. I use objects all the time. The objects I use are application.cfc, FW/1 Controllers, DI/1 / FW/1 Services, DI/1 / FW/1 Beans, and ORM back objects.
Each and every one of these has a built in set of expectations and usages. None of them are plain objects. It has been a long time since I wrote a plain object. I would much rather use a more feature rich object.
CFML also has member functions on its variables. This makes them similar objects.
Last but not least, If I really had to pull in functionality from multiple locations, I would just create an instance of an object inside of another.
Disclaimer: I currently work on an application with about fifty cfc and hundreds of functions. All of them are needed but some refactoring might be useful.
I could see one or two places where traits might helpful, but I can think of other things to do first.
Related
I want to use Google test to test my class.
Lets assume I have a state machine implementation and the current state is private
so I have a method SetNextState that looks like that:
void setNextState
{
switch(m_currentState) //m_currentState is a private member
{
case INIT_STATE:
{
if some conditions occurred m_currentState=GO_STATE
}
......
}
}
so I have several cases and each define the behavior to move from certain state to another.
My question:
How do I perform tests on that method assuming the state is relevant only to this class so there is no output
How do I set its value to be, for example "GO_STATE" to test the GO_STATE case
and how do i check the m_currentState at the end of the test
Im trying to avoid putting friends etc. in my UUT code since I want it to be as original as possible
You don't. You do the same thing that your actual program will do, which is provide an input, then examine the result; you say there's no output, but there must be some effect, otherwise the class is pointless!
Failing that, you could make the test a "friend" of the class so that it can inspect its internals, or add an immutable getter for the current state (and who really cares if your class's users get to see that?) but neither option is really in the spirit of the thing.
In my experience, you'll occasionally realise that you're not really unit testing any more but instead functional testing, and Google Test may not be the right tool for that job. If your class is as big as it sounds, that could be the case here. Conversely, you could help yourself by splitting the class into smaller chunks, then unit testing those. Depends what you're going for, really.
Lightness Races in Orbit is correct. However, if sometimes you feel like it's useful to test the private member functions of your class, it often means that your class could be split in multiple smaller pieces.
If you don't think those smaller components are useful to the clients of your library, you can simply hide them in a detail:: namespace and then create unit tests as usual. This will allow you to test the internal behavior of your classes without polluting your public API.
After much considerations I decided to wrap my UUT with a helper which provides set and get to the relevant private members.and use it in the test procedure before calling the tested API
Original code
===============
class UUT //That's the actual class I want to test
{
protected:
int m_protectedMember;
public:
void methodToTest()
{
//Do something with m_protectedMember use its value as input
//and set it as output
}
};
In the tester
==============
class UUTHelper: public UUT
{
public:
int getProtectedMember() { return m_protectedMember; }
void setProtectedMember(int value) { m_protectedMember = value; }
};
The pros:
My test code is very simple and I easily create complicated scenarios .
I test the real code without any "friends" or any other manipulations.
The cons:
As written in the discussion, not the best "good practice", touching private members
Thank you all :)
I'm attempting to help design some unit tests around controllers in a Qt C++ application.
To be frank, I have two large drawbacks. One, my testing background is heavily based on .NET projects, so my knowledge of best practice in the c++ world is slim at best. Two, the designer of the application I am looking at did not architect the code with unit testing in mind.
One specific point point, I'm looking at a controller class that includes boost/filesystem/operations.hpp. The controller constructor goes on to check directory existence and create directories using functions from the boost filesystem code.
Is there any way to overload or mock this behavior? I'm used to setting up an IoC container or at least dependency injected constructors in .NET, and then being able to pass mock objects in the unit test code. I'm not sure how a templated header file would work with that concept, though, or if it is even typical practice in c++.
Currently, I have no flexibility to suggest code changes, as there is a release build coming up this week. But after that, if there are some simple code changes that could improve testability, that is definitely an option. Ideally, there would be a way to overload the filesystem functions in the unit test framework as is, though.
We ended up creating a generic file system wrapper that calls Boost filesystem and accepting it as a parameter to our class constructors so we could send in mock versions at unit test time.
I understand the thought to not mock this, but I think there is value in fast unit tests for our CI environment to run at check in time as well as tests that actually hit the file system.
If you think about it, the only reason why you need to inject an instance of, suppose, IFilesystem into your classes, is to mock it in tests. No part of your non-test codebase gonna use anything but the real filesystem anyway, so it is safe to assume that you can inject not an object but a type into your classes and use them freely within your codebase without type clashes.
So, suppose you have class of interest
struct BuildTree
{
BuildTree(std::string_view dirname) { /*...*/ }
bool has_changed()
{
// iterates through files in directory
// recurs into directories
// checks the modification date against lastModified_
// uses boost::filesystem::last_write_time(), etc.
}
private:
boost::filesystem::file_time_type lastModified_;
};
Now, you could inject a type into the class. This type will be a class with a bunch of static methods. There will be a RealFilesystem type that will redirect to the boost::filesystem methods, and there will be a SpyFilesystem.
template <class Filesystem>
struct BuildTree
{
// ...
bool has_changed()
{
// uses Filesystem::last_write_time(), etc.
}
private:
typename Filesystem::file_time_type lastModified_;
};
The SpyFilesystem will resemble a PIMPL idiom, in that the static methods will redirect calls to the actual implementation.
struct SpyFilesystemImpl;
struct SpyFilesystem
{
using file_time_type = typename SpyFilesystemImpl::file_time_type;
static file_time_type last_time_write(std::string_view filename)
{
return instance.last_time_write(filename);
}
// ... more methods
static SpyFilesystemImpl instance;
};
SpyFilesystemImpl SpyFilesystem::instance{};
// No warranty of completeness provided
struct SpyFilesystemImpl
{
using file_time_type = std::chrono::system_clock::time_point;
void create_directory(std::string_view path) { /*...*/ }
void touch(std::string_view filename)
{
++lastModified_[filename];
}
file_time_type last_time_write(std::string_view filename)
{
return std::chrono::system_clock::time_point{lastModified_[filename]};
}
private:
std::unordered_map<std::string, std::chrono::seconds> lastModified_;
};
Finally, inside each of your tests you would prepare an instance of SpyFilesystemImpl, assign it to the SpyFilesystem::instance and then instantiate your class with SpyFilesystem. like so
// ... our SpyFilesystem and friends ...
// Google Test framework
TEST(BuildTree, PickUpChanges)
{
SpyFilesystemImpl fs{};
fs.create_directory("foo");
fs.touch("foo/bar.txt");
SpyFilesystem::instance = fs;
BuildTree<SpyFilesystem> tree("foo");
EXPECT_FALSE(tree.has_changed());
SpyFilesystem::instance.touch("foo/bar.txt");
EXPECT_TRUE(tree.has_changed());
}
This approach has an advantage that there will be no run-time overhead in the resulting binary (provided that optimizations are enabled). However, it requires more boilerplate code, which might be a problem.
It seems reasonable to me to consider boost::filesystem as an
extension of the standard libraries. So you mock it (or not) in
exactly the same way you mock something like std::istream.
(Generally, of course, you don't mock it, but rather your test
framework provides the necessary environment: the files you need
to read with std::istream, the directories, etc. for
boost::filesystem.)
I am working on a project which was mostly implemented using factory and facade patterns. However I am unable to understand as I do not have a clear concepts of how factory pattern works in C++. Can anybody suggest good sample program or link for the same.
Thanks
krissam
A good website for all design pattern queries is
Hudson Design Patterns
It pretty much has all GOF design patterns in it, but explains it in a way which is quite easy to understand. Also includes demos.
Wikipedia has a factory pattern page.
For simple cases there really is no trick. Just
Foo* createFoo() {
return new Foo();
}
It gets trickier when you want to do more than just use new. One good example is if the constructor takes a number of parameters, or if the objects need to be initialized somehow. In that case you can load up the factory with the requirements and not make the developer worry about them:
class BarFactory {
BarFactory(Dep* x, Depen* y) ...
getBar() {
return new Bar(x->SOME_METHODS, y->SOMETHINGELSE, ...);
}
}
In that example the the factory takes the confusion out of correctly making a Bar object, (imagine it took more arguments and they needed a lot of hand holding). This can be helpful when you've got an API with a lot of options that don't change or just a bad API.
The factory pattern works in all languages the same.
class NodeFactory {
SimpleNode createSimple() { return new SimpleNode(); }
ComplexNode createComplexNode() { return new ComplexNode(); }
};
A factory is just a class that has methods which create objects.
Angelo
Is there a way to implement functionality like Class Categories (of Objective-C) or Extension Methods (of C# 3.0) in C and/or C++?
C++ has free functions, but sometimes extension methods work better when you nest many functions together. Take a look at this C# code:
var r = numbers.Where(x => x > 2).Select(x => x * x);
If we write this in C++ using free function it would look like this:
auto r = select(where(numbers, [](int x) { return x > 2; }), [](int x) { return x * x; });
Not only is this difficult to read, but it is difficult to write. The common way to solve this is to create what is called a pipable function. These functions are created by overloading the | pipe operator(which is just really the or operator). So the code above could be written like this:
auto r = numbers | where([](int x) { return x > 2; }) | select([](int x) { return x * x; });
Which is much easier to read and write. Many libraries use pipable function for ranges, but it could be expanded to other classes as well. Boost uses it in their range library, pstade oven uses it, and also this C++ linq library uses it as well.
If you would like to write your own pipable function, boost explain how to do that here. Other libraries, however, provide function adaptors to make it easier. Pstade egg has a pipable adaptor, and linq provides the range_extension adaptor to create a pipable function for ranges as least.
Using linq, you first just create your function as a function object like this:
struct contains_t
{
template<class Range, class T>
bool operator()(Range && r, T && x) const
{ return (r | linq::find(x)) != boost::end(r); };
};
Then you initialize the function using static initialization like this:
range_extension<contains_t> contains = {};
Then you can use your pipable function like this:
if (numbers | contains(5)) printf("We have a 5");
Not really. It's not the C++ way to treat classes like this.
Amongst others, Meyers argue that it's best to have a small class with the minimal set of operations that make it fully useful. If you want to expand the feature set, you may add an utility namespace (e.g. namespace ClassUtil) that contains non-member utility functions that operate on that minimal class. It's easy to add functions to a namespace from anywhere.
You can check a discussion on the subject here.
C++ doesn't have sealed classes or single class inheritance, so in most cases you can subclass the base class. There are creative ways to make a class non-inheritable, but they are few and far in between. In general, C++ doesn't have the problems C# does that gave birth to extension methods.
C is not Object Orientated, so the question doesn't really apply.
With regard to C#'s extension methods: Not directly. C++ has less need for these things because C++ supports free functions. I've never used Objective-C so I can't comment there.
Can you use an interface? Extension methods are an easy way to avoid subclassing, but they are rendered semi-useless when proper OO techniques are used. The reason that they are used with Linq so much is so that the VS team did not have to go and update code that would most likely break a lot of legacy applications.
Per MSDN:
"In general, we recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type."
http://msdn.microsoft.com/en-us/library/bb383977.aspx
I've been playing around with Moose, getting a feel for it. I'd like an example of pure virtual functions like in C++ but in Moose parlance (specifically in a C++-looking way). I know that even with Moose imposing a stricter model than normal Perl, there's still more than one way to do what I'm asking (via method modifiers or SUPER:: calls). That is why I'm asking specifically for an implementation resembling C++ as much as possible. As for the "why?" of this restriction? Mostly curiosity, but also planning to port some C++ code to Perl with Moose in a way that C++-centric people could mostly identify with.
I can think of this way using roles instead of subclassing:
{
package AbstractRole;
use Moose::Role;
requires 'stuff';
}
{
package Real;
use Moose;
with 'AbstractRole';
}
This will give a compilation error because Real doesn't have stuff defined.
Adding stuff method to Real will now make it work:
{
package Real;
use Moose;
with 'AbstractRole';
sub stuff { print "Using child function!\n" }
}
You might also want to take a look at Jesse Luehrs'
MooseX::ABC.
It seems very similar to some of the implementations here. From the synopsis:
package Shape;
use Moose;
use MooseX::ABC;
requires 'draw';
package Circle;
use Moose;
extends 'Shape';
sub draw {
# stuff
}
my $shape = Shape->new; # dies
my $circle = Circle->new; # succeeds
package Square;
use Moose;
extends 'Shape'; # dies, since draw is unimplemented
I know that Jesse is a C++ programmer during the day.
It appears I can't do exactly what I want with Moose, but I can come very close with Roles. Here is the information from the Moose manual entry for Roles:
Roles Versus Abstract Base Classes
If you are familiar with the concept
of abstract base classes in other
languages, you may be tempted to use
roles in the same way.
You can define an "interface-only"
role, one that contains just a list of
required methods.
However, any class which consumes this
role must implement all of the
required methods, either directly or
through inheritance from a parent. You
cannot delay the method requirement
check so that they can be implemented
by future subclasses.
Because the role defines the required
methods directly, adding a base class
to the mix would not achieve anything.
We recommend that you simply consume
the interface role in each class which
implements that interface.
Here is was my attempt (without Roles, for information on Roles see the other answers):
package Abstract;
use Moose;
sub stuff;
package Real;
use Moose;
extends 'Abstract';
override 'stuff' => sub { print "Using child function!\n"; }