What C++ refactorings do you use in practice? [closed] - c++

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm going to create the comparison table of existing automated C++ refactoring tools as well as explore an ability of creation of such tool, free and open-source.
My question is: what refactorings do you really use in your everyday work? There are obvious things like renaming variable/class/method, but is there something specific for C++, like dealing with templates, STL, copy constructors, initializers, etc., etc?
I'm interested in building of realistic picture of all that little problems that C++ developer is facing each day in his coding and that could be automated at least in theory. I'm talking to my colleagues but that's probably not enough.
Thanks in advance.

It is pretty clear from the answers that few C++ programmers have ever seen a real refactoring tool. Yes, they are quite rare and highly specific to the IDE you use. That's inevitable, there is otherwise no good way to find out what source code files contribute code to the final executable. The preprocessor makes it extra challenging, you need to know the macro values. A source code parser is required but not enough.
Visual Assist for VS is one I know of.

As you said there are obvious things:
renaming is one
altering a function signature is another (especially since a function is almost necessarily duplicated: declaration in the header and implementation in the source)
renaming / moving a file (update of include directives)
Note that though it's basic, it's rarely well dealt with. My primary complaint being that comments are generally not updated (I am so not speaking about doxygen auto-generated useless clutter). So if I was describing the use of the class within a header, or the justification of using this class in another source file, the comment is now obsolete because by renaming the class no one will now know what it refers to...
There are however much more interesting cases:
When changing a function signature, you need to update all the call sites, the developer will need help for localizing them
With inheritance, the ability to act on all classes of a hierarchy: changing a function signature (once again) or adding/removing a virtual override.
With template: the Concept proposal having been dropped, it would be good if you could synthetise the requirements on the type passed (methods / inner types necessary) so that when altering those requirements (by modifying the template definition) one gets notified of the list of classes that are in use by this template and no longer conform to it (and shall be updated). Note that in case it's just renaming the type / method, you might want to automatically propagate the change, as long as it doesn't break anything else.
Good luck...

Take a look in Martin Fowler's Refactoring: Improving the Design of Existing Code and Refactoring to Patterns by Joshua Kerievsky. These in turn reference the GoF Design Patterns book so get that too.
If you can beyond the basic Rename Feature and Extract Function then you might be onto a winner.

Here's a C++ design pattern I came up with yesterday: Ditch inheritance in favor of policies.

One refactoring that I wish was supported is actually inject method. More-or-less the opposite of extract method.
Because perhaps I see that I can then rearrange the resulting code to better clarity or effect; but I am not aware that there is tool support for this at present.

Hi i use http://www.devexpress.com/Products/Visual_Studio_Add-in/RefactorCPP/ with this tool i do renaming variable/class/method, changing function body,initializers

Related

