XML vs Hardcoded interface? - c++

I'm working on a flexible GUI application that can have ~12 varied layouts. These layouts are all well-defined and won't change. Each layout consists of multiple widgets that interface with a DLL using bit patterns. While the majority of the widgets are the same, the bit patterns used vary depending on the interface type being presented.
My gut instinct is to use inheritance: define a generic 'Panel' and have subclasses for the different configurations. However, there are parts of the interface that are user-defined and are spec'd to be specified in an XML file.
Should the entire panel be defined in XML, or just the user configured sections?

YAGNI: Design your screens for the current requirements, which you specifically state aren't going to change. If a year down the line more customization is needed, make it more customizable then, not now.
KISS: If using XML results in less overall code and is simpler than subclassing, use XML. If subclassing results in less code, use subclassing. Experience tells me subclassing is simpler.

My feeling is that you should do whatever will give you the greater flexibility to change your mind, add new features or adjust the layout in the future.

Related

Best choice for runtime templating engine?

We're designing an app that will generate lots of different types of text output, eg email, html, sms, etc. The output will be generated using some kind of template, with data coming from a db. Our requirements include:
Basic logic / calculated fields within template. Eg "ifs" and "for" loops, plus some things like adding percentages for tax etc
Runtime editing. Our users need to be able to tweak the templates to their needs, such as change boilerplate text, add new logic, etc
Multi lingual. We need to choose the correct template for the current culture.
Culture sensitive. Eg dates and currencies will output according to current ui culture.
Flexibility. We need the templates to be able to handle multiple repeating groups, hierarchies, etc.
Cannot use commercial software as a solution (e.g. InfoPath). We need to be able to modify the source code at any time.
The app is c#.net. We are considering using T4, XML + XSLT or hosting the Razor engine. Given that the syntax cant be too overwhelming for non-techie users, we'd like to get your opinion on which you feel is the right templating engine for us. We're happy to consider ones notalready mentioned too.
Thanks.
I'm very hesitant to try and answer this question on a forum, because technology choices depend on far more factors than are conveyed in the question, including things such as attitude to risk, attitude to open source, previous good and bad experiences, politics and leadership on the project etc. The big advantage of XSLT over Razor is that it's a standard and has multiple implementations on multiple platforms (including at least three implementations on .NET!) so there's no lock-in; but that doesn't seem to be a factor in your statement of requirements. And the fact that you're using .NET suggests that supplier lock-in isn't something that worries you anyway.
One thing to bear in mind is that non-programmers often take to XSLT a lot more quickly than programmers do. Its rule-based declarative approach, and its XML syntax, sometimes make programmers uncomfortable (it's not like anything they have seen before) but end-users often take to it like ducks to water.
We've decided to go with Razor Hosting. The reason why I've posted this is an answer is that I thought it would help others if I include the following article link:
http://www.west-wind.com/weblog/posts/2010/Dec/27/Hosting-the-Razor-Engine-for-Templating-in-NonWeb-Applications
This excellent piece of work by Rick Strahl makes it really easy to host Razor.

What types of design patterns make events easier?

I'm working on a game and I'm finding myself having a ton of listeners.
For example, when the language of the game changes, the LanguageManager sends a languageChanged event which causes all interested gui elements to get the new text and redraw themselves. This means every interested gui element implements the LanguageListener class.
Another thing I find myself doing a lot is injecting dependencies. The GuiFactory needs to set fonts so it has a pointer to the FontManager (which holds an array of TTF fonts), it also has a GuiSkinManager so it can get Image* based on the skin of the game. Is this the right way to do this?
My main concern however is with the listeners and the massive amount of them; especially for the gui. The gui library im using is almost entirely listener driven. I can get away with ActionListeners most of the time but I still have nested ifs for if event.getSource() == button2 etc.
In general what type of design patterns are used to avoid these issues in large game projects that are much more complex than mine?
Thanks
Listeners are often used in huge applications as well. Don't be scared of them. I'm working with one of the biggest java app and I have seen tones of different listeners there, so it looks like that's the way to be.
For smaller applications Mediator could be way-around if you realy hate listening for events ;)
Instead of having one interface per event type containing a single callback (ie. LanguageListener), if you were to follow the Observer design pattern, you would have one interface xObserver with a callback for every kind of event.
class GuiElementObserver
{
public:
void LanguageChangedEvent(...) {}
void OtherEvent() {}
};
The default empty implementations allow you to redefine only the events you are interested in in the concrete classes.
Concerning dependencies, whenever I refactor code, I like to use the Single Responsibility Principle (http://en.wikipedia.org/wiki/Single_responsibility_principle). You said that the GuiFactory needs to set fonts... But is it really the responsibility of a factory to set fonts?
If you limit the responsibilities of your classes to what they were originally meant to do, you should have leaner classes, cleaner code and fewer dependencies. In this case, maybe adding a font manager and moving the font related code there could be a solution.

Presenting MVC to Old C++ Spaghetti Coders?

I wish to present the idea of MVC to a bunch of old C++ spaghetti coders (at my local computer club).
One of them that has alot of influence on the rest of the group seems to finally be getting the idea of encapsulation (largely due in part to this website).
I was hoping that I could also point him in the right direction by showing him Model View Controller, but I need to do it in a way that makes sense to him, as well as it probably needs to be written in C/C++!
I realize that MVC is a very old architectural pattern so it would seem to me that there should be something out there that would do the job.
I'm more of a web developer, so I was wondering if anybody out there who is a good C/C++ coder could tell me what it is that made the MVC light switch turn on in your head.
Don't start off with MVC. Start off with Publish / Subscribe (AKA the "listener" pattern).
Without the listener pattern fully understood, the advantages of MVC will never be understood. Everyone can understand the need to update something else when something changes, but few think about how to do it in a maintainable manner.
Present one option after another, showing each option's weaknesses and strengths: making the variable a global, merging the other portion of code into the variable holder, modifying the holder to directly inform the others, and eventually creating a standard means of registering the intent to listen.
Then show how the full blown listener can really shine. Write a small "model" class and add half a dozen "listeners" and show how you never had to compromise the structure of the original class to add "remote" updates.
Once you get this down, move the idea into to the "model view" paradigm. Throw two or three different views on the same model, and have everyone amazed on how comparatively easy it is to add different views of the same information.
Finally discuss the need to manage views and update data. Note that the input is partially dependent on items which are not in the view or the model (like the keyboard and mouse). Introduce the idea of centralizing the processing where a "controller" needs to coordinate which models to create and maintain in memory, and which views to present to the user.
Once you do that, you'll have a pretty good introduction to MVC.
You might find it easier to sell them on the Document/View or Document/Presenter patterns. MVC was invented on Smalltalk where everything about the different UI elements had to be coded by the developer (as I understand, never used the thing). Thus the controller element was necessary because didn't have things like TextElement::OnChange. Now days, more modern GUI API's use Document/View but Document/Presenter is something I've seen proposed.
You might also consider reading Robert Martin's article on the TaskMaster framework.
You might also consider that any C++ developer who is not familiar with these patterns and already understands their purpose and necessity is either a complete newb or a basket-case best avoided. People like that cause more harm than good and are generally too arrogant to learn anything new or they already would have.
Get some spaghetti C++ code (theirs?), refactor it to use MVC, and show them what advantages it has, like easier unit testing, re-use of models, making localized changes to the view with less worry, etc.

Interface hierarchy design pattern?

I'm in the early stages of developing a C++ multi platform (mobile) application which has a graphical user interface. I'm trying to find a good way of abstracting the actual UI/windowing implementation. Here is basically what I have tried so far:
I created an interface hierarchy
Screen
+Canvas
+Form
+Dialog
Control
+EditBox
+CheckBox
+...
and I also have a class, Application, which basically uses all of these interfaces to implement the UI logic. The Application class also provides abstract factory methods which it uses to create UI class instances.
These interfaces all have implementations. For example, for Windows Mobile, Win32Form implements Form, Win32Canvas implements Canvas and Win32Dialog implements Dialog. As you can see, the problem is that the implementations loses the hierarchy, i.e. Win32Dialog doesn't extend Win32Form.
This becomes a problem in, for example, the method Form::addControl(Control &ctrl). In the Windows Mobile version of the application, I know the ctrl parameter is one of the Win32... control implementations. But since the hierarchy is lost, there is no way of knowing if it's a Win32EditBox or a Win32CheckBox, which I really need to know in order to perform any platform specific operations on the control.
What I am looking for is some design pattern on how to solve this problem. Note that there is no requirement to retain this interface hierarchy solution, that is just my current approach. I'll take any approach that solves the problem of letting the UI logic be separate from the several different UI implementations.
Please don't tell me to use this or that UI library; I like coding stuff from scratch and I'm in this for the learning experience... ;-)
Some inspiration from my side:
Don't inherit Form from a Screen. It's not "is-a" a realtionship.
Screen
Canvas
GUIObject
Form
Dialog
Control
Button
EditBox
CheckBox
...
Panel
More detailed description:
Screen
"has-a" canvas
provides display specific functions
don't be tempted to inherit from Canvas
Canvas
your abstracted drawing environment
target is screen canvas, form canvas, image, memory...
GUIObject
Wnd in some of hierarchies
usually provides some introspection capabilities
usually provides message processing interface
Form
in some toolkits actually called "dialog"
"has-a" canvas on which you can draw
"has-a" list of controls or a client area Panel
"has-a" title, scrollbars, etc.
Dialog
I like to call dialog standardized YesNo, OpenFile etc, basically simplified Form (no close button, no menu etc.)
may or may not be inherited from Form
Controls are hopefully self-explanatory (Panel is area with controls inside with optional scrollbars).
This should work. However how to exploit specific features of each platform without ruining genericity of this interface and/or ease of use is the difficult part. I usually try to separate all drawing from these basic classes and have some platform specific "Painter" that can take each basic object and draw it in platform specific way. Another solution is parallel hierarchy for each platform(I tend to avoid this one, but sometimes needed - for example if you need to wrap windows handles) or "capability bits" approach.
You can use containment. For example the class that implements Dialog would contain a Win32Dialog as a property, and the class that implements Form would contain a Win32Form; all the accesses to the Dialog or Form members would delegate to accesses to the contained classes. This way, you can still make Dialog inherit from Form, if this is what makes sense for your project.
Having said that, I see somethinf strange in your interface design. If I understood correctly (I may have not, then please correct me), Dialog inherits from Form, and Form inherits from Screen. Ask yourself this to validate this design: Is a Dialog also a Form? Is it also a Screen? Inheritance should be used only when a is-a relationship makes sense.
The GOF pattern that addresses this issue is the Bridge Pattern. Konamiman's answer explains it, you use delegation/containment to abstract one of the concerns.
I've spent years doing mobile phone development.
My recommendation is that you do not fall into the 'make an abstraction' trap!
Such frameworks are more code (and tiresome hell, not fun!) than just implementing the application on each platform.
Sorry; you're looking for fun and experience, and I'd say there are funner places to get it.
First, the primary problem seems to be that there is no abstraction in your "abstraction" layer.
Implementing the same controls as are provided by the OS, and simply prefixing their names with "Win32" does not constitute abstraction.
If you're not going to actually simplify and generalize the structure, why bother writing an abstraction layer in the first place?
For this to actually be useful, you should write the classes that represent concepts you need. And then internally map them to the necessary Win32 code. Don't make a Form class or a Window class just because Win32 has one.
Second, if you need the precise types, I'd say ditch the OOP approach, and use templates.
Instead of the function
Form::addControl(Control &ctrl)
define
template <typename Ctrl_Type>
Form::addControl(Ctrl_Type &ctrl)
now the function knows the exact type of the control, and can perform whatever type-specific actions you want. (Of course, if it has to save the control into a list in the control, you lose the type information again. But the type information is propagated that much further, at least, which may help.
The collection could store something like boost::variant objects, even, which would allow you to retain some type information even there.
Otherwise, if you're going the OOP route, at least do it properly. If you're going to hide both EditBoxes and CheckBoxes behind a common IControl interface, then it should be because you don't need the exact type. The interface should be all you need. That's the point in interfaces.
If that contract isn't respected, if you're going to downcast to the actual types all the time, then your nice OOP hierarchy is flawed.
If you don't know what you're trying to achieve, it's going to be hard to succeed. What is the purpose of this Trying to write an "abstraction of the user interface exposed by Windows", you're achieving nothing, since that's what Windows already exposes. Write abstraction layers if the abstraction exposed by Windows doesn't suit your needs. If you want a different hierarchy, or no hierarchy at all, or a hierarchy without everything being a Form, or a Control, then writing an abstraction layer makes sense. If you just want a layer that is "the same as Win32, but with my naming convention", you're wasting your time.
So my advice: start with how you'd like your GUI layer to work. And then worry about how it should be mapped to the underlying Win32 primitives. Forget you ever heard of forms or dialog boxes or edit boxes, or even controls or windows. All those are Win32 concepts. Define the concepts that make sense in your application. There's no rule that every entity in the GUI has to derive from a common Control class or interface. There's no rule that there has to be a single "Window" or "Canvas" for everything to be placed on. This is the convention used by Windows. Write an API that'd make sense for you.
And then figure out how to implement it in terms of the Win32 primitives available.
Interesting problem, so a couple of thoughts:
first: you could always use MI so that Win32Dialog inherits from both Win32Form and Dialog, since you then get a nice diamond you need virtual inheritance
second: try to avoid MI ;)
If you want to use specific controls, then you are in a Win32 specific method, right ? I hope you are not talking about up_casting :/
Then how comes that this Win32 specific control method has been handed a generic object, when it could have got a more precise type ?
You could perhaps apply the Law of Demeter here. Which works great with a Facade approach.
The idea is that you instantiate a Win32Canvas, and then ask the canvas to add a dialog (with some parameters), but you never actually manipulate the dialog yourself, this way the canvas knows its actual type and can execute actions specific to the platform.
If you want to control things a bit, have the canvas return an Id that you'll use to target this specific dialog in the future.
You can alleviate most of the common implementation if canvas inherit from a template (templated on the platform).
On the other hand: Facade actually means a bloated interface...

Using strings with "general purpose" XML in WS - good or bad?

We're working now on the design of a new API for our product, which will be exposed via web services. We have a dispute whether we should use strict parameters with well defined types (my opinion) or strings that will contain XML in whatever structure needed. It is quite obvious that ideally using a strict signature is safer, and it will allow our users to use tools like wsdl2java. OTOH, our product is developing rapidly, and if the parameters of a service will have to be changed, using XML (passed as a string or anyType - not complex type, which is well defined type) will not require the change of the interface.
So, what I'm asking for is basically rule of thumb recommendations - would you prefer using strict types or flexible XML? Have you had any significant problems using either way?
Thanks,
Eran
I prefer using strict types. That gives you access to client tools that make that end of the job much easier. You also state that if the messaging changes, the string approach will not require changing the interface. Personally, I see this as a disadvantage, not an advantage. If the interface changes, you will know very quickly which clients need to be updated.
Strings containing XML is an extremely bad idea and asking for trouble. Use messages that have a defined schema.I had to rewrite significant portions of an app that used a lot of XML internally instead of types. It was horribly slow and impossible to figure out what was happening.