VB6 Is it possible to implement the Singleton design pattern? - vb6

Within VB6 is it possible to implement the Singleton design pattern?
Currently the legacy system I work on has a large about of IO performed by multiple instances of a particular class. It is desirable to clean up all these instances and have the IO performed by one instance only. This would allow us to add meaningful logging and monitoring to the IO routines.

There are so many ways to do this, and it depends if this is a multi-project application with different dlls or a single project.
If it is single project and there is a large amount of code that you are worrying about chaning/breaking then I suggest the following:
Given a class clsIOProvider that is instantiated all over the place, create a module modIOProvider in the same project.
For each method / property defined in clsIOProvider, create the same set of methods in modIOProvider.
The implementation of those methods, as well as the instance data of the class, should be cloned from clsIOProvider to modIOProvider.
All methods and properties in clsIOProvider should be chnaged to forward to the implementation in modIOProvider. The class should no longer have an instance data.
(Optional) If the class requires the use of the constructor and destructor (Initialize/Terminate), forward those to modIOProvider as well. Add a single instnace counter within modIOProvider to track the number of instances. Run your initialzation code when the instance counter goes from 0 to 1, and your termination code when the instance counter goes from 1 to 0.
The advantage of this is that you do not have to change the coe in the scores of places that are utilizeing the clsIOProvider class. They are happily unaware that the object is now effectively a singleton.
If coding a proejct from scratch I would do this a bit differently, but as a refactoring appraoch wahat I've outlined should work well.

It's easy enough to only create and use one instance of an object. How you do it depends on your code what it does and where it's called from.
In one process, you can just have a single variable in a global module with an instance, maybe with a factory function that creates it on first use.
If it's shared by multiple process, it complicates things, but can be done with an ActiveX EXE and the Running Object Table.

Related

What's the best practice for NSPersistentContainer newBackgroundContext?

I'm familiarizing myself with NSPersistentContainer. I wonder if it's better to spawn an instance of the private context with newBackgroundContext every time I need to insert/fetch some entities in the background or create one private context, keep it and use for all background tasks through the lifetime of the app.
The documentation also offers convenience method performBackgroundTask. Just trying to figure out the best practice here.
I generally recommend one of two approaches. (There are other setups that work, but these are two that I have used, and tested and would recommend.)
The Simple Way
You read from the viewContext and you write to the viewContext and only use the main thread. This is the simplest approach and avoid a lot of the multithread issues that are common with core-data. The problem is that the disk access is happening on the main thread and if you are doing a lot of it it could slow down your app.
This approach is suitable for small lightweight application. Any app that has less than a few thousand total entities and no bulk changes at once would be a good candidate for this. A simple todo list, would be a good example.
The Complex Way
The complex way is to only read from the viewContext on the main thread and do all your writing using performBackgroundTask inside a serial queue. Every block inside the performBackgroundTask refetches any managedObjects that it needs (using objectIds) and all managedObjects that it creates are discarded at the end of the block. Each performBackgroundTask is transactional and saveContext is called at end of the block. A fuller description can be found here: NSPersistentContainer concurrency for saving to core data
This is a robust and functional core-data setup that can manage data at any reasonable scale.
The problem is that you much always make sure that the managedObjects are from the context you expect and are accessed on the correct thread. You also need a serial queue to make sure you don't get write conflicts. And you often need to use fetchedResultsController to make sure entities are not deleted while you are holding pointers to them.

Is it bad to have many global functions?

