Update GUI based on boolean - c++

Trying to grey out certain buttons/text fields depending on the state of a boolean in my program. The boolean keeps track of if the connection to a subsystem is still up. Initializes to false until it connects, and then a watch dog keeps it updated from there on.
This may happen many times through the execution of the program, and thus I would like to make some sort of monitor that merely watches the state of the boolean and updates the GUI/button properties as appropriate.
My initial thought was to make some sort of event handler for this, but in my searches I found something called "properties" in C# that may make this even easier. Unfortunately I wasn't able to find a ton of information on this technique (initial thread here: How to trigger event when a variable's value is changed?)
So I have come to you folks with the hope that you may be able to give me an idea of the best way to do this.
Thanks,
EDIT:: Not sure if it matters, but the boolean is declared as an extern. This may make things easier, as I noticed in many cases the observer pattern is used when communicating between classes, which is not a concern in this problem.

C# properties just provide specialized syntax for getting/setting variables in an object. Since they are just specialized methods, you can really add whatever other functionality you want. From what you have described, I would probably recommend going with a listener... action listeners use a pattern called the "observer", which exactly fits what you're trying to do in this case. You can Google "observer pattern", and you'll get a lot more info on how to use it, and create your own variants, which you may or may not decide to do :)
Good luck!

Let me give you a simple example:
button1.IsEnabled = false;
To disable a button or a text field you just have to do that.

Related

C++ Singleton Design pattern alternatives

