Should static reference type variable be avoided? [duplicate] - vb.net

This question already has answers here:
Are static local variables bad practice?
(2 answers)
Closed 8 years ago.
Consider the following functionally two code snippets in a single-threaded environment. Assuming there are no other methods in Foo I believe these are functionally identical.
Class Foo
Private _Bar As Bar
Public ReadOnly Property GetBar As Bar
Get
If IsNothing(_Bar) Then
_Bar = New Bar
End If
Return _Bar
End Get
End Property
End Class
And
Class Foo
Public ReadOnly Property GetBar2 As Bar
Get
Static _Bar As New Bar
Return _Bar
End Get
End Property
End Class
Today I was challenged on code following the 2nd method because "the New will be called each time". I already know that is false, but the primary objection was with regards to the use of Static. I found several references to Static variables indicating that they may be dangerous, but they were all talking about Java. However, I was not able to find any good explanations as to why.
How are these two methods different? Is the 2nd method dangerous? If so, why?

Static in VB.Net is not that same as static in Java, C#, C, or C++. VB.Net's analog to that construct is Shared. The documentation on the Static keyword is here:
http://msdn.microsoft.com/en-us/library/z2cty7t8.aspx
In particular, I'd like to point out this snippet:
Behavior
When you declare a static variable in a Shared procedure, only one copy of the static variable is available for the whole application. You call a Shared procedure by using the class name, not a variable that points to an instance of the class.
When you declare a static variable in a procedure that isn't Shared, only one copy of the variable is available for each instance of the class. You call a non-shared procedure by using a variable that points to a specific instance of the class.
It's likely the objection comes from believing that Static always behaves like the first paragraph, even in instance methods, when we can see here that it's clearly documented that this is not the case.
Instead, Static allows you to declare a variable whose lifetime-scope is that of the class instance, but whose access-scope is limited to a single method. It's a way to narrow the potential scope of a variable, and therefore is a good thing. Additionally, variables declared as Static are rewritten by the compiler to be protected via the Monitor class (at least for the Shared version), giving them a measure of thread-safety. In other words, a variable declared as Static is more likely to have any needed locking done verses a similar class-scoped variable.
In this particular case, though, I fail to see the point. You don't really gain anything beyond an auto-implemented property like this:
Public ReadOnly Property GetBar2 As New Bar()

This probably is confusing the VB.net concepts of Static and Shared because some languages use the keyword Static to mean what VB uses Shared for: a variable/field/property/method that is shared or common to all instances of a class.
But Static doesn't mean that in VB. Instead it means a routine-local variable that persists beyond the invocation of the routine (i.e., its lifetime is object-scoped rather than routine invocation-scoped).
REF: http://msdn.microsoft.com/en-us/library/z2cty7t8.aspx
So in VB, Static means "routine-scoped visibility, object-scoped lifetime".
Whereas Shared means "class-scoped visibilty, class/program-scoped lifetime".

I would avoid the second approach if for no other reason than the fact that C and C# have a static keyword whose meaning is totally different from that of the VB.NET Static keyword. I generally dislike language features which look like features of other languages but aren't. If it's necessary to use a language feature despite its unfortunate resemblance to the other language's feature, I'll use it, but the VB.NET static keyword doesn't really add much here. Effectively, it asks the compiler to make the variable Private field, give it an arbitrary name which differs from that of any other field, and replace all references to the variable's given name within the method with references to the invented name.
Conceptually, use of such "localized" fields may be regarded as dubious because while one may expect that a field will only need to be used within one method, that may turn out not to be true. I wouldn't worry too much about that issue in vb.net, however, because a Static variable may easily be turned into an ordinary private field if the need arises. If when that need does arise a field exists with the same name, one may easily rename the Static variable before moving it.

Related

Do I understand not using getters and setters correctly

