What are the practical difference between declaring a function private vs public? - vb.net

So as I've been reading/learning about classes and the methods within them I've found very little about the practical differences between declaring a method as public versus private.
I know that the difference is a private class can only be accessed within the class, while a public method can be accessed from code outside the class (other classes, functions). But what I really want to know is:
Why would you want/not want to declare it one way or another when deploying an application?
Are there best practices that can guide whether to declare a method public vs private?
Also, I don't know if it matters, but I am learning primarily VB.Net and C# in a web application environment, so specifics to that would help.

Encapsulation means that you should think of each class as a machine that provides a service. For example, a chair allows you to sit on it, or a lawnmower allows you to cut your lawn.
The private methods pertain to the machine's internal workings. In contrast, the public methods relate to how you (other classes) interact with the machine.
Example one: Chair...
When sitting on a chair, you don't need to know volume of stuffing or the number of staples, you basically need to know whether or not it's occupied and if it's stable.
Public methods: IsStable, IsOccupied, Sit
Private methods: CalculateStuffingVolume, CountNumberOfStaples
Example two: Lawnmower...
For the lawnmower, you need to know if it has enough fuel (or is plugged in), if the blades are sharp, and be able to turn it on.
Public methods: GetFuelLevel, IsBladesSharp, TurnOn, TurnOff
Private methods: Combust, etc, Too many to imagine.
Conclusion:
So when you're developing all you will see is...
Example one: Chair.Sit, Chair.IsStable and Chair.IsOccupied
or
Example two: Lawnmower.GetFuelLevel, Lawnmower.IsBladesSharp, Lawnmower.TurnOn, LawnMower.TurnOff
As a developer, you will not have to think about number of threads in the uphosltry, the colour of the fuel cap, the number of RPM of the blades or whether the chair is glued or stapled together. This distinction makes it much easier to put your application together without being swamped in detail. Additionally, it allows programmers to expose only necessary information which adds a level of security. As John mentioned, this prevents the Person class from calling Lawnmower.Combust(fuel) when they're not supposed to.

If the method is private, then you don't have to think about outside classes calling it incorrectly.
One of the benefits of this is that it allows for a separation between the interface to your class (the public parts of it), and the implementation of it. If nobody knows how you implemented your class (that is, if there is no code that depends on how you implemented it), then you're free to change the way you implemented it without breaking any other code.

It's one of the most importand principles of the object-oriented programming -- encapsulation.
A class usually provides a (public) interface. E.g. (pseudocode):
class Rectangle {
private length;
private width;
public getPerimeter() {
// return calculatePerimeterOld();
return calculatePerimeterNew();
}
private calculatePerimeterOld() {
// old variant
}
private calculatePerimeterNew() {
// Here the perimeter is caltulated.
// so: perimeter = 2 * (length + width)
// or so: perimeter = 2 * (length) + 2 * (width)
// or maybe so: perimeter = length + width + length + width - (0.5 * length) + 2 * 0.25 * length)
return perimeter;
}
}
I can change my private methods however I want. I can rename or replace them with oher methods. But my public interface will stay the same -- and it has to stay the same, because it's a contract I sign, when I'm defining a mehod as public. Everything, what is signed as private is my "blackbox" and I can do there whatever I want.
It's the main reason. Another reason is, that we should not provide the user(-s) of our class with methods/informations, they don't need. To much (information) is not good.

If you're developing a one off website maintained just by you, you may find the concept of public and private functions unnecessary.
However, if you're delivering software to other people, and they're building on top of your software, it is an absolutely critical concept.
Think of it like a physical machine that has a thousand knobs and switches inside it, but is contained inside a pretty case with only a few clearly labelled knobs on the outside.
The public functions and methods are the ones you create for external parties to interact with your software.
The private functions and methods are the ones you create for your software to interact with
itself.
But, again, if it's a one-off website maintained by a single developer, these differences are less important.

Related

How do you test private methods, classes, and modules?

