Should I use private variables in Objective C if I want to make my code more testable? - objective-c

I just wonder if I want to make my code more testable, should I use private variables?
If not, when should I use private variables?

Private variables should just be used for internal storage for your class not testing directly against. Set up your class how it is designed to be accessed with the proper properties and methods, then write your test to access your properties and methods just as any other part of your code would.

Related

I can't see private members in a Kotlin KClass

I'm working on a library that uses reflection, and I would like to manipulate all the properties / function of a given KClass.
Using the KClass::members property, I can manipulate all the accessible members (as per the documentation), ie: the public, internal and protected fields, properties and functions. But I can't see the private ones.
Using Java reflection, I can see all fields (inluding private ones) using the Class.getDeclaredFields(), and likewise I can see private methods using Class.getDeclaredMethods().
Is there a way to do this using the kotlin reflection API ?
Yes, you can use the declaredMembers, declaredFunctions, and declaredMemberProperties, which will include the private members, but won't include the members declared in the supertypes, just like with the Java reflection API.

Can I change a private methods visibility in order to unit test them

I see in this answer that for Java you can set the visibility of a private method to "true" in a unit test in order to test the method. Is there something like this available for VBA, so that I can unit test private methods using RD-VBA?
If not, and I have a class that works out some logic in three private methods and give it back to a return value, am I doomed to only give a input value and test the return value, without being able to test the three private methods doing the heave lifting in between?
You shouldn't need to write tests for private methods, regardless of the language. You test your public API, what's private is implementation detail that isn't relevant.
If it is relevant and important enough to be tested on its own, then you should extract that private method to another class, and expose it as a public member of that class.
For example once I had a form and I wanted to limit user input in a textbox to numeric characters, and since I'm reusing that logic elsewhere then instead of treating it as an implementation detail of my form, I extracted a AsciiInputValidator class, and its public IsValidNumericValue method could be tested in every possible way as its own SUT.
Don't test private methods: the public ones invoke them anyway.
Unfortunately the Extract Class refactoring feature is not implemented as of this writing, so for now Rubberduck can't do this automatically for you... but it's definitely in-scope and if you're reading this and you're up for a bit of a C# metaprogramming challenge, go for it, pull requests are always welcome!
Can you add a public wrapper like
public sub testPrivateSub(param1,param2...)
PrivateSub(param1,param2....)
end sub
private sub PrivateSub(param1,param2....)
....
end sub

Sharing variable data between forms other than a Global Variable Class in Win Forms vb.net application

Currently in a Win Form application, im using a Global Variable Class which contains variables that are used to to share data. My question is, what other ways are there to achieve this? Best practises? and why?
Globals are bad for many reasons, but probably the most glaring reason is because, ideally speaking, every time you call the same method, passing it the same parameters, it should always do the same thing with the same results. Globals brake that rule. Suddenly your code starts behaving in unpredictable ways because something wasn't initialized properly somewhere else, or some global got modified incorrectly.
The best way I've found to get rid of the need for globals is to adhere to the principles of dependency injection (DI). There is much material on the topic online, but in a nutshell, rather than having classes reach out to create or find their dependencies on their own, they should simply request that the dependencies be provided to them, often in the constructor. Anything that you are accessing via global variables would, by definition, be considered dependencies of the classes that access them. Therefore, instead of, for instance, having a global settings object, like this:
Global settings As New Settings()
And then a class that uses it like this:
Public Class MyClass
Public Sub DoSomething()
If settings.SomethingEnabled Then
' ...
End If
End Sub
End Class
You would instead, do it like this:
Public Class MyClass
Public Sub New(settings As Settings)
_settings = settings
End Sub
Private _settings As Settings
Public Sub DoSomething()
If _settings.SomethingEnabled Then
' ...
End If
End Sub
End Class
This makes your code much cleaner, more flexible, and more reliable. It also makes the code far more testable too, which is a great added benefit.
Data should be shared according to how it is going to be used. If a variable is required across the entire application then it can be seen to have global scope and a global variable concept (e.g. public static shared) may well be appropriate.
Often this is not the case however as global variables should really be avoided (check out here and here for more reasoning)
Data should be encapsulated at the level it is required - for example if a form has data / variables within it that are applicable to it's function but where other forms need to now the value, this would be the ideal case for a public readonly property on the form, which would mask the actual detail of the variable from the rest of the aplication.

When to declare methods as private

