Saturday, August 28, 2010

Visual C++ 2010: What’s new for MFC library?

Some years ago i thought that MFC will be obsolete, and no new features will be added, but i was wrong, VS2008 added many features and functionalities, and with VS 2010 i discovered new improvements.

So what's new in MFC 10? to answer to this question i tried to compare the two versions MFC 9 and MFC 10 using CppDepend.

Removed classes:

Let's begin with breaking changes and search for removed classes:

SELECT TYPES WHERE WasRemoved




It was very strange that this class is removed , and to be sure i searched in the code source and i found it inside #ifdef ENABLE_RIBBON_LAUNCH_BUTTON statement.

The only resource i found in the web talking about this change is here , and i dont know if
adding #define ENABLE_RIBBON_LAUNCH_BUTTON is suficient to compile without problem.


Added Classes:

SELECT TYPES WHERE WasAdded AND isClass





What's the new features added by these classes?

CMFCRibbonCollector,CMFCRibbonConstructor,CMFCRibbonInfo:
When i searched in MSDN the utility of these classes , i didnt found any useful informations, so i searched for methods using CMFCRibbonInfo.

SELECT METHODS WHERE IsDirectlyUsing "CMFCRibbonInfo"




The RibbonBar class use CMFCRibbonInfo to save it to xml or load it.


CJumpList,CAppDestinations:
Jump list is a new useful Window7 feature, it adds a new way of interaction beteween user and application.
here's a good article to add JumpList feature with MFC.


CMFCControlContainer:

This class provides a CWnd support for MFC Control containment of Feature Pack controls.

And to know which controls can be contained inside this container, let's search for classes used by CMFCControlContainer::CreateDlgControl.

Here's the result:



So only these MFC feature pack controls are concerned by this container.


CDocument::CDocumentAdapter:

This class implements ATL::IDocument interface required for "Search and Organize" feature.
My first impression when i discovered that implemention was " WOW, MFC use now interfaces to enforce low coupling".

Let's see the impact of using this interface, for that let's search for classes using CDocumentAdapter :

SELECT TYPES WHERE IsDirectlyUsing "CDocument+CDocumentAdapter"



only CDocument use directly this class.

However IDocument is used by other classes like the new class CMFCPreviewCtrlImpl, so this class can work with CDocumentAdapter and also others classes implementing this interface.

And as explained in the comment of CDocumentAdapter code source:

"Search and Organize handlers are implemented in ATL DLLs, which can be MFC or not-MFC based.Internally handlers refer to IDocument interface, whose implementation in the common case should be supplied by a developer. CDocumentAdapter provides this implementation for MFC and basically calls the appropriate methods of the parent CDocument."


CDataRecoveryHandler:
This class autosaves documents and restores them if an application unexpectedly exits, it's used by Restart Manager feature, here's an interesting article talking about it.

Let's search for classes used by CDataRecoveryHandler:

SELECT TYPES WHERE IsDirectlyUsedBy "CDataRecoveryHandler"



CDataRecoveryHandler is highly coupled with other MFC classes like CDocument, CWinApp, CWnd.



Which MFC classes use the recovery feature?

SELECT TYPES WHERE IsDirectlyUsing "CDataRecoveryHandler"



So all these classes benefit of this new feature especially CDocument.

CTaskDialog:
A pop-up dialog box that functions like a message box but can display additional information to the user.
here's an interesting article talking about this feature.

CMFCVisualManagerVS2008,CMFCVisualManagerWindows7:
Gives an application the apparence of a VS2008 or Windows 7 application.


CGestureConfig:
Used for touch feature.

CFolderPickerDialog:
CFolderPickerDialog class implements CFileDialog in the folder picker mode.

CXMLParser,CXMLParserCollection,CXMLParserRoot:
when i dsicovered these classes, i thouth that is concerning xml parsing but when i searched for methods using them i discovered that only CMFCRibbonInfo use them to save or load its description to xml files.

SELECT METHODS WHERE IsDirectlyUsing "CXMLParserRoot"



CMFCZoomKernel,CMFCScanliner, CMFCScanlinerBitmap :
Not yet documented in MSDN, let's discover which classes use them.

SELECT TYPES WHERE IsDirectlyUsing "CMFCZoomKernel"



And we have the same result for the two other classes.


