C# Application Blocks - Static Class and methods - vb.net

I have developed a Data Access Layer for an application that connects to Oracle and SQL databases. I have written a similar class to that provided by Application Blocks here: http://www.sharpdeveloper.net/source/SqlHelper-Source-Code-cs.html.
I am not sure why the methods are static in the link. When I want to perform a CRUD operation I create an instance of the class and then call the appropriate function. Why are the methods static?
VB.NET does not allow for Shared classes (only shared functions). Therefore I was thinking about making all the functions Shared. Before I do this I want to understand why the methods in the link are static.
I have researched this. For example, the following link explains that the methods are static but does not explain why: https://web.archive.org/web/20210304123854/https://www.4guysfromrolla.com/articles/062503-1.aspx.

A couple of big reasons spring to mind.
Simplicity
Everything you need to run that method arrives via the parameter list. Developers don't have to follow any quirks of an instantiated implementation.
Speed.
According to the following link, static method calls are about 4-5 times faster than their instanced equivalent.
http://msdn.microsoft.com/en-us/library/ms973852.aspx

In vb a module behaves as a static class does in c#. Useful when you just want a helper type class with all shared methods.
As a very general rule static/shared methods should be more efficient. As you do not need to instantiate a class to make the same call. So you aren't generating an entire object to do something that you don't need a full object to do. For example, a simple math function.
public shared function AddNumbers(number1 as integer, number2 as integer) as integer
versus something that modifies or accesses object data.
public function AccrueInterest() as integer
which might be something that accesses an interestRate and Balance property on the same object.

Related

Fastest way to invoke method handle fields