I'm relatively new to software development, and I'm on my way to completing my first app for the iPhone.
While learning Swift, I learned that I could add functions outside the class definition, and have it accessible across all views. After a while, I found myself making many global functions for setting app preferences (registering defaults, UIAppearance, etc).
Is this bad practice? The only alternate way I could think of was creating a custom class to encapsulate them, but then the class itself wouldn't serve any purpose and I'd have to think of ways to passing it around views.
Global functions: good (IMHO anyway, though some disagree)
Global state: bad (fairly universally agreed upon)
By which I mean, it’s probably a good practice to break up your code to create lots of small utility functions, to make them general, and to re-use them. So long as they are “pure functions”
For example, suppose you find yourself checking if all the entries in an array have a certain property. You might write a for loop over the array checking them. You might even re-use the standard reduce to do it. Or you could write a re-useable function, all, that takes a closure that checks an element, and runs it against every element in the array. It’s nice and clear when you’re reading code that goes let allAboveGround = all(sprites) { $0.position.y > 0 } rather than a for…in loop that does the same thing. You can also write a separate unit test specifically for your all function, and be confident it works correctly, rather than a much more involved test for a function that includes embedded in it a version of all amongst other business logic.
Breaking up your code into smaller functions can also help avoid needing to use var so much. For example, in the above example you would probably need a var to track the result of your looping but the result of the all function can be assigned using let. Favoring immutable variables declared with let can help make your program easier to reason about and debug.
What you shouldn’t do, as #drewag points out in his answer, is write functions that change global variables (or access singletons which amount to the same thing). Any global function you write should operate only on their inputs and produce the exact same results every time regardless of when they are called. Global functions that mutate global state (i.e. make changes to global variables (or change values of variables passed to them as arguments by reference) can be incredibly confusing to debug due to unexpected side-effects they might cause.
There is one downside to writing pure global functions,* which is that you end up “polluting the namespace” – that is, you have all these functions lying around that might have specific relevance to a particular part of your program, but accessible everywhere. To be honest, for a medium-sized application, with well-written generic functions named sensibly, this is probably not an issue. If a function is purely of use to a specific struct or class, maybe make it a static method. If your project really is getting too big, you could perhaps factor out your most general functions into a separate framework, though this is quite a big overhead/learning exercise (and Swift frameworks aren’t entirely fully-baked yet), so if you are just starting out so I’d suggest leaving this for now until you get more confident.
* edit: ok two downsides – member functions are more discoverable (via autocomplete when you hit .)
Updated after discussion with #AirspeedVelocity
Global functions can be ok and they really aren't much different than having type methods or even instance methods on a custom type that is not actually intended to contain state.
The entire thing comes down mostly to personal preference. Here are some pros and cons.
Cons:
They sometimes can cause unintended side effects. That is they can change some global state that you or the caller forgets about causing hard to track down bugs. As long as you are careful about not using global variables and ensure that your function always returns the same result with the same input regardless of the state of the rest of the system, you can mostly ignore this con.
They make code that uses them difficult to test which is important once you start unit testing (which is a definite good policy in most circumstances). It is hard to test because you can't mock out the implementation of a global function easily. For example, to change the value of a global setting. Instead your test will start to depend on your other class that sets this global setting. Being able to inject a setting into your class instead of having to fake out a global function is generally preferable.
They sometimes hint at poor code organization. All of your code should be separable into small, single purpose, logical units. This ensures your code will remain understandable as your code base grows in size and age. The exception to this is truly universal functions that have very high level and reusable concepts. For example, a function that lets you test all of the elements in a sequence. You can also still separate global functions into logical units by separating them into well named files.
Pros:
High level global functions can be very easy to test. However, you cannot ignore the need to still test their logic where they are used because your unit test should not be written with knowledge of how your code is actually implemented.
Easily accessible. It can often be a pain to inject many types into another class (pass objects into an initializer and probably store it as a property). Global functions can often remove this boiler plate code (even if it has the trade off of being less flexible and less testable).
In the end, every code architecture decision is a balance of trade offs each time you go to use it.
I have a Framework.swift that contains a set of common global functions like local(str:String) to get rid of the 2nd parameter from NSLocalize. Also there are a number of alert functions internally using local and with varying number of parameters which makes use of NSAlert as modal dialogs more easy.
So for that purpose global functions are good. They are bad habit when it comes to information hiding where you would expose internal class knowledge to some global functionality.

ColdFusion memory usage for Components