SafeInt classes:

Extends the integer primitives to help prevent integer overflow and lets you compare different types of integers.

here's a video about using SafeInt.

Methods Removed:

SELECT METHODS WHERE WasRemoved




Almost all theses methodes are not removed but only the signature is changed , and some optional parameters are added, however some methods are removed like CCommandManager::ResetAllImages or CPanelDialog::ClipPaint, and one method was renamed from CMFCRibbonBar::GetTabTrancateRatio to CMFCRibbonBar::GetTabTruncateRatio.



Methods Added:

Let's search for all methods added to MFC10

SELECT METHODS WHERE WasAdded




Which features are added by these new methods?

For that we will focus only in the most used classes.

CWnd:

Here's the methods added for CWnd, and almost all methods added concern touch feature and touch gestures.



CFile,CStdioFile,CFileFind:
Many methods of these classes add CAtlTransactionmanager as optional parameter.

Transactional File System is a new technology first introduced in Windows Vista. It enables you to roll back operations made on the file system and registry.

here's a good article about this feature.

CRecentFileList:



New possibilities to add item to recent file list are now available.

CDocument:
Here's the methods added by CDocument:



Two new features concern methods added :

-Supporting Windows Search with MFC
-Rich Preview

Let's discover the changes concerning dependency of CDocument to other MFC classes,and which additional dependencies are added in MFC10, for that Dependency Matrix can be useful, and the sign "+" in the cell representing the dependency indicate that this dependency is new.



So many dependencies are added, especially with new classes added to MFC10 like CDataRecoveryHandler,and also some other inner classes added to CDocument.


CFileDialog:
Here's the methods added by CFileDialog:




A good news is we can now customize CFileDialog by adding what we want in the dialog.


CMDIChildWndEx:
Here's the methods added by CMDIChildWndEx:



Windows7 add a new interesting features like:taskbar Tabs,Taskbar thumbnails and thumbnail previews, and almost all methods added to CMDIChildWndEx concern theses features.


CFrameWnd:

Windows 7 add also some useful features like OverlayIcon and progressbar in the taskbar, and the methods added to CFrameWnd concern these features.





CWinApp:

Almost all methods added to CWinApp concern the ApplicationRecovery support.





Other useful methods are added like CMFCControlRenderer::SmoothResize and CDrawingmanager::DrawRotated.


Methods where visibility was changed:

SELECT METHODS WHERE VisibilityWasChanged



Almost the visibility of all CMFCRibbonTab methods is changed from private to public.

But when i checked the code source the only modification in the class declaration is the adding of DECLARE_DYNAMIC(CMFCRibbonTab) , this macro include "public:" , so i wonder if this visibility changes is only a side effect of adding this macro.

Methods Not Used Anymore:

Some methods become obsolete when upgrading framework version, did MFC10 not use anymore some methods?

To answer to this question let's execute the query :

SELECT METHODS WHERE IsNotUsedAnymore

here's the result:




Theses methods was declared before in multimon.h , the origin of this file goes back to Windows 98 to let compatibility with Windows 95 in the case of multi monitor, here's an interesting article talking about it.
In MFC10 this file is no longer included in mfc files. and MFC10 use directly GetSystemMetrics instead of xGetSystemmetrics.

Wednesday, August 18, 2010

Where's the model for MFC Doc/View Design?

MFC is a good library that wraps Windows API, and it’s also a framework so it provides a structure for your application and influent the design.

We have to be careful when using frameworks, because it impact also the design, and accepting the structure imposed by a specific framework without understanding its impact could be dangerous.

Let’s take a look into Doc/View architecture proposed by MFC and discuss how MVC pattern could be implemented.


Did CDocument/CView implements MVC pattern?

Doc/View architecture as described by many articles is implementing MVC pattern, but where’s the Model, the controller and the view?

Here’s a description from this msdn article:

“The Document-View variant recognizes all three roles of Model-View-Controller but merges the controller into the view. The document corresponds to the model role in MVC. This variant is present in many existing GUI platforms. An excellent example of Document-View is the Microsoft Foundation Class Library (MFC) in the Microsoft Visual C++ environment. The tradeoff of using this variant is that the view and the controller are more tightly coupled.”

So the CDocument is the model and CView merge the view and controller.