C++ events/messages system [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I need to IMPLEMENT(not to use some library/open source) an event/message system.
I have the following restrictions:
It must be fast. It will be use for games and speed is the main restriction. I think I can't create/delete message/event classes every time a new message/event is sent even if I use custom allocators for that.
I must be able to predict when a messages/event sent/created will be received.
It must be easy to use. Doesn't matter how complicated the implementations of the system will be, the programmer that uses it must have an easy to use interface.
I will prefer to avoid giant switches like on Windows messages, but I also want to avoid overriding a class for only one function - the event handler or something like this. I think something like the MFC style would be nice.
It must be able to handle lots (maybe 1000/frame at 60 frames/second, don't know exactly this) of messages/events without performance issues.
It can't use compilers hacks that are not available on other platforms. It must be portable. I will use C++ for implementation.
Any architecture/design/link/book that you think is suitable for/might help this would be highly appreciated. Thanks!
Let me address your points one by one:
It must be fast. It will be use for games and speed is the main
restriction. I think I can't
create/delete message/event classes
every time a new message/event is sent
even if I use custom allocators for
that.
It would suffice and perhaps be even more efficient (it was for me in one project) to reuse and refill existing messages. No need for a custom allocator.
I must be able to predict when a
messages/event sent/created will be
received.
You can make predictions but normal networks (you want portability) will make your predictions sometimes a bit off and sometimes way off.
It must be easy to use. Doesn't matter
how complicated will be the
implementations of the system, the
programmer that uses it must have an
easy to use interface.
That should be possible, albeit this could cost you some extra effort. Error handling and special cases (platform, networking) come to mind.
I will prefer to avoid giant switches
like on Windows messages, but I also
want to avoid overriding a class for
only one function - the event handler
or something like this. I think
something like the MFC style would be
nice.
Avoiding manually written giant switches is a thing I 100% subscribe to.
It must be able to handle lots (maybe
1000/frame at 60 frames/second, don't
know exactly this) of messages/events
without performance issues.
If you take care during implementation, you should only be bounded by the network.
It can't use compilers hacks that are
not available on other platforms. It
must be portable. I will use C++ for
implementation.
Not even C++ is available on all platforms. Could you please list the platforms you are addressing?

Reasons for refactoring tools for C/C++ to be so limited [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
What is the problem that no industrial level refactoring tool for C/C++ have been created, I only need a tool that "just works"?
What I mean by "industrial level" is a quality provided by JetBrains products (IntelliJ, ReSharper), or above. Any available solutions (including Visual Assist from Tomato Software or Eclipse CDT) are not mature enough.
Below are advantages for a start-up to drive such a project.
alleviation of C++ boring syntax (making development more fun);
C++ is evolving (0x version is coming hence a lot of work for such tool implementers);
marketing niche is broader than anything else (a lot of written C++ code, a lot of active C++ projects), even taking into account Web (HTML/JavaScript) projects;
C++ is chosen for system problems where each bug found by tool at compile time is a survival (a lot of corporations or governments should be interested in);
such tool can decrease project compilation time;
The only drawback is technical challenges... but looking at what Google, Microsoft, Intel, etc. are doing, there should be no unsolvable technical problems.
Lets summarize:
it is possible to implement such product
it is enormously profitable
it doesn't exist
No one wants make a profit? Collusion ;) ? Whats is the reason?
Let's consider just one basic refactoring: Rename function
The implementation appears very simple. Find all references, and replace the identifier used.
It gets a little more complicated with virtual functions. Now it's necessary to find the base declaration (and implementation, if not abstract), and references may be to any derived implementation in the class hierarchy. Much more difficult, but still feasible, because the group of functions to be renamed is well-defined.
That's the complexity that applies to languages like C# and Java. Now comes the kicker: C++ templates are duck typed. The set of implementations in the class hierarchy is no longer well-defined, because it could include ANY function with the same name and possibly compatible parameters. You did remember about Koenig lookup, right?
Trying to separate the list of functions which must have the same name, because they started out in the same overload resolution set, from those truly independent, would be an absolute nightmare. At this point you might as well just do a textual search-and-replace.
So let's go down your list of claims/desires:
"alleviate boring syntax". This is just trolling and means nothing in any technical sense. If the tool doesn't input and output C++ syntax, it's not a C++ refactoring tool.
"C++ is evolving". This means that such a tool would need to be maintained at considerable expense to keep up. It also means that a well-maintained tool would easily steal market share from older stable tools. And it means that any tool needs a ton of user configuration -- you don't want to generate C++0x-isms on a C++03 codebase after all -- so users will have to use the tool an awful lot to win back the time spent configuring.
"Each bug is a survival"? Not sure exactly what this grammatically nonsensical statement means, but perhaps it means zero bug tolerance? But that's best achieved by maintaining stability (the antithesis of automated refactoring that touches multiple files), solid architecture and documentation (which a refactoring tool won't automatically update, or do you want that too?), massive test suites, and static analysis. In fact, refactoring makes the massive test suites even more important, if that's possible, in order to verify that the tool didn't break anything. Note that automated static analysis faces some of the same challenges as refactoring, but since it doesn't change the code it can and does work on post-preprocessed code and/or compiler ASTs.
"decrease compilation time"? This is an unsupported claim in serious need of some evidence or at least solid reasoning. Are you expecting a refactoring tool to introduce pimpl for compilation firewalling? None of the C# and Java-style refactorings will reduce C++ compile time one whit.
"it is possible" No, actually it seems like it isn't. If you or I can't design one basic refactoring like Rename function in a sane manner, never mind implement it correctly, how can anyone implement dozens of them? If it is possible, it's also assuredly extremely expensive, which leads to:
"it is enormously profitable". Profitability requires not only a large base of users who are willing to pay for a product, but that the potential gross sales exceeds the costs. I claim you have seriously underestimated the costs so until you provide some real research on costs and markets I'll call this one wishful thinking as well.
"it doesn't exist". After going to some length to explain why such a tool can't exist, I'm now going to tell you that it already does? Yup. At least insofar as refactoring makes the final code better by doing things like hoisting common subexpressions outside loops, unrolling loops, exchanging order of iteration, inlining, cache optimization, vectorization, they are already provided by optimizing compilers, an area in which C++ leads both C# and Java by a wide-margin. C++ simply doesn't require many of the source-level tweaks needed in C# and Java in order to get a good final product. It's only the manipulation of source code to make it more accessible to humans that remains, and the existing tools do an adequate if not exception job of this.
This link talks about some details and complexity involved
The reason is that C++ is not parseable by most common parsing techniques (LALR, LL, etc.) and actually requires some pretty heavy lifting to properly parse. Some tools like clang and gcc-xml make it possible for other tools to process C++ without implementing their own C++ parsers, although both are fairly new, and it can still be complicated to process C++ even with these parsing tools. I think that the industry will eventually see all the Java-related goodies ported/adapted to C++ ... the question is when.
The problem is that C++ is hard to parse (its grammar is not context free) and hard to make any sense of without actually compiling the source. Java tools can work because the language is a lot simpler, both grammar and semantics.

Object-oriented programming [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I am developing a project in C++. I realised that my program is not OO.
I have a main.cpp, and several headers for different purposes. Each header is basically a collection of related functions with some global variables to retain data. I also have a windowing.h for managing windows. This contains the winMain() and winProc(). It calls the functions that resides in my main.cpp when events happen (like clicking a button) or when it needs information (like 'how big to make this window?'). These functions are declared in a seperate .h file included into windowing.h.
Is it worth changing this to be OO? Is it worth the work. Is there any better way I can construct the program without too many changes?
All feedback welcome, thankyou for taking the time to read this.
No, I think if it ain't broke, don't fix it.
Any windowing system is inherently OO to a degree. You have a handle to a window managed by the OS, and you can perform certain operations on it. Whether you use window->resize() or resize(window) is immaterial. There is clearly no value in such syntactic rearrangement.
However, as the application grows, you will likely find that many windows are mostly similar and subtly different. The best implementation is boilerplate basic functionality with special functions attached. And the way to do that is with a base class and polymorphism.
So, if you can refactor the program to be more elegant with OO, go for it. If it grows into the OO paradigm with natural evolution, follow best practices and let it be so. But don't just try to be buzzword-compliant.
Two things you need to think about: cost/benefit analysis and opportunity cost.
What is the cost of changing your code to be OO? What is the benefit? If the latter outweighs the former, then I'd tend towards changing it.
Costs include traditional costs such as time spent, money spent and so on. Benefits include a cleaner implementation, leading to easier maintenance in future. Whatever other costs and benefits there are depend really upon your own situation.
But one thing often overlooked is the opportunity cost. This is a cost that should be factored in to your analysis. It's an economic term meaning foregone opportunities.
In other words, if you do convert your code, your cost includes your inability to do something else with that time.
Classic example. If you do the conversion and a customer decides to not buy your software because you're not adding the feature they want, that lost sales opportunity is a cost.
It depends on what you want to accomplish with the project. If not using the OO features of C++ works for you and there are no good reasons to change, then keep going the way you're going. If, on the other hand, you would like to learn more about OOP and you have the time to apply to it, refactoring it to be more OO style will provide you with a great learning opportunity.
I would follow the best practices for working with whatever window manager you are using. Most use an OO style, which you'll automatically inherit (!) as you follow its usage patterns.

Does it feel anytime that c++ sometimes reduces problem solving time and increases syntactic, semantic rigor? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
C++ introduces OOPS, templates and variety of other concepts. But sometimes I am stuck in unmanageable storm of calling convention incompatibilities between methods, convoluted casting between distantly connected classes and struggling with code that forces me think in the level of byte-alignment.
I am very tempted to go back to plain old-C language that is low level enough and simple enough that I can spend much of my time solving a problem at hand, than having to figure out the conceptual implementation and nuances of using C++.
What is your take on such an issue. Using C-language as the first class citizen in my code-base and coating it at the end with a C++ primer make for a better way to manage a conceptual code-base ??
sometimes I am stuck in unmanageable storm of calling convention incompatibilities between methods, convoluted casting between distantly connected classes and struggling with code that forces me think in the level of byte-alignment.
It sounds like you might be doing something wrong. I don't know what sorts of projects you work on, but I've rarely had to deal with any of those things--certainly never in over 99.9% of the code I've written--and I've written a bit of C++ code (though not nearly as much as others here on StackOverflow).
What is your take on such an issue.
You should consider getting a good book on C++ (like one of the introductory books or any of the best practices books listed in The Definitive C++ Book Guide and List) and really learn C++ if you want to use C++.
I often feel the way you do. C++ compilers are incredibly bitchy about insignificant details and, if you considered them an object, they have appalling encapsulation, and they give horrendously bad error messages. Sometimes, programming C++ feels like fighting against the Standard.
However, I'd never, ever ditch it for C. If you're considering it, you fail C++. Yes, templates and their syntax and some of their semantics can be a bitch, but the power they offer is unparalleled. The things offered like automatic memory management and the power of the STL just can't be matched by C.
In addition, nobody is forcing you to use templates. You could write a whole C++ program using nothing but the pre-provided templates. You could never use polymorphism, or templates, or encapsulation, or object-orientation as a whole, and yes, sometimes none of those solutions are appropriate. But it's plain stupid not to give yourself the option.
And if you're casting classes in C++ (frequently), it sounds to me like whoever wrote the original code flat out didn't know what they were doing. Same for byte alignment.
I've never had to worry about byte alignment unless I was writing binary files.
Casting distantly related classes to each other is bad design.
I've never worried about calling conventions unless I was writing interrupt routines.
If you forced to frequently "cast distantly connected classes" and "think in the level of byte-alignment" - there is something wrong with the architecture of the project. Language is not the problem here.
C++ is heavy. You probably should not use all the features it provides. KISS principle, you know.
You can always pretend that C++ is just "C with classes" and exploit templates and other "hard" stuff only when it will provide reasonable improvement in some areas (like code simplicity, as a matter of fact).
I recently switched back from C++ to C and took a liking in C99. But it certainly depends on what you are doing. For a library of reasonable size, C99 with its advantages over C89, is good enough, and as somebody else said you can easily provide a C++ wrapper, if necessary. C++, I only would go for a big project that has large amount of code reuse (internal or external) with templates.
Things from C++ I missed in C89 have nothing to do with objects or so, but are simple things as declaration of variables inside the for and a well defined inline feature. C99 has that plus variable length arguments for macros, so I am happy with it.
You are not alone. These are all well-known flaws in C++, a language which forces developers to attend incompatible conventions, to struggle to overcome a convoluted caste system, and to take their code in for byte-realignment every 3,000 lines. Definitely switch back to C.

What are the coolest examples of metaprogramming that you've seen in C++? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What are the coolest examples of metaprogramming that you've seen in C++?
What are some practical uses of metaprogramming that you've seen in C++?
Personally, I think Boost.Spirit is a pretty amazing example of meta-programming. It's a complete parser generator that lets you express grammars using C++ syntax.
The most practical use of meta programming is turning a runtime error into a compile time error.
Example: Lets call the interface IFoo. One of my programs dealt with a COM object that had multiple paths to IFoo (very complicated inheritance hierarchy). Unfortunately the underlying COM object implementation didn't realize they had multiple paths to IFoo. They assumed it was always the left most one. So inside their code, the following pattern was very common
void SomeMethod(IFoo* pFoo) {
CFooImpl *p = (CFooImpl)pFoo;
}
The second IFoo though caused the resulting "p" pointer to be completely invalid (multiple inheritance is dangerous).
The long term solution was to have the COM object owner fix this issue. Short term though I needed to make sure that I always returned the correct IFoo. I could guarantee that I had the appropriate IFoo by using a QI and avoiding any implicit casts to IFoo. So I created a new CComPtr<> implementation and added the following override to the equal method.
template <typename T>
CComPtr<T>& operator=(const T* pT) {
// CComPTr Assign logic
}
template <>
CComPtr<IFoo> operator=<IFoo>(const IFoo* pT) {
COMPILE_ERROR();
}
This quickly revealed every single place I implicitly casted to IFoo.
Not of practical usage (except maybe for compiler testing), but metatrace is a Whitted-Style (i.e. recursive and deterministic) ray tracer which generates images like those at compilation time:
Some more complex parts of the code can be seen in fixp.hh, which has an implementation of fixed-point sqrt using the Heron method, or sphere.hh which shows ray/sphere-intersection calculation.
Blitz++ does some impressive things with templates (for instance, a single readable line of code can be turned into a set of loops over a multidimensional array, automatically optimized for the best traversal order).
Coolest metaprogramming example: tricking the compiler into computing a list of prime numbers. Not very practical, but impressive.
One practical use is compile-time assert statements, i.e. causing a compile error if a Boolean condition does not hold.
Loki written by Andrei Alexandrescu
I would have to say Boost.Lambda, Boost.Function, and Boost.Bind and the way that they all work seamlessly together. They provide a really slick interface and make functional programming about as easy as possible in a language that wasn't really built for it.
luabind is a pretty cool practical example, quite a nice binding dsl for binding C++ classes to lua
BOOST_FOREACH
Static assertion (boosts version here)
(Note: builtin support for range-based for loops and static assertions is introduced in C++11)
I posed a question not to long ago: C++ Runtime Knowledge of Classes and the answer I got back from a StackOverflow user "Denice" was a URL to a website Meatspace: C++ runtime class registration.
I think that is a really cool way to use templates and instantiate objects that are all derived from a base class, so that when I have 10 C++ files, they can all just add the AUTO_REGISTER_BASE() at the bottom, and when everything is all done and linked, only those classes/files that made it would be registered, so at runtime you can switch between the different classes that are available, and those that are not available are not registered and thus can't accidently be called.
There are many different OS dependant ways to do event notification (select(), kqueue(), /dev/epoll, Solaris has it's own thing, poll()), and I needed a way to have all of the class files exist in the directory, but depending on what OS the Makefile was run, it would only compile certain ones. I needed a way to know at runtime which ones were available, and have a way for the programmer using the library to select their preference, however if it was unavailable to just use the one that made the most logical sense for the platform (they each have weights assigned to them).
The code above helped me accomplish this goal, with some hefty modifications, but it helped me none-the-less!