I am writing a couple of endpoints manages a scheduler, for that I use quartzite.
I would like to have the scheduler instance visible across schedule, reschedule and unschedule functions, the easiest way is to create an atom but I guess it's not the best way to keep the code from smelling.
I would like to know if there's an idiomatic way to handle state in clojure?
A common approach is to use a library like Component or Integrant to manage the lifecycle and dependency injection of state.
In those cases you tend to end up with a single atom containing a system of interrelated state.
In my personal experience I use Quartzite and Component - I have a scheduler component that is available to start/stop/schedule etc.
I prefer Integrant these days and will slowly move my projects from Component.
I believe, it's really OK to have an atom in your code, but store as little data in it as possible, only those ones that are really needed to be changed.
You cannot avoid having state completely, and atoms are great for that.
Related
I need to design a application registry S/W component using C++. Basically, this needs to support addition and deletion of key/values. Dynamic updates need to be supported (for example, when a new application get installed).
Is there a design pattern which closely matches the given problem?
Though I have formulated a rough sketch of the APIs this component needs to support, it would be helpful to have a look at alternative (perhaps better) ways of design.
If there are some typical problems associated with registry design (may be some thread issues which I might have overlooked), I want to make sure I have circumvented those.
Is there a design pattern which closely matches the given problem?
You are probably looking at more than one: A proxy for the entire registry, iterator etc. comes to mind.
If there are some typical problems associated with registry design
You will probably need transactional semantics. Rollback too!
Do you need to save snapshots from time to time? Then you will need an archiving module.
Synchronization: Multiple writes to the registry need to be taken care of.
Basically, I'm unable to find any good articles for developing your own GUI, that deal with good practices, the basic structure, event bubbling, tips and avoiding all the usual pitfalls. I'm specifically not interested on how to build some proof-of-concept GUI in 5 minutes that just barely works... nor am I interested in building the next future GUI.
The purpose is to build a reasonably capable GUI to be used for tools for a game, however they will exist within the game itself so I don't want to use existing large scale GUIs, and I find most game GUIs to be rather bloated for what I need. And I enjoy the experience of doing it myself.
I have done a GUI in the past which worked very well to a point, however, due to some bad design decisions and inexperience it could only do so much (and was built in Flash so it got a lot of stuff for free). So I would like to really understand the basics this time.
A few tips -
1) Pick your style the UI will work - will it be stateless? If yes, how are you going to handle the events appropriately? In case it'll be stateless, you'll maybe have to re-evaluate your UI user code twice in order to get up to date event changes from user side. If your UIs store state, then you won't have to care about handling events, but it'll limit your UIs when it comes to rapid mutations and rebuilds.
2) Do not rely on the OO too much, virtual methods are not the fastest thing in the world so use them with care; having some sort of inheritance based structure might help though. Beware of dynamic_cast and RTTI if you use objects; they will slow you down. Instead, set up an enum, get_type() method for every widget class, and do manual checks for castability.
3) Try to separate the looks and the UI logic/layout.
4) If you want dynamic windows, layouts etc. then you'll have to handle aligning, clamping, positions etc. and their updates. If you want just statically positioned widgets, it'll make it much easier.
5) Do not overdesign, you won't benefit from that.
There is not really anything too specific I tell you; having some concrete question would help, maybe?
Take a look at the docs for existing GUI libraries. That should give you details on proven designs to handle the issues you've run into.
You might want to start with one you're familiar with, but one that I think is designed quite well is AppKit. Its API is Obj-C so it would require some adjustment if you wanted to copy it, but the docs give all kinds of details about how objects interact to, e.g. handle events, and how layout constraints work, which should be directly applicable to designing an OO GUI in most any language.
I've got lots of problems with project i am currently working on. The project is more than 10 years old and it was based on one of those commercial C++ frameworks which were very populary in the 90's. The problem is with statecharts. The framework provides quite common implementation of state pattern. Each state is a separate class, with action on entry, action in state etc. There is a switch which sets current state according to received events.
Devil is hidden in details. That project is enormous. It's something about 2000 KLOC. There is definitely too much statecharts (i've seen "for" loops implemented using statecharts). What's more ... framework allows to embed statechart in another statechart so there are many statecherts with seven or even more levels of nesting. Because statecharts run in different threads, and it's possible to send events between statecharts we have lots of synchronization problems (and big mess in interfaces).
I must admit that scale of this problem is overwhelming and I don't know how to touch it. My first idea was to remove as much code as I can from statecharts and put it into separate classes. Then delegate these classes from statechart to do a job. But in result we will have many separate functions, which logically don't have any specific functionality and any change in statechart architecture will need also a change of that classes and functions.
So I asking for help:
Do you know any books/articles/magic artefacts which can help me to fix this ? I would like to at least separate as much code as I can from statechart without introducing any hidden dependencies and keep separated code maintainable, testable and reusable.
If you have any suggestion how to handle this, please let me know.
The statechart pattern is intended to be used specifically to remove switch statements, so this sounds like a horrid abuse. Additionally, states should only change on asynchronous events. If you are processing an event and you change through multiple states (or for loop, etc.), then this is also a horrid abuse of the pattern.
I would start from these two points, as they will solve much of your concurrency issues just fixing them up. What you need to determine is:
What are your external, asynchronous events to the system? These are the only things that should be determining state transitions, not things that happen during event processing. An event may cause 0 or 1 state transitions. Once you have a list of these state transitions, you can reconstruct the actual states of your system. If you are aware of UML State diagrams, this would be a perfect time to sketch one up in a charting program, not just for yourself (though it will help you immensely), but also for everyone in the future that has to return to the project. As you have learned, this happens.
Now that you know what are really states, list what are states in the code that shouldn't be. This usually indicates that something can be "functionally decomposed". Instead of a state object for each of these, likely all that is needed is a separate function. This will cut down on a lot of the overhead of state objects and should clean up the code immensely.
Now it's time to tackle those horrendous switch statements you mentioned. If they were truly based on state, you shouldn't need one at all. Instead, you should be able to call the state machine directly.
Something like:
myStateMachine->myEvent();
and it should work without any switch. But notice, this may be the case even for some of those objects that don't work across asynchronous events. This is also an indication of where you may just use inheritance to get the same effect. If you have:
switch (someTypeIdentifier)
{
case type1:
doSomething();
break;
case type2:
doSomethingElse();
break;
}
usually the correct OOP method to do is to create two actual types Type1, Type2, both derived from an abstract base TypeBase, with a virtual method doSomething() that does what you need. The reason this is useful is because it means you can "close" the handling (in the meaning of the Open/Closed Principle), and still extend the functionality by adding new derived types as needed (leaving it open to extension). This saves bugs like crazy because it gets developers hands out of those switch statements, which can get quite ugly and convoluted, instead encapsulating each separate behavior in separate classes.
4 - Now look to fix up your thread issues. Identify all objects used from multiple threads. Make a list. Now, how are these used? Are some of them always used together? Start making groups. The goal here is to find the level of encapsulation that best works for these objects, separate the objects into individual classes that control their own synchronisation, figure out the atomic level of actual "transactions" for the objects, and make methods of the classes that expose those meaningful transactions, wrapped behind the scenes with the appropriate mutexes, condition variables, etc.
You might be saying "that sounds like a lot of work! Why do all that instead of just writing it all over myself?" Good question! :) The reason is actually straightforward: if you are going to do it all by yourself, those are the steps you should be doing anyway. You should be identifying your states, your dynamic polymorphism, and getting a handle on the multithreaded transactions. But, if you start with the existing code, you also have all of those unspoken business rules that were never documented and may cause all sorts of unexpected bugs down the line. You don't have to bring everything over - if you suspect it's a bug, discuss the logic with the people who have worked with the system in the past (if available), QA, or whoever might identify bugs, and see if it really should be carried over. But you need to actually evaluate what the bugs are either way, or you may not code something that actually needed coding.
In the end, this is a manual process that is a part of software engineering. There are CASE tools that can help draw up the state diagrams and even publish them to code, there are refactoring tools, like those found in many IDEs, that can help move code between functions and classes, and similar tools which can help identify threading needs. However, those things shouldn't be picked up for a single project. They need to be learned throughout your career, picking them up and learning them more deeply over years of work, as they are a part of being a software engineer. They don't do it for you. You still need to know the whys and hows, and they just help get it done more efficiently.
Statecharts (including nested Statecharts) are a powerful way to specify, understand and even simulate/validate complex control flow. But to gain the benefit, you need the statechart model in a suitable tool (I used Statemate way back in the day, not sure if it's still available), plus a reliable mapping from the chart to the code (Statemate used to generate the code) - then you can forget about the state management code (mostly)! In your situation, if you don't have the model, I would try to reverse one from the code - as Ira says, chances are high that the original developers had a model in some form, and you may find the code making a lot of sense as the model emerges. If this works out, you will have a really good spec/model of the code which should make future code edits much easier (even if you don't want to go to automatic code generation, and maintain the code/model mapping manually (but you'll need to be meticulous!!))
Sounds to me like your best bet is (gulp!) likely to start from scratch if it's as horrifically broken as you make out. Is there any documentation? Could you begin to build some saner software based on the docs?
If a complete re-write isn't an option (and they never are in my experience) I'd try some of the following:
If you don't already have it, draw an architectural picture of the whole system. Sketch out how all the bits are supposed to work together and that will help you break the system down into potentially manageable / testable parts.
Do you have any kind of requirements or testing plan in place? If not, can you write one and start to put unit tests in place for the various chunks of code / functionality which exist already? If you can do that, you can start to refactor things without breaking as much of whatever does currently work.
Once you've broken things down a bit, start building your unit tests into integration tests which pull together more of the functionality.
I've not read them myself, but I've heard good things about these books which may have some advice you can use:
Refactoring: Improving the Design of Existing Code (Object Technology Series).
Working Effectively with Legacy Code (Robert C. Martin)
Good luck! :-)
Firstly, I am an absolute beginner in programming, so don't make fun of me too much.
The only thing that I have seen signals used for are GUI toolkits, and GUI toolkits all come with their own signaling. So, can Boost:Signals even be used with these GUI toolkits? Would this be a good idea? What other applications do signals have?
Signals is an event messaging implementation, much like Smalltalk/Objective C Messages or Events in various other (e.g. C#) lanugages.
You can use them for a wide variety of tasks, take a look at the Observer Pattern
Why would you use the Observer Pattern?
The benefits are largely organisational, when you work with large applications it's is important to apply patterns of reuse that help maintain development team coherence.
When the implementation of a particular pattern becomes de facto (or close to) it's especially useful because it means that lead up times for new team members are likely to be expedited, not only if they have used the implementation before, but also because the popularity of the implementation will mean that there are widespread resources, and documentation available to speed learning.
From a pure code perspective, ALL patterns appear as bloat, but when you begin to understand that upwards of 60% of the costs involved in software development are in maintenance life-cycle, it is well worth the additional code to gain coherence.
The other benefit is to aid in software reuse, depending on the style of implementation, the Observer Pattern can assist in modularising and decoupling classes from one another. I would suggest that this is also an organisational benefit, in as much that different teams can build components more easily, or simply because components are easier to replace.
Just my two cents, signals are not only used in (or for) GUI toolkits. They are used in contexts where you want to decouple the producer of a datum with the receiver of it (the observer pattern mentioned above, for example). If you mix that idea with threads, you can implement actors easily, an interesting pattern for concurrent tasks (Erlang and Scala use actors, for instance).
One possible use would be in the implementation of a GUI toolkit. You'd basically set up the wiring to get messages (or whatever they happen to be called) from the native system to produce signals. From there, the code for routing and handling signals can be (at least somewhat) portable.
In addition to the Observer pattern that others have mentioned, anytime you find yourself having to write a callback function, so that one class can notify another that something has happened, then you can use Signals and Slots instead. The great advantage over callbacks is that it takes care of lots of the boiler plate code to add and remove the callback function, and deals with automatically disconnecting when either the caller or the callee go out of scope.
Callbacks are really just an instance of the Observer pattern though.
i'm developing a simple simulation with OpenGL and this simulation has some global constants that are changed by the user during the simulation execution. I would like to know if the Singleton design pattern is the best way to work as a temporary, execution time, "configuration repository"
A singleton is probably the best option if you need to keep these settings truly "global".
However, for simulation purposes, I'd consider whether you can design your algorithms to pass a reference to a configuration instance, instead. This would make it much easier to store configurations per simulation, and eventually allow you to process multiple simulations with separate configurations concurrently, if requirements change.
Often, trying to avoid global state is a better, long term approach.
I think in the past I've used namespaces for this purpose, not singleton classes, but this should work too (probably even better).
Of course, if you want to be able to change the configuration without recompiling, you might want to move everything to a separate properties file (or XML or YAML or CSV or whatever you prefer) and then load it at application start up. Then you WOULD need a "config" class to store all the values in a hashmap (or something like that).