But actually the CDocument is not representing only the model , and to proof it let’s discover some CDocument design and methods:

CDocument derives from CCmdTarget to receive events and commands and contains the following methods : AddView, GetFirstViewPosition,GetNextView,UpdateAllViews.

So this class treats events,refresh and manage views, so it have some controller responsability.


Why CDocument is not the good candidate to be the model?


As described below the CDocument contains controller logic, and considering it also as model impact a lot the cohesion of classes, each classe must have a specific responsibility; it makes the design more flexible.

The model must be independent of any framework used, if it can be a POCO classes it will be wonderful, the question is why coupling the model with a specific framework?
high coupling makes the design more rigid, and any evolution or changes will be very difficult, for example if some client ask to provides also webservices, and if our model is highly coupled with CDocument , this evolution will cost a lot, on the other side if it’s independent to CDocument it can be developed more easily.


What’s the conclusion of this story?

  • High cohesion and low coupling are two powerful concepts that assist your design, but their benefits are more visible only if evolutions or changes are needed.
  • Be careful when using external frameworks, and not understanding the design provided by the framework could impact a lot the design quality of your application.

Friday, February 19, 2010

Could we reuse Garbage collector of V8 javascript engine?

V8 javascript engine is well optimized, and use an efficient way to manage memory.
And I wonder if I can use the garbage collector easily in other projects? and to answer to this question we have to talk about coupling metrics.

There is a whole range of interesting code metrics relative to coupling. The simplest ones are named Afferent Coupling (Ca) and Efferent Coupling (Ce). Basically, the Ca for a code element is the number of code elements that use it and the Ce is the number of code elements that it uses.



You can define Ca and Ce for the graph of projects dependencies, the graph of namespaces dependencies, the graph of types dependencies and the graph of methods dependencies of a code base. You can also define the Ca metric on the fields of a program as the number of methods that access the field. This leads to 9 metrics all supported by the tool CppDepend We precise that when computing Ce.

With CppDepend, if you wish to know which methods of your program are massively used you can write the following CQL Query :

SELECT TOP 10 METHODS ORDER BY MethodCa DESC

Being used a lot is not necessarily a problem. However it is still interesting to know which part of your code base is used a lot.

High Efferent Coupling and design flaws

If you wish to know which types of your program are heavy users of other types you just have to write:

SELECT TOP 10 TYPES ORDER BY TypeCe DESC

High Ce might reveal a design problem. Types with high Ce are entangled with many other implementations. The higher the Ce, the higher the number of responsibilities the type has.


What about reusing garbage collector?


The class representing the garbage collector is MarkCompactCollector, this class has a TypeCe equal to 34, but how many types this class use indirectly.

SELECT TYPES WHERE IsUsedBy "v8.internal.MarkCompactCollector"

And there’s the result



And the metric view shows better relation between MarkCompactCollector class and other V8 types:




So it’s very difficult to isolate only the garbage collector mechanism from V8 source code, Maybe in the future the V8 team will isolate this garbage collector, and it will be used in other projects.

Wednesday, February 17, 2010

Lessons to take from V8 javascript engine

V8 is Google's open source JavaScript engine it's written in C++ and is used in Google Chrome, the open source browser from Google.

It's very interesting to discover how this engine is implemented and what lessons we can take when analyzing it.

here's some remarks about this engine:

Optimization is also a design issue

When I hear that google chromium browser use fast javascript engine, I was sure that it was developed with “C” language like almost all known languages and interpreters (Perl, Python, PHP, Spider Monkey), but when I got the source code, I was very surprised that‘s developed with C++.

The goal of this engine is to be very fast and the decision of V8 team to choose C++ proof that performance depends also on design choices more than language choice.

There’s some V8 Design Choices:

Hidden Class:

JavaScript is a dynamic programming language: properties can be added to, and deleted from, objects on the fly. This means an object's properties are likely to change.
Javascript has a class concept but there’s a class representing it in source code?

To answer to this question let’s search in V8 source code all objects kind treated, for that we can execute the following request:

SELECT TYPES WHERE DeriveFrom "v8.internal.JSObject"






as we can observe there's no class inheriting from JSObject representing a Class like Function or Value, it's normal because in any dynamic langage the idea is to create a class in the real time and most JavaScript engines use a dictionary-like data structure as storage for object properties,each property access requires a dynamic lookup to resolve the property's location in memory.