After reading this piece by Yegor about not using getters and setters, it sounds like something that makes sense to me.
Please note this question is not about whether doing it is better/worst, only if I am implementing it correctly
I was wondering in the following two examples in VBA, if I understand the concept correctly, and if I am applying it correctly.
The standard way would be:
Private userName As String
Public Property Get Name() As String
Name = userName
End Property
Public Property Let Name(rData As String)
userName = rData
End Property
It looks to me his way would be something like this:
Private userName As String
Public Function returnName() As String
returnName = userName
End Function
Public Function giveNewName(newName As String) As String
userName = newName
End Function
From what I understand from the two examples above is that if I wanted to change the format of userName (lets say return it in all-caps), then I can do this with the second method without changing the name of the method that gives the name through - I can just let returnName point to a userNameCaps property. The rest of my code in my program can still stay the same and point to the method userName.
But if I want to do this with the first example, I can make a new property, but then have to change my code everywhere in the program as well to point to the new property... is that correct?
In other words, in the first example the API gets info from a property, and in the second example the API gets info from a method.
Your 2nd snippet is neither idiomatic nor equivalent. That article you link to, is about Java, a language which has no concept whatsoever of object properties - getFoo/setFoo is a mere convention in Java.
In VBA this:
Private userName As String
Public Property Get Name() As String
Name = userName
End Property
Public Property Let Name(rData As String)
userName = rData
End Property
Is ultimately equivalent to this:
Public UserName As String
Not convinced? Add such a public field to a class module, say, Class1. Then add a new class module and add this:
Implements Class1
The compiler will force you to implement a Property Get and a Property Let member, so that the Class1 interface contract can be fulfilled.
So why bother with properties then? Properties are a tool, to help with encapsulation.
Option Explicit
Private Type TSomething
Foo As Long
End Type
Private this As TSomething
Public Property Get Foo() As Long
Foo = this.Foo
End Property
Public Property Let Foo(ByVal value As Long)
If value <= 0 Then Err.Raise 5
this.Foo = value
End Property
Now if you try to assign Foo with a negative value, you'll get a runtime error: the property is encapsulating an internal state that only the class knows and is able to mutate: calling code doesn't see or know about the encapsulated value - all it knows is that Foo is a read/write property. The validation logic in the "setter" ensures the object is in a consistent state at all times.
If you want to break down a property into methods, then you need a Function for the getter, and assignment would be a Sub not a Function. In fact, Rubberduck would tell you that there's a problem with the return value of giveNewName being never assigned: that's a much worse code smell than "OMG you're using properties!".
Functions return a value. Subs/methods do something - in the case of an object/class, that something might imply mutating internal state.
But by avoiding Property Let just because some Java guy said getters & setters are evil, you're just making your VBA API more cluttered than it needs to be - because VBA understands properties, and Java does not. C# and VB.NET do however, so if anything the principles of these languages would be much more readily applicable to VBA than Java's, at least with regards to properties. See Property vs Method.
FWIW public member names in VB would be PascalCase by convention. camelCase public member names are a Java thing. Notice how everything in the standard libraries starts with a Capital first letter?
It seems to me that you've just given the property accessors new names. They are functionally identical.
I think the idea of not using getters/setters implies that you don't try to externally modify an object's state - because if you do, the object is not much more than a user-defined type, a simple collection of data. Objects/Classes should be defined by their behavior. The data they contain should only be there to enable/support that behavior.
That means you don't tell the object how it has to be or what data you want it to hold. You tell it what you want it to do or what is happening to it. The object itself then decides how to modify its state.
To me it seems your example class is a little too simple to work as an example. It's not clear what the intended purpose is: Currently you'd probably better off just using a variable UserName instead.
Have a look at this answer to a related question - I think it provides a good example.
Regarding your edit:
From what I understand from the two examples above is that if I wanted
to change the format of userName (lets say return it in all-caps),
then I can do this with the second method without changing the name of
the method that gives the name through - I can just let returnName
point to a userNameCaps property. The rest of my code in my program
can still stay the same and point to the method iserName.
But if I want to do this with the first example, I can make a new
property, but then have to change my code everywhere in the program as
well to point to the new property... is that correct?
Actually, what you're describing here, is possible in both approaches. You can have a property
Public Property Get Name() As String
' possibly more code here...
Name = UCase(UserName)
End Property
or an equivalent function
Public Function Name() As String
' possibly more code here...
Name = UCase(UserName)
End Function
As long as you only change the property/function body, no external code needs to be adapted. Keep the property's/function's signature (the first line, including the Public statement, its name, its type and the order and type of its parameters) unchanged and you should not need to change anything outside the class to accommodate.
The Java article is making some sort of philosophic design stance that is not limited to Java: The general advise is to severely limit any details on how a class is implemented to avoid making one's code harder to maintain. Putting such advice into VBA terms isn't irrelevant.
Microsoft popularized the idea of a Property that is in fact a method (or two) which masquerade as a field (i.e. any garden-variety variable). It is a neat-and-tidy way to package up a getter and setter together. Beyond that, really, behind the scenes it's still just a set of functions or subroutines that perform as accessors for your class.
Understand that VBA does not do classes, but it does do interfaces. That's what a "Class Module" is: An interface to an (anonymous) class. When you say Dim o As New MyClassModule, VBA calls some factory function which returns an instance of the class that goes with MyClassModule. From that point, o references the interface (which in turn is wired into the instance). As #Mathieu Guindon has demonstrated, Public UserName As String inside a class module really becomes a Property behind the scenes anyway. Why? Because a Class Module is an interface, and an interface is a set of (pointers to) functions and subroutines.
As for the philosophic design stance, the really big idea here is not to make too many promises. If UserName is a String, it must always remain a String. Furthermore, it must always be available - you cannot remove it from future versions of your class! UserName might not be the best example here (afterall, why wouldn't a String cover all needs? for what reason might UserName become superfluous?). But it does happen that what seemed like a good idea at the time the class was being made turns into a big goof. Imagine a Public TwiddlePuff As Integer (or instead getTwiddlePuff() As Integer and setTwiddlePuff(value As Integer)) only to find out (much later on!) that Integer isn't sufficient anymore, maybe it should have been Long. Or maybe a Double. If you try to change TwiddlePuff now, anything compiled back when it was Integer will likely break. So maybe people making new code will be fine, and maybe it's mostly the folks who still need to use some of the old code who are now stuck with a problem.
And what if TwiddlePuff turned out to be a really big design mistake, that it should not have been there in the first place? Well, removing it brings its own set of headaches. If TwiddlePuff was used at all elsewhere, that means some folks may have a big refactoring job on their hands. And that might not be the worst of it - if your code compiles to native binaries especially, that makes for a really big mess, since an interface is about a set of function pointers layed out and ordered in a very specific way.
Too reiterate, do not make too many promises. Think through on what you will share with others. Properties-getters-setters-accessors are okay, but must be used thoughtfully and sparingly. All of that above is important if what you are making is code that you are going to share with others, and others will take it and use it as part of a larger system of code, and it may be that these others intend to share their larger systems of code with yet even more people who will use that in their even larger systems of code.
That right there is probably why hiding implementation details to the greatest extent possible is regarded as fundamental to object oriented programming.

Is public variable all that bad?

I've read a lot of articles about "public vs getter/setter", but I still wonder if there is any good part about public variable.
Or the question is:
If you're going to make a new awesome programming languange, are you still going to support public variable and why??
I agree with almost everything that's been said by everyone else, but wanted to add this:
Public isn't automatically bad. Public is bad if you're writing an Object Class. Data Classes are just fine. There's nothing wrong with this class:
public class CommentRecord
{
public int id;
public string comment;
}
... why? Because the class isn't using the variables for anything. It's just a data object - it's meant to be just a simple data repository.
But there's absolutely something wrong with this class:
public class CommentRecord
{
public int id;
public string comment;
public void UpdateInSQL()
{
// code to update the SQL table for the row with commentID = this.id
// and set its UserComment column to this.comment
}
}
... why is this bad? Because it's not a data class. It's a class that actually does stuff with its variables - and because of that, making them public forces the person using the class to know the internals of the class. The person using it needs to know "If I want to update the comment, I have to change the public variable, but not change the id, then call the UpdateInSQL() method." Worse, if they screw up, they use the class in a way it wasn't intended and in a way that'll cause unforseen consequences down the line!
If you want to get some more info on this, take a look at Clean Code by Robert Martin, Chapter 6, on "Data/Object Anti-Symmetry"
A public variable essentially means you have a global accessible/changeable variable within the scope of an object. Is there really a use case for this?
Take this example: you have a class DatabaseQueryHandler which has a variable databaseAccessor. Under what circumstances would you want this variable to be:
Publicly accessible (i.e. gettable)
Publicly settable
Option #1 I can think of a few - you may want to get the last insert ID after an insert operation, you may want to check any errors the last query generated, commit or rollback transactions, etc., and it might make more logical sense to have these methods written in the class DatabaseAccessor than DatabaseQueryHandler.
Option #2 is less desirable, especially if you are doing OOP and abiding by SOLID principles, in particular regards to the ISP and DIP principles. In that case, when would you want to set the variable databaseAccessor in DatabaseQueryHandler? Probably on construction only, and never at any time after that. You probably also want it type-hinted at the interface level as well, so that you can code to interfaces. Also, why would you need an arbitrary object to be able to alter the database accessor? What happens if Foo changes the variable DatabaseQueryHandler->databaseAccessor to be NULL and then Bar tries to call DatabaseQueryHandler->databaseAccessor->beginTransaction()?
I'm just giving one example here, and it is by no means bullet proof. I program in PHP (dodges the hurled rotten fruit) and take OOP and SOLID very seriously given the looseness of the language. I'm sure there will be arguments on both sides of the fence, but I would say that if you're considering using a public class variable, instead consider what actually needs to access it, and how that variable is to be used. In most cases the functionality can be exposed via public methods without allowing unexpected alteration of the variable type.
Simple answer is: yes, they are bad. There are many reasons to that like coupling and unmaintanable code. In practice you should not use them. In OOP the public variable alternative is Singleton, which is considered a bad pracitce. Check out here.
It has a lot to do with encapsulation. You don't want your variable to be accessed anyhow. Other languages like iOS (objective-c) use properties:
#property (nonatomic, strong) NSArray* array;
then the compiler will generate the instance variable with it's getter and setter implicitly. In this case there is no need to use a variable (though other developers still prefer to use variables). You can then make this property public by declaring it in the .h file or private by declaring it in the .m file.

Why do we need a constructor in OOP?

I am new to OOP. I am still in a learning phase.
Why do we need constructors, When we can initialize the values of the properties (variables) by writing a "Initialize function"?
Basically why do we write a constructor when we can achieve the same results even by writing a function for initializing the variables?
The constructor IS the "Initialize function"
Rather than calling two functions
object = new Class;
object.initialize();
You just call
object = new Class();
The logic inside the constructor can be identical to the logic inside the initialize function, but it's much tidier and avoids you naming your function initialize(), me naming mine initialize_variables(), and someone else naming theirs init_vars()... consistency is useful.
If your constructor is very large, you may still wish to split variable initialisation into a separate function and calling that function from your constructor, but that's a specific exception to the scenario.
So answer is simple
Why do we write Constructor?
Because in C you can write,
int i;
if write like this In above case data type and variable defines if you define like this memory allocated for i variable.So simple here we define class name and variable name(object name) we can create memory allocated for class name.
Example
myClass objectName;
But in C++ new keyword is used for dynamic memory allocation, so this dynamic memory which we can allocate to our class but here my example myClass is our class and we want to allocate to dynamic memory allocated.
So
myClass objectName = new myClass();
and simply constructor is memory allocation for class variable is called the constructor.`
the role of the constructor is to initialize the variables/values.it is the "initialization function".The only reason i find on why we use a constructor instead of a normal function to initialize the variables is to stop different people from using different function names and avoid ambiguity and it is much more easier to use a constructor which is instantiated automatically as soon as the class is run,instead of having to write a separate code for instantiation.this may seem small and like something that doesn't require much work,but only for a very small program,for larger ones the struggle is real.
It is usual to put mandatory things into the constructor and optional ones into the Initialise function.
For example, consider an amplifier that requires a power source so that would be supplied to its constructor. Logically, you may want to turn it on and set its power level but one could argue that you might not want to do that until later. In pseudo-code:
class Amplifier
{
public Amplifier(PowerSource powerSource)
{
// create amplifier...
}
public int PowerLevel;
public void Initialise()
{
// turn on...
}
}
The example, above, is rather puerile but it illustrates the concepts at play. It is always an issue of design, however, and opinions do vary.
Some classes of object, however, will have to perform obvious set-up operations during their construction phase. In these cases, the requirement to have a constructor is very easy to understand. For example, if your object might require a variable amount of memory, the constructor would be a logical place to allocate it and the destructor or finaliser would be a logical place to free it up again.
Even if you don't use constructor it will call implicitly by your language translator whenever you create object.Why?
The reason is that it is used for object initialization means the variable(instance) which we declare inside our class get initialized to their default value.
class Person {
//Class have two parts
//1.Data(instance variable)
//2.Methods(Sub-routine)
String name;
int age;
}
public class Stack{
public static void main(String[] args){
Person person1 = new Person();
System.out.println("Name: "+person1.name);
System.out.println("Age: " + person1.age);
}
}
Output- Name: null
Age: 0
"null" and "0" are default values which are impicitly set by default constructor.
When we initialize a class by creating an instance or object the constructor is called automatically. This is very helpful when we need a huge amount of code to be executed every time we create an object.
The best use of constructor can be seen when we create a " graphical user interface". While building a GUI for an application we need to separate the code for designing the GUI and the business logic of the application. In such a case we can write the code for designing GUI, in a constructor and business logic in respective methods. This make the code tidy and neat too.
Also when an object is created the global variables can be initialized to their default values using constructor. If we don't initialize the global variables, then the compiler will do it implicitly by using the default constructor.
So constructor is a very wise concept which appears to be an idiosyncrasy at first but as you code further and more and more you will realize it's importance.
Because constructors are exactly for that: to avoid using an "initialize function"
Plus you can have have as many constructors as you want: you juste feed them some parameters, depending how you want to inialize your object.
Constructor is a special member function which has same name as class name and called whenever object of that class is created. They are used to initialize data field in object.
Constructor has following properties:
It has same name as class name.
It is called whenever object of a class is created.
It does not have return type not even void.
It can have parameters.
Constructor can be overloaded.
Default constructor is automatically created when compiler does not find any constructor in a class.
Parameterized constructor can call default constructor using this() method.
A constructor can be static for static data field initialization.
It is not implicitly inherited.
For More Info
https://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)

When is a static variable created?

Let's say I have a static variable in a function:
Private Sub SomeFunction()
Static staticVar As String = _myField.Value
End Sub
When, exactly, is the value from _myField assigned to staticVar? Upon the first call to the function? Instantiation of the enclosing class?
The CLR has no support for this construct so the VB.NET compiler emulates it.
Creation first. The variable is lifted to a private field of the class with an unspeakable name that ensures no name collisions can occur. It will be an instance field if the variable is inside an instance method of the class. So will be created when an object of the class is created with the new operator. It will be a Shared field if the method is Shared or is part of a Module. So will be created in the loader heap by the jitter.
Assignment next, the much more involved operation. The language rule is that assignment occurs when code execution lands on the Dim statement for the first time. The term first time is a loaded one. There's an enormous amount of code generated by the compiler inside the method to ensure this is guaranteed. The kind of problems that need to be addressed are threading, recursion and exceptions.
The compiler creates another hidden helper field of type StaticLocalInitFlag at the same scope as the hidden variable field to keep track of initialization state for the variable. The first part of the injected code is a call to Monitor.Enter() to deal with threading. Same thing as SyncLock. The StaticLocalInitFlag serves as the locking object, note how it is a class and not just a Boolean.
Next, Try and Finally statements guard against exceptions. Inside the Try statement, the value of StaticLocalInitFlag.State is checked for 0. This protects against recursion on the same thread. State is then set to 2 to indicate that initialization code is running. Followed by the assignment. Next, State is checked again to see if it is still 2. If it is not then something went drastically wrong and an IncompleteInitialization exception is thrown.
The Finally block then sets the State to 1 to indicate that the variable is initialized. Followed by a call to Monitor.Leave().
Lots of code, 96 bytes of IL for just a simple variable. Use Static only if you don't worry about the cost.
A Static variable is instantiated when it is assigned, obviously.
When that line is run, not before, not after.
Put a breakpoint on it and you'll see.
Static just means that the value will persist between calls.
Shared class/module members are instantiated the first time the class is accessed, before any Shared constructor and before the call, whether that is to the class constructor or some Shared method/property. I think this may be the origin of your confusion. Static local variables, like local statics in c# are not instantiated in this way.
Interesting information from Tim Schmelter, it appears the value is maintained internally using a hidden Shared class level variable that is instantiated like other Shared class level variables but always with the default value.
The effect observed by you the developer is unchanged, apart from some instantiation delay when the class is accessed. This delay should be undetectable in practice.
The VB.NET compiler creates a static (shared in VB.NET) class-level variable to maintain the value of "staticVar". So it's initialized like any other static/shared variable, on the first use of a static field of that class (or when you call this method).
http://weblogs.asp.net/psteele/pages/7717.aspx

naming a method - using set() when *not* setting a property?

Is setX() method name appropriate for only for setting class property X?
For instance, I have a class where the output is a string of an html table. Before you can you can call getTable, you have to call setTable(), which just looks at a other properties and decides how to construct the table. It doesn't actually directly set any class property -- only causes the property to be set. When it's called, the class will construct strHtmlTable, but you can't specify it.
So, calling it setTable breaks the convention of get and set being interfaces for class properties.
Is there another naming convention for this kind of method?
Edit: in this particular class, there are at least two ( and in total 8 optional ) other methods that must be called before the class knows everything it needs to to construct the table. I chose to have the data set as separate methods rather than clutter up the __construct() with 8 optional parameters which I'll never remember the order of.
I would recommend something like generateTable() instead of setTable(). This provides a situation where the name of the method clearly denotes what it does.
I would probably still use a setTable() method to actually set the property, though. Ideally, you could open the possibility of setting a previously defined table for further flexibility.
Yes, setX() is primarily used for setting a field X, though setX() may have some additional code that needs to run in addition to a direct assignment to a field. Using it for something else may be misleading to other developers.
I would definitely recommend against having a public setTable() and would say that setTable() could be omitted or just an unused private method depending upon your requirements.
It sounds like the activity to generate the table is more of a view of other properties on the object, so you might consider moving that to a private method on the object like generateHtmlTable(). This could be done during construction (and upon updates to the object) so that any subsequent calls to getTable() will return the the appropriate HTML.