I am looking for specific and exact rules to determine how a method's visibility can be declared. This is not language agnostic, it applies to the standard OOP languages.
A good rule to follow would be:
Members should not have more accessibility than they need.
Start with private and make them more accessible as the need arises.
Basically:
Public is for when the method must be accessible by an outside class. Something like getState() would fit here.
Private is for when the method should not be accessible by any other class, something like changeState(...). Generally this relates to the actual alteration of an object's contents - maybe you'll have a public setX(int x) that just calls the private setXInternal(int x), that way you can have extra type-checking/safety/etc. To be safe you might as well make everything private until it has to be otherwise.
Protected is basically "public to child classes, private otherwise". Could go either way.
With any class/object there are:
1. things it does (behaviours)
2. how it does them (implementation)
The world cares about the behaviour of your object. It shouldn't (often) care about how it achieves this behaviour under the hood. Keep implementation details private, and expose behaviours.
Any kind of operation which does not define behaviour of particular object directly but is useful during implementation of object's behaviour is a candidate for private member function.
I think the helpfulness of the public, protected and private keywords is just to make the code more clear.
So you would use public for the API of a class, private to make it clear how to do NOT extend a class and protected in every other case.
A common pragmatic approach is never use private and to use just public or protected.
Public for things that are part of the public API.
Protected for non-public functions that you want subclasses to be able to call.
Private if you don't want subclasses mucking around with said method (or to even know of its existence).
In C, C++, and C# don't forgot to mark a method virtual if you want a child class to be able to override it.

Declare global variables in Visual Studio 2010 and VB.NET