This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and Smalltalk. In these languages, instance variables are located at fixed offsets determined by the compiler due to the fixed object layout defined by the object's class. Access is simply a matter of a memory load or store, often requiring only a single instruction.

V8 use hidden class concept to reduce the time required to access JavaScript properties. V8 does not use dynamic lookup to access properties. Instead, V8 dynamically creates hidden classes behind the scenes as detailled in this post.

Dynamic machine code generation:

V8 compiles JavaScript source code directly into machine code when it is first executed. There are no intermediate byte codes, no interpreter. Property access is handled by inline cache code that may be patched with other machine instructions as V8 executes.

let's discover the dependency graph for MakeCode function.




Garbage collector:


V8 use an efficient garbage collector to manage memory, and I was very interested to know if I can use it easily in other C++ projects, for that I have to look if the garbage collector classes are highly coupled with other V8 classes or not.

An interesting question is to know if we can use MarkCompactCollector in other C++ projects.

for that let’s search for indirect dependencies for this class:

SELECT TYPES WHERE IsUsedBy "v8.internal.MarkCompactCollector"




Unfortunately this class is highly coupled with a lot of other V8 classes.

V8 is optimized and use design patterns:

I dont know why many developpers think that using OOP and design patterns can impact a lot the optimization.

V8 is an example of project that use OOP and patterns and in the same time very optimized.

here's for example two patterns used:

Factory:

The factoy class create many objects needed and do abstraction of garbage collector invocation, for example let's search for methods invoked by Factory::NewJsObject

SELECT METHODS WHERE IsDirectlyUsedBy "v8.internal.Factory.NewJSObject(Handle,PretenureFlag)"



as we can observe this method do some abstraction of memory allocation.

Visitor:

V8 contains many classes implementing visitor pattern.





Make C++ easy to use:

Memory allocation simplified

Managing memory and allocating pointers is complicated in C++ Using garbage collector can simplify this task.

Avoid multiple inheritance

Let's search for classes with multiple base classes:

SELECT TYPES WHERE NbBaseClass >1

and the result of this query is empty so V8 dont use multiple inheritance, it simplify a lot the developement and evolution of application.

Use RTTI carefully

Using RTTI resolve some problems but can be an indicator of a bad design, be sure to no overuse this technique.

Let's search if V8 use dynamic_cast:

SELECT METHODS WHERE IsDirectlyUsing "Keywords.dynamic_cast"

the result is empty and it's an indicator from others that V8 is well designed.

Exceptions

Using exceptions is interesting but is not easy that a code be exception safe.
V8 team choose to not use exceptions to simplify the implementation.

we can execute the following CQL request to know if exception is used:

SELECT METHODS WHERE IsDirectlyUsing "Keywords.throw"

Thursday, December 3, 2009

C vs C++: The Linux case

I think that the debate "C vs C++" will end when the two langages died, and each one have its advantages and inconvenients, the choice of one instead of another depend on the application context.

Recently i read a famous linus torvalds opinion about C++, where he wrote:

"C++ is a horrible language. It's made more horrible by the fact that a lot of substandard programmers use it, to the point where it's much much easier to generate total and utter crap with it. Quite frankly, even if the choice of C were to do *nothing* but keep the C++ programmers out,that in itself would be a huge reason to use C."

Thursday, November 19, 2009

Irrlicht:The art of using GRASP patterns

When we search for design pattern articles, we found essentially documentation concerning "Gang of Four" patterns, they are very useful and contribute to well design application.

But when i discovered GRASP patterns , i advice any one interested to improve his skills design to look at this patterns, it gives a design fondamental rules.

Irrlicht is a 3D engine library that use many GRASP concepts, let's discover with CppDepend the benefits of using this kind of patterns, and to show using of GRASP concepts we will focus on the namespace irr::gui.

Tuesday, November 17, 2009

Inside Qt Part 1 : QtCore

Qt is a cross-platform application development framework, widely used for the development of GUI programs ,and also used for developing non-GUI programs such as console tools and servers.

Qt consists of several modules, and each one rely on QtCore, this module contains all basic classes like Containers,String,Smart Pointer,Multithreading,Localisation and other funcionalities.

Let's discover with CppDepend the QtCore module.