I have looked at other discussions about this topic (on StackOverflow) however the other questions seem to be language specific whereas this is not language specific and I'm considering no longer using private methods, classes, and modules.
I want to test my private methods, classes, and modules so that I can more easily locate bugs. To allow me to do this I'm considering no longer using private methods, classes, and modules for two reasons, (1) I see no reasonable way of testing a private method, class, or module without injecting test code or using some sort of "magic" and (2) to improve code reuse. Note that I'm not considering no longer using private variables and properties because data needs protecting and does not provide behaviour therefore it does not need to be public during testing.
As a lame example, if you're writing a module called OneOperations that has two public methods addOne and subtractOne, and two private methods add and subtract. If you were not allowing yourself to have private methods you would put the two private methods into another module (basicOperations) where they are public and import those methods inside the OneOperations module. From this you should now be able to write testing code for all the methods in both modules without injecting code. An advantage of this is that the methods add and subtract can now be used in other modules by importing the basicOperations module (2 - improving code reuse).
I have a feeling this a bad idea, but I lack the real world experience to justify not doing this, which is why I've posted this question on StackOverflow.
So, how do you test your private methods, classes, and modules? Is not writing private methods, modules, and classes a potential solution?
1) Like in many other answers on this topic, the main question is why would you want to test your private methods? The purpose of a class is to provide some functionality to its clients. If you have comprehensive unit tests that prove that the public interface of this class behaves correctly, why do you care what it's doing in its private methods?
2) Your idea of not having private methods at all seems like cutting your leg off. For small projects it may be possible to have every tiny behaviour well separated and tested. But for large projects it's an overkill. What matters, is the domain logic behaving correctly.
Consider for example a method:
public double getDistanceSquared(Point other)
{
return getDifferenceSquared(this.x, other.x)
+ getDifferenceSquared(this.y, other.y);
}
private double getDifferenceSquared(double v1, double v2)
{
return (v1 - v2)*(v1 - v2);
}
Ad1) Does it really make sense to unit test getDifferenceSquared method, if getDistanceSquared returns correct results for all test cases?
Ad2) Creating a separate class for calculating squared distance between doubles - in case there is only one place when it'll be used leads to a swarm of tiny classes, with millions of tests. Also, constructors of your domain classes will accept like 10 different interfaces for every tiny thing they're doing internally.
Maintaining all this is a lot of unnecessary work. Imagine that you would like to change the method of calculating the distance (maybe use some precomputed values). The behaviour of getDistanceSquared would not change. But you would have to change all of the tests of getDifferenceSquared even though you shouldn't have to care how is the distance being calculated, as long as it's calculated correctly.
Diving into minor details when it's not necessary makes you forgot what you're really doing - you lose the "big picture view". Value your time, and focus on important problems.
As a side note, also - the main concern of unit tests is not "locating bugs" as you suggest. They impose a clean design, provide an always up-to-date documentation of your code's behaviour and allow convenient refactoring giving you flexibility. Additionally they assure you that the code is working as you expect it to.
http://artofunittesting.com/definition-of-a-unit-test/
http://en.wikipedia.org/wiki/Unit_testing#Benefits
There is another way to look at this, which is how do you generate a private method?
If we are following the TDD process properly, then the first thing we write is the test. At this point the test should contain all of our code, e.g.
public void ShouldAddTwoNumbers()
{
(1 + 1).ShouldEqual(2);
}
Yes, that looks appalling. But consider what happens as we write is some more tests.
public void ShouldAddTwoMoreNumbers()
{
(2 + 2).ShouldEqual(4);
}
Now we have something to reactor, so it can become
public void ShouldAddTwoNumbers()
{
Add(1, 1).ShouldEqual(2);
}
public void ShouldAddTwoMoreNumbers()
{
Add(2, 2).ShouldEqual(4);
}
private int Add(int a, int b)
{
return a+b;
}
So now we have a private method that we can test inside our test class. It's only when you complete further refactoring to move the code out into your application, that the private becomes an issue. Most automated refactoring tools will offer you the option of changing the methods signature at this point, so that the private method is still accessible, because its not private.
(There is a fabulous exercise called TDD as if you mean it by Keith Braithwaite which I've just paraphrased above)
However, this isn't the end of our refactorings and development. One thing that we should be doing as we write and refactor our tests is to delete old tests, for example when functionality is duplicated. Another is to extract new methods so we don't repeat ourselves. Both of these can lead to scenarios where we have private methods back in the non-test code base.
So my advice is to be pragmatic, make the best decision you can for the code that you have in front of you. I wouldn't advise not creating private methods, but I would instead look at the factors that lead you to create them.

Public static data used throughout program

Code examples are C# but this is a general OO question.
I know according to OO rules, class coupling should be minimised and members should be kept private wherever possible, etc.
Consider this example:
You are writing an esoteric program which has some sort of data set (I'm not talking about System.Data.DataSet) which is used in literally every facet of the program. In fact, the program basically exists just to load, display, manipulate, and save the data set. Furthermore, there can only ever be one data set loaded at any time, and it is loaded when the program opens.
If we follow OO rules strictly, we would have
public void ShowSomeGraphs(IData data)
{
// do stuff with data which implements IData
}
however we could potentially store a public static Data member in Program, for example.
public void ShowSomeGraphs()
{
// do stuff with Program.Data
}
On one hand, we have traded a slightly shorter function signature for vastly increased class coupling. On the other hand, we are no longer passing a Data parameter to practically every function, everywhere.
The right answer probably is: Avoid class coupling wherever possible. The local Data variables are just pointers so the memory overhead is negligible, and because the classes are decoupled they can be used elsewhere at a later date.
Though realistically speaking, the structure of the Data class will likely be phenomenally different in a different application, so it's not like you can just pull a class from this program and drop it in somewhere else without any tweaks. The extra time and effort required to write the classes in such a way that they can just be dropped in might be difficult to justify to a stakeholder.
I'm working on this sort of program now, and I have used the OO-canon approach: Data parameters are passed around where needed I have minimised class coupling with an IData interface to generalise the data set for future code re-use. Given the application, I'm almost certain this code won't ever be re-used. Without these extra interfaces and abstraction, the program would have worked exactly the same as far as the end user is concerned, but would have represented significantly less headaches and development time for me.
What do you think about this? Do you think it's justifiable to spend all the extra time to write the interfaces and generalisations to ensure classes are decoupled where possible, especially when you can't see the classes being use elsewhere later?
Don't agonise over it. Seriously.
Software paradigms/patterns are there to help us and not to be followed dogmatically.
You make it clear in your question that you consider the loose coupling overkill, and you can justify why. Therefore, don't use it.
How about using the singleton pattern to provide a method or read-only property to get the IData interface? This way you're only coupled to a very thin singleton class and all your interactions with the data set are done through the IData interface.
(I would definitely avoid the tight coupling. Even if you don't plan to do much with this app chances are that you will run into an issue during development which will force you to touch significantly more code than if you accessed the data via an interface.)
Code sample of the singleton solution proposed above:
using System;
public class MyClass {
public static void Main() {
// simple usage:
Console.WriteLine("From Main: " + Singleton.Instance.IMyData.GetData());
// client code from another type:
new ClientObj().DoWork();
Console.ReadKey();
}
}
public sealed class Singleton {
// standard singleton stuff:
private static readonly Singleton _instance = new Singleton();
private Singleton(){}
public static Singleton Instance {get { return _instance; }}
// data interface stuff:
private MyData _myData = new MyData();
public IData IMyData {get { return _myData; }}
}
// the interface:
public interface IData {
string GetData();
}
// concrete implementation of the data class
public class MyData : IData {
public string GetData() {return "Hello World!";}
}
// example of a type using the singleton and the IData interface
public class ClientObj {
public void DoWork() {
IData data = Singleton.Instance.IMyData;
string str = data.GetData();
Console.WriteLine("From other obj: " + str);
}
}
Some caveats: The code sample above is completely stripped down to show the concept of a singleton and shared interface. There is no thread safety implemented, there is no initialization of the data object etc.
Well, there's one big assumption in your text: There will always only be one data set in the program. Are you sure that condition will hold for all time? There was a time where word processors could only hold one text at a time. Today it's standard to be able to have several files open at once. I'd also not be surprised if the first web browsers could only open one web page at a time. Today nobody would use a web browser which could not have several pages open at the same time. I think the sort of object where you can say there will be for certain only one of it in the program, ever, is quite rare. Indeed, the only thing which I would make a global object or singleton would be object factories.
On the other hand, passing the object around for each function call seems to be overkill to me, too. Therefore I would go for the middle ground: Have the objects remember that "global" object, so you only have to pass it via the constructor. This limits each single object to one Data object, but still allows you to easily have several Data objects in your program should you ever decide to.

Decomposing big member function

Decomposing a member function
In a class there is a member function that is rather long. Let's say we have
class Customer {
public:
void process();
...
};
The method process is by nature long and consists of a couple of different
steps. You'd like these steps to be functions of their own, to avoid having
multiple levels of abstraction in the process method. I have thought of these
different options (including the noop-alternative):
Create stand-alone functions for the steps outside of the class.
double step_a(vector<Order> orders, double foo);
void step_b(double bar);
void Customer::proccess()
{
double foo;
...
double bar = step_a(this->orders, foo);
...
step_b(bar);
};
Concerns: The class is less self-contained. The stand alone functions are so
specific to the process function that they would never be of interest to any
other code, making it feel unnatural to keep them outside of the class.
Create private methods.
class Customer {
public:
void process();
private:
double step_a(double foo);
void step_b(double bar);
};
Concerns: The private methods for the steps (at least some of them) wouldn't
operate on any class members at all. They have no side effects, they only
compute a value from arguments and return it, so they have no need at all to
be member functions of the class.
Leave Customer::process as is
Concerns: The function becomes long, and could be hard to read, because of all
the details in the steps making it hard to see the big picture of what steps
the process contains.
Question:
What would be the cleanest way to handle this?
(Perhaps none of the above, but someting I hadn't thought of.)
The question isn't really language agnostic. Not all languages have stand alone functions.
In C++ or C# I would probably use private member functions (static if possible).
In C++ you could use stand-alone functions (possibly in an anonymous namespace) so they are not visible to the outside.
I'd point you at the refactoring books - especially Martin Fowler's Refactoring, and Joshua Kerievsky's Refactoring to Patterns. This problem is explored at some depth in those books.
The "stand-alone" option you describe is often called "helper methods"; there's nothing inherently wrong with this, except that they often explode into becoming the core of the method, and this leads to dependency explosion.
Private (static) methods are best if the code is directly related to the duties of the class in question.
Leaving it as is can be okay - but there's a fairly well-understood correlation between the complexity of a method and the likelihood it contains bugs. If this is a living code base, I'd refactor it.

Interface reference variables

I am going over some OO basics and trying to understand why is there a use of Interface reference variables.
When I create an interface:
public interface IWorker
{
int HoneySum { get; }
void getHoney();
}
and have a class implement it:
public class Worker : Bee, IWorker
{
int honeySum = 15;
public int HoneySum { get { return honeySum; } }
public void getHoney()
{
Console.WriteLine("Worker Bee: I have this much honey: {0}", HoneySum);
}
}
why do people use:
IWorker worker = new Worker();
worker.getHoney();
instead of just using:
Worker worker3 = new Worker();
worker3.getHoney();
whats the point of a interface reference variable when you can just instatiate the class and use it's methods and fields that way?
If your code knows what class will be used, you are right, there is no point in having an interface type variable. Just like in your example. That code knows that the class that will be instantiated is Worker, because that code won't magically change and instantiate anything else than Worker. In that sense, your code is coupled with the definition and use of Worker.
But you might want to write some code that works without knowing the class type. Take for example the following method:
public void stopWorker(IWorker worker) {
worker.stop(); // Assuming IWorker has a stop() method
}
That method doesn't care about the specific class. It would handle anything that implements IWorker.
That is code you don't have to change if you want later to use a different IWorker implementation.
It's all about low coupling between your pieces of code. It's all about maintainability.
Basically it's considered good programming practice to use the interface as the type. This allows different implementations of the interface to be used without effecting the code. I.e. if the object being assigned was passed in then you can pass in anything that implements the interface without effecting the class. However if you use the concrete class then you can only passin objects of that type.
There is a programming principle I cannot remember the name of at this time that applies to this.
You want to keep it as generic as possible without tying to specific implementation.
Interfaces are used to achieve loose coupling between system components. You're not restricting your system to the specific concrete IWorker instance. Instead, you're allowing the consumer to specify which concrete implementation of IWorker they'd like to use. What you get out of it is loosely dependent components and better flexibility.
One major reason is to provide compatibility with existing code. If you have existing code that knows how to manipulate objects via some particular interface, you can instantly make your new code compatible with that existing code by implementing that interface.
This kind of capability becomes particularly important for long-term maintenance. You already have an existing framework, and you typically want to minimize changes to other code to fit your new code into the framework. At least in the ideal case, you do this by writing your new code to implement some number of existing interfaces. As soon as you do, the existing code that knows how to manipulate objects via those interfaces can automatically work with your new class just as well as it could with the ones for which it was originally designed.
Think about interfaces as protocols and not classes i.e. does this object implement this protocol as distinct from being a protocol? For example can my number object be serialisable? Its class is a number but it might implement an interface that describes generally how it can be serialised.
A given class of object may actually implement many interfaces.

Correct way to lay out Interface C#

I'm having a problem designing part of my program (not writing it, for once!). This is kind of hard to explain without writing a novel, so I'll try and be brief.
Basically, I have a program which reads/writes parameters from a piece of hardware. Currently, it does so over Serial, but eventually, I'll like it to do so over USB, using the .NET wrapper for the FTDI chip http://www.ftdichip.com/Projects/CodeExamples/CSharp.htm
I think my problem is, I know I want several layers of abstraction, but I can't seem to know where to draw the lines. First, I don't want my ReadParam(), WriteParam(), and SendCommand() functions to be sitting in my main form class. That just seems cobbled. So obviously they should be in some other class, which I'll instantiate. Let's call that Comm for now.
The first option is, I could make an interface, lets say IComm, and have my Serial and USB flavors both implement that. The problem with this is, a large percentage of the code would be duplicated in both flavors, because I have special ReadReplyData() and other functions, that do pre-processing of the serial data before they return it to the GUI.
So the next option, is have Comm be an intermediary class, which defines an interface ICommDriver. Comm would implement a private ReadReplyData() formatting function, as well as the public ReadParam(), WriteParam(), and SendCommand() functions, while ICommDriver would specify only simpler Read and Write functions.
This all seems trivial except for two twists. One, I want this to be multi-theaded, obviously, so the GUI doesn't hang. So I'm thinking that Comm would use a BackgroundWorker to do all the reads/writes. Also, the Serial flavor needs to be told which COM port to open (from a GUI drop-down), while the USB flavor does not. So do I make that part of the interface or not?
Thanks for your help everyone, I've been writing/deleting code for days trying to figure out the correct way to do this!
Jonathon
I know I want several layers of
abstraction, but I can't seem to know
where to draw the lines
This is where your problem lies. It is a fundamentally flawed approach to development and it is exactly what leads to this paralysis. Develop several concrete implementations of the flavors first. Get them working in your application with kludgy if type1 else type2 logic. Then go back and refactor them all to share a common contract, common base, what have you. It will be blindingly obvious what needs to go where.
With more details in the comments:
If you have shared code between implementations, you should use an abstract class. In my experience it's best practice to keep the public methods final and call protected abstract methods from the public methods, like so:
public interface IComm
{
void WriteParam(...);
}
public abstract class CommStandardBase : IComm
{
public void WriteParam(...)
{
DoWriteParam(...);
}
private void DoWriteParam(...)
{
CommonWrite1(...);
HandleWriteParam(...);
CommonWrite2(...);
}
protected abstract void HandleWriteParam(...);
private void CommonWrite1(...)
{
...
}
private void CommonWrite2(...)
{
...
}
}
Make each class self-contained. It should be single-instance, single-threaded and can be passed between workers and reporters.
In regards to exactly which kind of interfaces you need, that is ultimately up to you and whoever knows how this application works at that low of a level. I would like to respond to the part about using your implementations in a UI, and the comment about Comm using a BackgroundWorker. I would recommend inverting that. BackgroundWorker is really a UI level component....but Comm would be more of a "central" component (like a business object in an enterprise application). Your UI should create a BackgroundWorker that then creates Comm instances to perform the required work, and orchestrate any events from your Comm to update the UI. If you need your UI and the BackgroundWorker to communicate over a lengthy duration of time, I would recommend creating some kind of data transfer object that your UI can create, drop in a queue, and use ManualResetEvent or AutoResetEvent threading handles to communicate between your UI thread and the BackgroundWorker. That should give you a more loosely coupled product, allowing you to develop your Comm class independantly of any kind of UI that may display it (possibly allowing you to have WindForms, WPF, Command line, and maybe even PowerShell clients.)
I am somewhat in VB.NET mode at the momement so here goes...
Interface IComm
Function ReadParam()
Function WriteParam()
Function SendCommand()
End Interface
>
MustInherit Class CommBase
.... Load this up with the overideable
End Class
Then just implement the interface and inherit the base if needed. I also agree with Rex M. Don't push it too far for loose coupling.