I'm generating bytecode roughly equivalent to a class like:
final class MyCls {
final MethodHandle handle1;
final MethodHandle handle2;
// and so on
// This needs to invoke `handle1`, `handle2`, etc. in it somehow
final static myMethod() {
// ...
}
}
The class is fairly long-lived and I wish to call the MethodHandles from inside other methods, with ideally as little overhead as possible. What would be the best way to do this? The two ideas that come to mind are:
Generating explicit MethodHandle.invokeExact calls on the fields
Using invokedynamic somehow (although I think I'd still need the exactInvoker?)
The handles will vary in signatures (although their use-sites should all use the right signatures - I can detect/enforce that at codegen time).
Update
Here's some extra context on what I'm actually doing. The classes represent compiled WASM modules, the method handles are imported functions, and each instance of the class in another instance of the WASM module.
Using MethodHandle to represent imported functions isn't a necessity here - I could also accept something like a java.util.function.Function or maybe even just a virtual method invocation. I do need a MethodHandle representation sometimes, but I could summon one up from a virtual method too (and I could implement a virtual method manually calling a Function too).
The module class instances themselves might end up being stored in static fields but that's not guaranteed. If there is a way to speed up that case, I could recommend users use that.
The simple answer is to just generate invokeExact calls. With the code shape you've shown, there's no need to use invokedynamic (in fact that doesn't seem possible, since invokedynamic calls a bootstrap method which supplies the implementation dynamically).
Since the handles are stored instance fields, they are not seen as constants, and so the calls will be out of line, which adds overhead, as well as missed optimization opportunities due to a lack of inlining.
If you really want this to be as fast as possible, you'd need to generate a new class per combination of method handles you want to use, and store the method handles in static final fields, or in the constant pool (for instance using constant pool patching, or hidden classes + class data + dynamic constants [1]).

How to get created objects (instances) in VB.net

I just did some researches on google but I didn't find an answer to my question.
Is there a way to get the list of the active objects (instances of classes) at runtime?
In my application I need to have single instance classes that needs to be used by different running forms but if I create an instance in the form A, ho do i get control of the same instance in the form B?
Thank you
Actually, your question has 2 parts:
1. How to create single-instance objects.
2. How to have the same object accessible from different forms.
Fortunately for you, there is a solution to both of these problems in one simple and common design pattern called Singleton.
Classes written in the Singleton pattern can only have a single instance, and as you are about to see, as a side effect, this instance is accessible through the entire application.
The simplest way to use the singleton design pattern is this:
Public Class SingletonClass
Private Shared _instance As SingletonClass
Public Shared Function GetSingletonClass() As SingletonClass
If isNothing(_instance) Then
_instance = New SingletonClass()
End If
Return _instance
End Function
Private Sub New()
'' Create the instance here
End Sub
End Class
As you can see, since the constructor is private, it is not accessible from anywhere outside of class SingletonClass, and since class SingletonClass holds a static reference to it's instance, it means that every time you write SingletonClass.GetSingletonClass() in your application you get the same instance.
This design pattern solves both of your problems in a simple, elegant, and well known architecture.
Update
I've recently read a great article about different ways to implement singleton patterns. It turns out that my above specific implementation is not so good, as it is not thread safe. The code examples in this article are C#, but it should be very easy to change them to VB.Net. If you are using .Net 4 or higher, I would recommend going with the 6th version - using .NET 4's Lazy type.
It is both thread safe and lazy loading, two advantages that the implementation I've written doesn't have.

specific questions about scope and property reference in actionscript 3

I've been battling with AS3 for a little while now, and I'm working on a simple application using only actionscript and the FlashDevelop/flex-compiler combo. I've hit a bit of a wall in my fledgling OOP understanding, and I'm wondering whether someone might be able to point me in the right direction. I have genuinely read several books, and spent many hours reading online tutorials etc, but something's just not clicking!
What's baffling me is this: When something is declared 'public', according to what I read, it is therefore available anywhere in the application (and should therfore be used with care!) However, when I try to use public properties and methods in my program, they most definitely are not available anywhere other than from the class/object that instantiated them.
This leads me to conclude that even if objects (of different class) are instantiated from the same (say 'main') class, they are not able to communicate with each other at all, even through public members.
If so, then fair enough, but I've honestly not seen this explained properly anywhere. More to the point, how do different objects communicate with other then? and what does Public actually mean then, if it only works through a direct composition hierarchy? If one has to write applications based only on communication from composer class to it's own objects (and presumably use events for, er, everything else?) - isn't this incredibly restrictive?
I'm sure this is basic OOP stuff, so my apologies in advance!
Any quick tips or links would be massively appreciated.
There are different topics you are covering in your question. Let me clarify:
What does the modifier public mean?
How can instances of the same class communicate to each other?
--
1.
In OOP you organize your code with objects. An object needs to be instantiated to provide its functionality. The place where you instantiate the object can be considered as the "context". In Flash the context might be the first frame, in a pure AS3 movie, it might be the main class, in Flex it could be the main mxml file. In fact, the context is always an object, too. Class modifier of your object public class MyClass tells your context whether it is allowed to instantiate the object or not. If set to internal, the context must live in the same directory as the class of the object. Otherwise it is not allowed to create a new object of the class. Private or protected are not valid class modifiers. Public class ... means that any context may create an object of that class. Next: Not only instantiation is controlled by these modifiers but also the visibility of a type. If set to internal, you cannot use an expression like var obj : InternalType in a context that does not live in the same directory as Internal type.
What about methods and properties? Even if your context is allowed to access a type, certain properties and methods might be restricted internal/protected/private var/method and you perhaps are not able to invoke them.
Why we're having such restrictions? Answer is simple: Differnent developers may develop different parts of the same software. These parts should communicate only over defined interfaces. These interfaces should be as small as possible. The developer therefore declares as much code as possible to be hidden from outside and only the necessary types and properties publicly available.
Don't mix up with modifiers and global properties. The modifier only tells you if a context is allowed to see a type or method. The global variable is available throughout the code. So even if a class is declared to be public, instances of that class do not know each other by default. You can let them know by:
storing the instances in global variables
providing setter such as set obj1(obj1 : OBJ1) : void where each object needs to store the reference in an instance variable
passing the object as method arguments: doSomething(obj1 : OBJ1)
Hope this helps you to more understand OOP. I am happy to answer your follow up questions.
Jens
#Jens answer (disclaimer: I skimmed) appears to be completely correct.
However, I'm not sure it answers your question very directly, so I'll add a bit here.
A public property is a property of that class instance that is available for other objects to use(function: call, variable: access, etc). However, to use them you must have a reference (like a very basic pointer, if that helps?) to that object instance. The object that instantiates (creates, new ...) that object can take that reference by assigning it to a variable of that class type.
// Reference is now stored in 's'
public ExampleClass s = new ExampleClass();
If you'd like to, you do have the option of making a static property, which is available just by knowing the class name. That property will be shared by all instances of that class, and any external class can refer to it (assuming it's public static) by referring to the class name.
A public property is referred to by the reference you stored.
//public property access
s.foo
s.bar(var)
A static property is referred to by the class name.
//static property access
ExampleClass.foo
ExampleClass.bar(var)
Once you've created the instance, and stored the reference, to an object, you can pass it around as you'd like. The below object of type OtherExampleClass would receive the reference to 's' in its constructor, and would have to store it in a local variable of its own to keep the reference.
public OtherExampleClass s2 = new OtherExampleClass(s);

Use of Constructors - Odd Doubt

I'm reading about constructors,
When an object is instantiated for a class, c'tors (if explicitly written or a default one) are the starting points for execution. My doubts are
is a c'tor more like the main() in
C
Yes i understand the point that you
can set all the default values using
c'tor. I can also emulate the behavior
by writing a custom method. Then why a c'tor?
Example:
//The code below is written in C#.
public class Manipulate
{
public static int Main(string[] args) {
Provide provide = new Provide();
provide.Number(8);
provide.Square();
Console.ReadKey();
return 0;
}
}
public class Provide {
uint num;
public void Number(uint number)
{
num = number;
}
public void Square()
{
num *= num;
Console.WriteLine("{0}", num);
}
}
Am learning to program independently, so I'm depending on programming communities, can you also suggest me a good OOP's resource to get a better understanding. If am off topic please excuse me.
Head First OOA&D will be a good start.
Dont you feel calling a function for setting each and every member variable of your class is a bit overhead.
With a constructor you can initialize all your member variables at one go. Isnt this reason enough for you to have constructors.
Constructor and Destructor functionality may be emulated using regular methods. However, what makes those two type of methods unique is that the language treats them in a special way.
They are automatically called when an object is created or destroyed. This presents a uniform means to handle the most delicate operations that must take place during those two critical periods of an object's lifetime. It takes out the possibility of an end user of a class forgetting to call those at the appropriate times.
Furthermore, advanced OO features such as inheritance require that uniformity to even work.
First of all, most answers will depend at least a bit on the language you're using. Reasons that make great sense in one language don't necessarily have direct analogs in other languages. Just for example, in C++ there are quite a few situations where temporary objects are created automatically. The ctor is invoked as part of that process, but for most practical purposes it's impossible to explicitly invoke other member functions in the process. That doesn't necessarily apply to other OO languages though -- some won't create temporary objects implicitly at all.
Generally you should do all your initialization in the constructor. The constructor is the first thing called when an instance of your class is created, so you should setup any defaults here.
I think a good way to learn is comparing OOP between languages, it's like seeing the same picture from diferent angles.
Googling a while:
java (I prefer this, it's simple and full)- http://java.sun.com/docs/books/tutorial/java/concepts/
python - http://www.devshed.com/c/a/Python/Object-Oriented-Programming-With-Python-part-1/
c# - http://cplus.about.com/od/learnc/ss/csharpclasses.htm
Why constructors?
The main diference between a simple function (that also could have functions inside) and an Object, is the way that an Object can be hosted inside a "variable", with all it functions inside, and that also can react completly diferent to an other "variable" with the same kind of "object" inside. The way to make them have the same structure with diferent behaviours depends on the arguments you gave to the class.
So here's a lazy example:
car() is now a class.
c1 = car()
c2 = car()
¿c1 is exactly c2? Yes.
c1 = car(volkswagen)
c2 = car(lamborghini)
C1 has the same functionalities than C2, but they are completly diferent kinds of car()
Variables volkswagen and lamborghini were passed directly to the constructor.
Why a -constructor-? why not any other function? The answer is: order.
That's my best shot, man, for this late hours. I hope i've helped somehow.
You can't emulate the constructor in a custom method as the custom method is not called when the object is created. Only the constructor is called. Well, of course you can then call your custom method after you create the object, but this is not convention and other people using your object will not know to do this.
A constructor is just a convention that is agreed upon as a way to setup your object once it is created.
One of the reasons we need constructor is 'encapsulation',the code do something initialization must invisible
You also can't force the passing of variables without using a constructor. If you only want to instantiate an object if you have say an int to pass to it, you can set the default constructor as private, and make your constructor take an int. This way, it's impossible to create an object of that class without having it take an int.
Sub-objects will be initialized in the constructor. In languages like C++, where sub-objects exist within the containing object (instead of as separate objects connected via pointers or handles), the constructor is your only chance to pass parameters to sub-object constructors. Even in Java and C#, any base class is directly contained, so parameters to its constructor must be provided by your constructor.
Lastly, any constant (or in C#, readonly) member variables can only be set from the constructor. Even helper functions called from the constructor are unable to change them.

Making Class methods instead of Instance Methods in VB.NET

I am not sure how clear my question is by the title, but I am trying to make Class methods instead of Instance methods in Visual Basic that way I don't have to waste memory and code creating temporary objects to execute methods that don't need instance variables.
I am not sure if you can do that in VB but I know you can in Objective-C by using either a "+" or "-" sign in front of the method declaration. And in C++ (at least I think, I can't remember) you put the static keyword or const keyword in front of the function.
How would I do this in VB if it is possible? Or should I just make a separate set of functions that are not members of a class?
If you are looking to define class methods in VB.Net you just need to add the Shared modifier to the function
Class C1
Public Shared Function DoSomething() As String
' Insert code here
End Function
End Class
As to whether or not you should use a class method over an instance method to avoid allocations. I think you're using the wrong reasoning pattern here. I would start simply with design the class to have the most natural and straight forward API. Then after that process if a profiler shows that allocation of small objects is a problem update the API to account for this.
Making an API design decision for performance reasons without using a profiler will almost surely lead to wasted effort.
You want to create a Shared method in VB.net.