How do I declare a global variable in Visual Basic?
These variables need to be accessible from all the Visual Basic forms. I know how to declare a public variable for a specific form, but how do I do this for all the forms in my project?
There is no way to declare global variables as you're probably imagining them in VB.NET.
What you can do (as some of the other answers have suggested) is declare everything that you want to treat as a global variable as static variables instead within one particular class:
Public Class GlobalVariables
Public Shared UserName As String = "Tim Johnson"
Public Shared UserAge As Integer = 39
End Class
However, you'll need to fully-qualify all references to those variables anywhere you want to use them in your code. In this sense, they are not the type of global variables with which you may be familiar from other languages, because they are still associated with some particular class.
For example, if you want to display a message box in your form's code with the user's name, you'll have to do something like this:
Public Class Form1: Inherits Form
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
MessageBox.Show("Hello, " & GlobalVariables.UserName)
End Sub
End Class
You can't simply access the variable by typing UserName outside of the class in which it is defined—you must also specify the name of the class in which it is defined.
If the practice of fully-qualifying your variables horrifies or upsets you for whatever reason, you can always import the class that contains your global variable declarations (here, GlobalVariables) at the top of each code file (or even at the project level, in the project's Properties window). Then, you could simply reference the variables by their name.
Imports GlobalVariables
Note that this is exactly the same thing that the compiler is doing for you behind-the-scenes when you declare your global variables in a Module, rather than a Class. In VB.NET, which offers modules for backward-compatibility purposes with previous versions of VB, a Module is simply a sealed static class (or, in VB.NET terms, Shared NotInheritable Class). The IDE allows you to call members from modules without fully-qualifying or importing a reference to them. Even if you decide to go this route, it's worth understanding what is happening behind the scenes in an object-oriented language like VB.NET. I think that as a programmer, it's important to understand what's going on and what exactly your tools are doing for you, even if you decide to use them. And for what it's worth, I do not recommend this as a "best practice" because I feel that it tends towards obscurity and clean object-oriented code/design. It's much more likely that a C# programmer will understand your code if it's written as shown above than if you cram it into a module and let the compiler handle everything.
Note that like at least one other answer has alluded to, VB.NET is a fully object-oriented language. That means, among other things, that everything is an object. Even "global" variables have to be defined within an instance of a class because they are objects as well. Any time you feel the need to use global variables in an object-oriented language, that a sign you need to rethink your design. If you're just making the switch to object-oriented programming, it's more than worth your while to stop and learn some of the basic patterns before entrenching yourself any further into writing code.
Pretty much the same way that you always have, with "Modules" instead of classes and just use "Public" instead of the old "Global" keyword:
Public Module Module1
Public Foo As Integer
End Module
Okay. I finally found what actually works to answer the question that seems to be asked;
"When needing many modules and forms, how can I declare a variable to be public to all of them such that they each reference the same variable?"
Amazingly to me, I spent considerable time searching the web for that seemingly simple question, finding nothing but vagueness that left me still getting errors.
But thanks to Cody Gray's link to an example, I was able to discern a proper answer;
Situation;
You have multiple Modules and/or Forms and want to reference a particular variable from each or all.
"A" way that works;
On one module place the following code (wherein "DefineGlobals" is an arbitrarily chosen name);
Public Module DefineGlobals
Public Parts As Integer 'Assembled-particle count
Public FirstPrtAff As Long 'Addr into Link List
End Module
And then in each Module/Form in need of addressing that variable "Parts", place the following code (as an example of the "InitForm2" form);
Public Class InitForm2
Private Sub InitForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Parts = Parts + 3
End Sub
End Class
And perhaps another Form;
Public Class FormX
Sub CreateAff()
Parts = 1000
End Sub
End Class
That type of coding seems to have worked on my VB2008 Express and seems to be all needed at the moment (void of any unknown files being loaded in the background) even though I have found no end to the "Oh btw..." surprise details. And I'm certain a greater degree of standardization would be preferred, but the first task is simply to get something working at all, with or without standards.
Nothing beats exact and well worded, explicit examples.
Thanks again, Cody
Make it static (shared in VB).
Public Class Form1
Public Shared SomeValue As Integer = 5
End Class
Public variables are a code smell - try to redesign your application so these are not needed. Most of the reasoning here and here are as applicable to VB.NET.
The simplest way to have global variables in VB.NET is to create public static variables on a class (declare a variable as Public Shared).
A global variable could be accessible in all your forms in your project if you use the keyword public shared if it is in a class. It will also work if you use the keyword "public" if it is under a Module, but it is not the best practice for many reasons.
(... Yes, I somewhat repeating what "Cody Gray" and "RBarryYoung" said.)
One of the problems is when you have two threads that call the same global variable at the same time. You will have some surprises. You might have unexpected reactions if you don't know their limitations. Take a look at the post Global Variables in Visual Basic .NET and download the sample project!
small remark: I am using modules in webbased application (asp.net).
I need to remember that everything I store in the variables on the module are seen by everyone in the application, read website. Not only in my session.
If i try to add up a calculation in my session I need to make an array to filter the numbers for my session and for others.
Modules is a great way to work but need concentration on how to use it.
To help against mistakes: classes are send to the
CarbageCollector
when the page is finished. My modules stay alive (as long as the application is not ended or restarted) and I can reuse the data in it.
I use this to save data that sometimes is lost because of the sessionhandling by IIS.
IIS Form auth
and
IIS_session
are not in sync, and with my module I pull back data that went over de cliff.
All of above can be avoided by simply declaring a friend value for runtime on the starting form.
Public Class Form1
Friend sharevalue as string = "Boo"
Then access this variable from all forms simply using Form1.sharevalue
You could just add a new Variable under the properties of your project
Each time you want to get that variable you just have to use
My.Settings.(Name of variable)
That'll work for the entire Project in all forms
The various answers in this blog seem to be defined by SE's who promote strict adherence to the usual rules of object-oriented programming (use a Public Class with public shared (aka static), and fully-qualified class references, or SE's who promote using the backward-compatibility feature (Module) for which the compiler obviously needs to do the same thing to make it work.
As a SE with 30+ years of experience, I would propose the following guidelines:
If you are writing all new code (not attempting to convert a legacy app) that you avoid using these forms altogether except in the rare instance that you really DO need to have a static variable because they can cause terrible consequences (and really hard-to-find bugs). (Multithread and multiprocessing code requires semaphores around static variables...)
If you are modifying a small application that already has a few global variables, then formulate them so they are not obscured by Modules, that is, use the standard rules of object-oriented programming to re-create them as public static and access them by full qualification so others can figure out what is going on.
If you have a huge legacy application with dozens or hundreds of global variables, by all means, use Modules to define them. There is no reason to waste time when getting the application working, because you are probably already behind the 8-ball in time spent on Properties, etc.
The first guy with a public class makes a lot more sense. The original guy has multiple forms and if global variables are needed then the global class will be better. Think of someone coding behind him and needs to use a global variable in a class you have IntelliSense, it will also make coding a modification 6 months later a lot easier.
Also if I have a brain fart and use like in an example parts on a module level then want my global parts I can do something like
Dim Parts as Integer
parts = 3
GlobalVariables.parts += Parts '< Not recommended but it works
At least that's why I would go the class route.
You can pipe the variable in to a file in the output directory and then load that file in the variable.
Imports System.IO
This code writes the file.
Dim somevariable = "an example"
Dim fs As FileStream = File.Create("globalvars/myvar1.var")
Dim filedata As Byte() = New UTF8Encoding(True).GetBytes(somevariable)
fs.Write(filedata, 0, filedata.Length)
fs.Close()
This loads the file in another form.
Dim form2variable
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("globalvars/myvar1.var")
form2variable = filereader
Public Class Form1
Public Shared SomeValue As Integer = 5
End Class
The answer:
MessageBox.Show("this is the number"&GlobalVariables.SomeValue)