I am creating a site using VMC and using beans to transfer the data from the Model to the Controller/Views.
I plan to implement some basic and very simple caching that will store the beans in a simple struct if they have not changed (as usage grows, we will implement a better caching system around ver 1.3).
So the question goes to what goes in our bean.
One type of bean would only hold the basic data and would rely on some outside service to do the rest of the work (contacting the DAO to get the query, parsing the query to load the bean values). This is the "anemic bean" model as I have been told repeatedly by a co-worker :-).
Another type of bean would be more self-contained. It would know where the DAO is so would call the DAO directly to get the data query. It would contain necessary functions to parse out the query and set the properties. It would basically combine much of the "service" layer with the bean, leaving the direct database in the DAO layer.
Of course, to the controller/views, both beans would look and act the same.
But the question is memory and how ColdFusion/Java deals with it.
With the anemic model, the bean would just have enough memory to hold the property variables with just a touch more to let it point to the Service when it needs to.
With the heavier functions in the second type bean, would it take up more memory in the cache??? Would each copy of the bean have a full copy of the methods?
I tend to think that the second model would not have much more memory since they would "share" the methods and would only need memory for the property variables.
IMHO the second method would simplify the codebase, since the code the bean needs would be closer to the bean rather than scattered between the DAO and Services. And it would reduce simple functions in the Service that merely pass along calls to the DAO of the bean could go directly to the DAO when it needed it...
Does the question make sense?? Or at least how I am asking it?
All the memory management is handed at Java level, so it follows the same rules. In Java the only "new" memory that's allocated when an object instance is created is for its member variables; there is not memory foot print for the methods of the component/class itself: that stuff is only stored in memory once, with a reference back to it.
One possible consideration is that each method of a CFC is compiled as its own discrete class (why? I don't know), so each method is its own class. This will perhaps mean a slightly larger memory footprint for CFC usage compared to Java class usage, but this will still not be something that scales with object-instantiation: each instance of an object will still just consume memory for its member variables, not the methods of the CFC that defines the object.
all cfm pages are compiled to memory by default, a CFC needs to implicitly be stored in memory (application scope for example) in order to avoid instantiating it each time, however you do it requires the same memory for the same component, any additional usage will depend on any data you are storing within your component or bean.
Have you had a look at ColdSpring ?

What does it mean when someone says that the module has both behavior and state?

As I understand I got a code review that my module has behavior and state at the same time, what does it mean anyway ?
Isn't that the whole point of object oriented programming, that instead of operating on data directly with logical circuitry using functions. We choose to operate on these closed black-boxes (encapsulation) using a set of neatly designed keys, switches and gears.
Wouldn't such a scheme naturally contain data(state) and logic(behavior) at the same time ?
By module I mean : a real Ruby module.
I designed something like this : How to design an application keeping SOLID principles and Design Patterns in mind
and implemented the commands in a module which I used to mixin.
Whatever you are referring to, be it an object defined by a class (or type), a module, or anything else with code in it, state is data that is persisted over multiple calls to the thing. If it "remembers" anything between one execution and the next, then it has state.
Behavior, otoh, is code that manipulates or processes that state-data, or non-state data that is used only during a single execution of the code, (like parameter values passed to a function). Methods, subroutines or functions, anything that changes or does something is behavior.
Most classes, types, or whatever, have both data (state) and behavior, but....
Some classes or types are designed simply to carry data around. They are referred to as Data Transfer objects or DTOs, or Plain Old Container Objects (POCOs). They only have state, and, generally, have little or no behavior.
Other times, a class or type is constructed to hold general utility functions, (like a Math Library). It will not maintain or keep any state between the many times it is called to perform one of its utilities. The only data used in it is data passed in as parameters for each call to the library function, and that data is discarded when the routine is finished. It has behavior. but no state.
You're right in your thinking that OOP encapsulates the ideas of both behaviour and state and mixes the two things together, but from the wording of your question, I'm wondering if you have written a ruby module (mixin, whatever you want to call it) that is stateful, such that there is the potential for state leakage across multiple uses of the same module.
Without seeing the code in question I can't really give you a full answer.
In Object-Oriented terminology, an object is said to have state when it encapsulates data (attributes, properties) and is said to have behavior when it offers operations (methods, procedures, functions) that operate (create, delete, modify, make calculations) on the data.
The same concepts can be extrapolated to a ruby module, it has "state" if it defined data accessible within the module, and it has "behavior" in the form of operations provided which operate on the data.

Performance of using static methods vs instantiating the class containing the methods

I'm working on a project in C#. The previous programmer didn't know object oriented programming, so most of the code is in huge files (we're talking around 4-5000 lines) spread over tens and sometimes hundreds of methods, but only one class. Refactoring such a project is a huge undertaking, and so I've semi-learned to live with it for now.
Whenever a method is used in one of the code files, the class is instantiated and then the method is called on the object instance.
I'm wondering whether there are any noticeable performance penalties in doing it this way? Should I make all the methods static "for now" and, most importantly, will the application benefit from it in any way?
From here, a static call is 4 to 5 times faster than constructing an instance every time you call an instance method. However, we're still only talking about tens of nanoseconds per call, so you're unlikely to notice any benefit unless you have really tight loops calling a method millions of times, and you could get the same benefit by constructing a single instance outside that loop and reusing it.
Since you'd have to change every call site to use the newly static method, you're probably better spending your time on gradually refactoring.
I have dealt with a similar problem where i work. The programmer before me created 1 controller class where all the BLL functions were dumped.
We are redesigning the system now and have created many Controller classes depending on what they are supposed to control e.g.
UserController, GeographyController, ShoppingController...
Inside each controller class they have static methods which make calls to cache or the DAL using the singleton pattern.
This has given us 2 main advantages. It is slightly faster(around 2-3 times faster but were talking nanoseconds here ;P). The other is that the code is much cleaner
i.e
ShoppingController.ListPaymentMethods()
instead of
new ShoppingController().ListPaymentMethods()
I think it makes sense to use static methods or classes if the class doesn't maintain any state.
It depends on what else that object contains -- if the "object" is just a bunch of functions then it's probably not the end of the world. But if the object contains a bunch of other objects, then instantiating it is gonna call all their constructors (and destructors, when it's deleted) and you may get memory fragmentation and so on.
That said, it doesn't sound like performance is your biggest problem right now.
You have to determine the goals of the rewrite. If you want to have nice testable, extendable & maintainable OO code then you could try to use objects and their instance methods. After all this is Object Oriented programing we're talking about here, not Class Oriented programming.
It is very straightforward to fake and/or mock objects when you define classes that implement interfaces and you execute instance methods. This makes thorough unit testing quick and effective.
Also, if you are to follow good OO principles (see SOLID at http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29 ) and/or use design patterns you will certainly be doing a lot of instance based, interface based development, and not using many static methods.
As for this suggestion:
It seems silly to me to create an object JUST so you can call a method which
seemingly has no side effects on the object (from your description i assume this).
I see this a lot in dot net shops and to me this violates encapsulation, a key OO concept. I should not be able to tell whether a method has side effects by whether or not the method is static. As well as breaking encapsulation this means that you will need to be changing methods from static to instance if/when you modify them to have side effects. I suggest you read up on the Open/Closed principle for this one and see how the suggested approach, quoted above, works with that in mind.
Remember that old chestnut, 'premature optimization is the root of all evil'. I think in this case this means don't jump through hoops using inappropriate techniques (i.e. Class Oriented programming) until you know you have a performance issue. Even then debug the issue and look for the most appropriate.
Static methods are a lot faster and uses a lot less memory. There is this misconception that it's just a little faster. It's a little faster as long as you don't put it on loops. BTW, some loops look small but really aren't because the method call containing the loop is also another loop. You can tell the difference in code that performs rendering functions. A lot less memory is unfortunately true in many cases. An instance allows easy sharing of information with sister methods. A static method will ask for the information when he needs it.
But like in driving cars, speed brings responsibility. Static methods usually have more parameters than their instance counterpart. Because an instance would take care of caching shared variables, your instance methods will look prettier.
ShapeUtils.DrawCircle(stroke, pen, origin, radius);
ShapeUtils.DrawSquare(stroke, pen, x, y, width, length);
VS
ShapeUtils utils = new ShapeUtils(stroke,pen);
util.DrawCircle(origin,radius);
util.DrawSquare(x,y,width,length);
In this case, whenever the instance variables are used by all methods most of the time, instance methods are pretty worth it. Instances are NOT ABOUT STATE, it's about SHARING although COMMON STATE is a natural form of SHARING, they are NOT THE SAME. General rule of thumb is this: if the method is tightly coupled with other methods --- they love each other so much that they when one is called, the other needs to be called too and they probably share the same cup of water---, it should be made instance. To translate static methods into instance methods is not that hard. You only need to take the shared parameters and put them as instance variables. The other way around is harder.
Or you can make a proxy class that will bridge the static methods. While it may seem to be more inefficient in theory, practice tells a different story. This is because whenever you need to call a DrawSquare once (or in a loop), you go straight to the static method. But whenever you are gonna use it over and over along with DrawCircle, you are gonna use the instance proxy. An example is the System.IO classes FileInfo (instance) vs File (static).
Static Methods are testable. In fact, even more testable than instance once. Method GetSum(x,y) would be very testable to not just unit test but load test, integrated test and usage test. Instance methods are good for units tests but horrible for every other tests (which matters more than units tests BTW) that is why we get so many bugs these days. The thing that makes ALL Methods untestable are parameters that don't make sense like (Sender s, EventArgs e) or global state like DateTime.Now. In fact, static methods are so good at testability that you see less bugs in C code of a new Linux distro than your average OO programmer (he's full of s*** I know).
I think you've partially answered this question in the way you asked it: are there any noticeable performance penalties in the code that you have?
If the penalties aren't noticeable, you needn't necessarily do anything at all. (Though it goes without saying the codebase would benefit dramtically from a gradual refactor into a respectable OO model).
I guess what I'm saying is, a performance problem is only a problem when you notice that it's a problem.
It seems silly to me to create an object JUST so you can call a method which seemingly has no side effects on the object (from your description i assume this). It seems to me that a better compromise would be to have several global objects and just use those. That way you can put the variables that normally would be global into the appropriate classes so that they have slightly smaller scope.
From there you can slowly move the scope of these objects to be smaller and smaller until you have a decent OOP design.
Then again, the approach that I would probably use is different ;).
Personally, I would likely focus on structures and the functions which operate on them and try to convert these into classes with members little by little.
As for the performance aspect of the question, static methods should be slightly faster (but not much) since they don't involve constructing, passing and deconstructing an object.
It's not valid in PHP,
Object Method is faster :
http://www.vanylla.it/tests/static-method-vs-object.php

Resources