I hate to beat a dead horse, that said, I've gone over so many conflicting articles over the past few days in regards to the use of the singleton pattern.
This question isn't be about which is the better choice in general, rather what makes sense for my use case.
The pet project I'm working on is a game. Some of the code that I'm currently working on, I'm leaning towards using a singleton pattern.
The use cases are as follows:
a globally accessible logger.
an OpenGL rendering manager.
file system access.
network access.
etc.
Now for clarification, more than a couple of the above require shared state between accesses. For instance, the logger is wrapping a logging library and requires a pointer to the output log, the network requires an established open connection, etc.
Now from what I can tell it's more suggested that singletons be avoided, so lets look at how we may do that. A lot of the articles simply say to create the instance at the top and pass it down as a parameter to anywhere that is needed. While I agree that this is technically doable, my question then becomes, how does one manage the potentially massive number of parameters? Well what comes to mind is wrapping the different instances in a sort of "context" object and passing that, then doing something like context->log("Hello World"). Now sure that isn't to bad, but what if you have a sort of framework like so:
game_loop(ctx)
->update_entities(ctx)
->on_preupdate(ctx)
->run_something(ctx)
->only use ctx->log() in some freak edge case in this function.
->on_update(ctx)
->whatever(ctx)
->ctx->networksend(stuff)
->update_physics(ctx)
->ctx->networksend(stuff)
//maybe ctx never uses log here.
You get the point... in some areas, some aspects of the "ctx" aren't ever used but you're still stuck passing it literally everywhere in case you may want to debug something down the line using logger, or maybe later in development, you actually want networking or whatever in that section of code.
I feel like the above example would much rather be suited to a globally accessible singleton, but I must admit, I'm coming from a C#/Java/JS background which may color my view. I want to adopt the mindset/best practices of a C++ programmer, yet like I said, I can't seem to find a straight answer. I also noticed that the articles that suggest just passing the "singleton" as a parameter only give very simplistic use cases that anyone would agree a parameter would be the better way to go.
In this game example, you probably wan't to access logging everywhere even if you don't plan on using it immediately. File system stuff may be all over but until you build out the project, it's really hard to say when/where it will be most useful.
So do I:
Stick with using singletons for these use cases regardless of how "evil/bad" people say it is.
Wrap everything in a context object, and pass it literally everywhere. (seems kinda gross IMO, but if that's the "more accepted/better" way of doing it, so be it.)
Something completely else. (Really lost as to what that might be.)
If option 1, from a performance standpoint, should I switch to using namespace functions, and hiding the "private" variables / functions in anonymous namespaces like most people do in C? (I'm guessing there will be a small boost in performance, but then I'll be stuck having to call an "init" and "destroy" method on a few of these rather than being able to just allow the constructor/destructor to do that for me, still might be worth while?)
Now I realize this may be a bit opinion based, but I'm hoping I can still get a relatively good answer when a more complicated/nested code base is in question.
Edit:
After much more deliberation I've decided to use the "Service Locator" pattern instead. To prevent a global/singleton of the Service Locator I'm making anything that may use the services inherit from a abstract base class that requires the Service Locator be passed when constructed.
I haven't implemented everything yet so I'm still unsure if I'll run into any problems with this approach, and would still love feedback on if this is a reasonable alternative to the singleton / global scope dilemma.
I had read that Service Locator is also somewhat of an anti-pattern, that said, many of the example I found implemented it with statics and/or as a singleton, perhaps using it as I've described removes the aspects that cause it to be an anti-pattern?
Whenever you think you want to use a Singleton, ask yourself the following question: Why is it that it must be ensured at all cost that there never exists more than one instance of this class at any point in time? Because the whole point of the Singleton pattern is to make sure that there can never be more than one instance of the Singleton. That's what the term "singleton" is all about: there only being one. That's why it's called the Singleton pattern. That's why the pattern calls for the constructor to be private. The point of the Singleton pattern is not and never was to give you a globally-accessible instance of something. The fact that there is a global access point to the sole instance is just a consequence of the Singleton pattern. It is not the objective the Singleton pattern is meant to achieve. If all you want is a globally accessible instance of something, then use a global variable. That's exactly what global variables are for…
The Singleton pattern is probably the one design pattern that's singularly more often misunderstood than not. Is it an intrinsic aspect of the very concept of a network connection that there can only ever be one network connection at a time, and the world would come to an end if that constraint was ever to be violated? If the answer is no, then there is no justification for a network connection to ever be modeled as a Singleton. But don't take my word for it, convince yourself by checking out page 127 of Design Patterns: Elements of Reusable Object-Oriented Software where the Singleton pattern was originally described…😉
Concerning your example: If you're ending up having to pass a massive number of parameters into some place then that first and foremost tells you one thing: there are too many responsibilities in that place. This fact is not changed by the use of Singletons. The use of Singletons simply obfuscates this fact because you're not forced to pass all stuff in through one door in the form of parameters but rather just access whatever you want directly all over the place. But you're still accessing these things. So the dependencies of your piece of code are the same. These dependencies are just not expressed explicitly anymore at some interface level but creep around in the mists. And you never know upfront what stuff a certain piece of code depends on until the moment your build breaks after trying to take away one thing that something else happened to depend upon. Note that this issue is not specific to the Singleton pattern. This is a concern with any kind of global entity in general…
So rather than ask the question of how to best pass a massive number of parameters, you should ask the question of why the hell does this one piece of code need access to that many things? For example, do you really need to explicitly pass the network connection to the game loop? Should the game loop not maybe just know the physics world object and that physics world object is at the moment of creation given some object that handles the network communication. And that object in turn is upon initialization told the network connection it is supposed to use? The log could just be a global variable (or is there really anything about the very idea of a log itself that prohibits there ever being more than one log?). Or maybe it would actually make sense for each thread to have its own log (could be a thread-local variable) so that you get a log from each thread in the order of the control flow that thread happened to take rather than some (at best) interleaved mess that would be the output from multiple threads for which you'd probably want to write some tool so that you'd at least have some hope of making sense of it at all…
Concerning performance, consider that, in a game, you'll typically have some parent objects that each manage collections of small child objects. Performance-critical stuff would generally be happening in places where something has to be done to all child objects in such a collection. The relative overhead of first getting to the parent object itself should generally be negligible…
PS: You might wanna have a look at the Entity Component System pattern…

Newbie Needs Direction - Monitor contents of variable in a seperate process

I want to apologize up front for being unfamiliar with the terminology I should use. I have programming experience, but not in this area. I'm looking for general guidance, links to helpful sources, books, ect that will help me understand my problem better and can possible give a tutorial on how to achieve a solution.
On the surface, I think what I am trying to do is pretty simple, it's just I have never done any programming with hooking other applications.
The Goal:
I am trying to monitor (not change) a variable (or a few variables) in a game. In the UI of the game, there is a box that lists some items in plain text. I want to know what items that box contains. I would like a function in my code that returns the contents of that box as a string. This could be done with OCR, but I was thinking this may be a better, faster, more accurate solution. Plus, OCR isn't a simple solution either.
I will likely be writing my program in C++, since it seems like that would be the best language for my overall project (of which, this is just a small, but important part).
I would appreciate your thoughts or suggestions on the best way to achieve this. Especially any references that may help me to create such a function.
Thank you.
One approach is to have a "monitoring" task that goes through the variables and sends events to a container of recipients. The frequency would be adjustable via sleep command.
You could also use an std::bitset to indicate whether the variable's value has changed since the last notification and only notify recipients of the changed variables.
Research "subscriber design pattern" and "publisher design pattern".

boost::signals2 and exception handling

Is there some way to override the specific moment when a slot is called in boost::signals2 and perform some actions (logging, debugging, exception handling)?
I would like to catch exceptions at the moment of slot invocations, because signals/slots are where the execution path in my code crosses between various software components and each component is meant to be optional / can be disabled at run-time if it misbehaves. So when a slot invocation throws (might come from an external library, might just be std::bad_alloc), I would like to be notified about it -- and know which component was signaled into -- so I can kill that component.
I don't see how I can do it in a combiner because I don't have access to the slot or connection objects there? So I don't see a way to get any information. (Changing the return type on every slot is unfeasible.)
Is there some super easy way to do this that I've missed?
If not, how should I go about it?
Subclass something like slot_call_iterator (to wrap call in try/catch) and connection_body_base (to store information about what component it belongs to for example) and have boost use these? (How?)
Or subclass signals2::slot<...>, give it information about the owning component in the constructor and somehow overload the operator()(...)? (No idea about that either, seems way harder with all the template magic.)
To summarize the comments:
From Igor R.
Such a functionality doesn't seem to exist, but you can add a feature
request in the trac (or even provide a patch).
From integer (nice nickname):
Thank you for your comment. Yeah, I assumed it didn't exist, was just
wondering if there were a way to subclass or override publicly
exported boost classes to make my own, sort of. It can be intimidating
trying to do this blindly with boost code as I'd fear doing something
which might break or misuse internals.

Is it acceptable practice to give an object a pointer to "the world"?

I often find myself in situations where objects need to communicate between each other. For example, a button might need to talk to various textboxes. Would it be proper to simply construct each widget with a pointer to the container for all of them? Would it be better to give it a pointer to a resource container map where the object can locate another object by string or something? This area has always been very vague to me. I could easily implement everything I want to do if I just constructed objects with pointers to containers of every other object, but that seems wrong. In the case of a widget, would it actually just be more proper if the widget knew nothing about the outside world and instead its action listeners were constructed with resource access?
Thanks
I understand that it is a bad idea but what are some solutions in these situations eg: good design patterns?
Any object should know as little as possible about things outside itself. What you are describing sounds alot like the ani-pattern often referred to as a 'God object'
You get better de-coupling if you use messages/events.
objects with pointers to containers of every other object, but that seems wrong.
And why do you think it is wrong?
Usually you will not just need to send messages but to do something like navigation/enumeration.
For example HTML DOM tree consists of nodes where each node contains [weak] reference to its parent. Without such reference operations like nextSibling() are just impossible.
So answer depends on set of other operations you will want to implement there.
The answer depends on how long the objects might live and how long the pointers might stick around. Anything which might change needs to go through a directory service. If the target's lifetime is short enough, you might even need to have the directory service place a hold on the target.
DON'T DO THAT!
No, seriously, your idea is analogous to the singleton pattern, with the difference that you have just one instance per "name" instead of per type.
You can collect a bunch of bad things about your idea by seeing what's wrong with singletons.
Why would a button in a dialog(?) want to know how many other objects there are in the dialog?
When the button is pressed, it sends a message to its owner. The owner will then have to coordinate the action between the widgets it owns. You don't want to change the code for you OK-button when the dialog gets another listbox, do you?
You could use dependency injection to pass the pointers you need. That way you make the dependencies explicit. http://en.wikipedia.org/wiki/Dependency_injection
This approach gives you a lot of advantages - unit testing is much easier when you don't have global state, god objects and so on. Also when new guy comes to the team, he can see what are the dependencies of a class - you make it explicit in constructor, so no magic like "you must first create this singleton to use that object or it will crash". This approach reduces coupling, thus making reuse easier.
IMO it is not possible to make every class independent of all the others (you ask if it is better when widget does not know anything about outside world). While this removes coupling making code reuse easier it also is very hard to do and leads to lot more coding.
On the other hand it is a bad idea to pursue some ideology "just because" without understanding why. Maybe in your case advantages of OOP are not worth writing additional code. If you can see that you will finish your application much quicker with "god object" then I would say "go for it".
IMO it is not as easy as "never create singletons and god objects". You must decide if additional time spent on passing all the references explicitly pays back in future.
Personally I always choose what is appropriate for program I write. It is not unusual for me to consciously break some OOP rules. Remember there are also other guidelines - I like KISS.

Need refactoring ideas for Arrow Anti-Pattern

I have inherited a monster.
It is masquerading as a .NET 1.1 application processes text files that conform to Healthcare Claim Payment (ANSI 835) standards, but it's a monster. The information being processed relates to healthcare claims, EOBs, and reimbursements. These files consist of records that have an identifier in the first few positions and data fields formatted according to the specs for that type of record. Some record ids are Control Segment ids, which delimit groups of records relating to a particular type of transaction.
To process a file, my little monster reads the first record, determines the kind of transaction that is about to take place, then begins to process other records based on what kind of transaction it is currently processing. To do this, it uses a nested if. Since there are a number of record types, there are a number decisions that need to be made. Each decision involves some processing and 2-3 other decisions that need to be made based on previous decisions. That means the nested if has a lot of nests. That's where my problem lies.
This one nested if is 715 lines long. Yes, that's right. Seven-Hundred-And-Fif-Teen Lines. I'm no code analysis expert, so I downloaded a couple of freeware analysis tools and came up with a McCabe Cyclomatic Complexity rating of 49. They tell me that's a pretty high number. High as in pollen count in the Atlanta area where 100 is the standard for high and the news says "Today's pollen count is 1,523". This is one of the finest examples of the Arrow Anti-Pattern I have ever been priveleged to see. At its highest, the indentation goes 15 tabs deep.
My question is, what methods would you suggest to refactor or restructure such a thing?
I have spent some time searching for ideas, but nothing has given me a good foothold. For example, substituting a guard condition for a level is one method. I have only one of those. One nest down, fourteen to go.
Perhaps there is a design pattern that could be helpful. Would Chain of Command be a way to approach this? Keep in mind that it must stay in .NET 1.1.
Thanks for any and all ideas.
I just had some legacy code at work this week that was similar (although not as dire) as what you are describing.
There is no one thing that will get you out of this. The state machine might be the final form your code takes, but thats not going to help you get there, nor should you decide on such a solution before untangling the mess you already have.
First step I would take is to write a test for the existing code. This test isn't to show that the code is correct but to make sure you have not broken something when you start refactoring. Get a big wad of data to process, feed it to the monster, and get the output. That's your litmus test. if you can do this with a code coverage tool you will see what you test does not cover. If you can, construct some artificial records that will also exercise this code, and repeat. Once you feel you have done what you can with this task, the output data becomes your expected result for your test.
Refactoring should not change the behavior of the code. Remember that. This is why you have known input and known output data sets to validate you are not going to break things. This is your safety net.
Now Refactor!
A couple things I did that i found useful:
Invert if statements
A huge problem I had was just reading the code when I couldn't find the corresponding else statement, I noticed that a lot of the blocks looked like this
if (someCondition)
{
100+ lines of code
{
...
}
}
else
{
simple statement here
}
By inverting the if I could see the simple case and then move onto the more complex block knowing what the other one already did. not a huge change, but helped me in understanding.
Extract Method
I used this a lot.Take some complex multi line block, grok it and shove it aside in it's own method. this allowed me to more easily see where there was code duplication.
Now, hopefully, you haven't broken your code (test still passes right?), and you have more readable and better understood procedural code. Look it's already improved! But that test you wrote earlier isn't really good enough... it only tells you that you a duplicating the functionality (bugs and all) of the original code, and thats only the line you had coverage on as I'm sure you would find blocks of code that you can't figure out how to hit or just cannot ever hit (I've seen both in my work).
Now the big changes where all the big name patterns come into play is when you start looking at how you can refactor this in a proper OO fashion. There is more than one way to skin this cat, and it will involve multiple patterns. Not knowing details about the format of these files you're parsing I can only toss around some helpful suggestions that may or may not be the best solutions.
Refactoring to Patterns is a great book to assist in explainging patterns that are helpful in these situations.
You're trying to eat an elephant, and there's no other way to do it but one bite at a time. Good luck.
A state machine seems like the logical place to start, and using WF if you can swing it (sounds like you can't).
You can still implement one without WF, you just have to do it yourself. However, thinking of it like a state machine from the start will probably give you a better implementation then creating a procedural monster that checks internal state on every action.
Diagram out your states, what causes a transition. The actual code to process a record should be factored out, and called when the state executes (if that particular state requires it).
So State1's execute calls your "read a record", then based on that record transitions to another state.
The next state may read multiple records and call record processing instructions, then transition back to State1.
One thing I do in these cases is to use the 'Composed Method' pattern. See Jeremy Miller's Blog Post on this subject. The basic idea is to use the refactoring tools in your IDE to extract small meaningful methods. Once you've done that, you may be able to further refactor and extract meaningful classes.
I would start with uninhibited use of Extract Method. If you don't have it in your current Visual Studio IDE, you can either get a 3rd-party addin, or load your project in a newer VS. (It'll try to upgrade your project, but you will carefully ignore those changes instead of checking them in.)
You said that you have code indented 15 levels. Start about 1/2-way out, and Extract Method. If you can come up with a good name, use it, but if you can't, extract anyway. Split in half again. You're not going for the ideal structure here; you're trying to break the code in to pieces that will fit in your brain. My brain is not very big, so I'd keep breaking & breaking until it doesn't hurt any more.
As you go, look for any new long methods that seem to be different than the rest; make these in to new classes. Just use a simple class that has only one method for now. Heck, making the method static is fine. Not because you think they're good classes, but because you are so desperate for some organization.
Check in often as you go, so you can checkpoint your work, understand the history later, be ready to do some "real work" without needing to merge, and save your teammates the hassle of hard merging.
Eventually you'll need to go back and make sure the method names are good, that the set of methods you've created make sense, clean up the new classes, etc.
If you have a highly reliable Extract Method tool, you can get away without good automated tests. (I'd trust VS in this, for example.) Otherwise, make sure you're not breaking things, or you'll end up worse than you started: with a program that doesn't work at all.
A pairing partner would be helpful here.
Judging by the description, a state machine might be the best way to deal with it. Have an enum variable to store the current state, and implement the processing as a loop over the records, with a switch or if statements to select the action to take based on the current state and the input data. You can also easily dispatch the work to separate functions based on the state using function pointers, too, if it's getting too bulky.
There was a pretty good blog post about it at Coding Horror. I've only come across this anti-pattern once, and I pretty much just followed his steps.
Sometimes I combine the state pattern with a stack.
It works well for hierarchical structures; a parent element knows what state to push onto the stack to handle a child element, but a child doesn't have to know anything about its parent. In other words, the child doesn't know what the next state is, it simply signals that it is "complete" and gets popped off the stack. This helps to decouple the states from each other by keeping dependencies uni-directional.
It works great for processing XML with a SAX parser (the content handler just pushes and pops states to change its behavior as elements are entered and exited). EDI should lend itself to this approach too.