Testing/TDDing Private Methods [closed] - testing

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Yet ANOTHER post about testing private methods, but this one I hope will be a little different to the norm.
People are always wondering whether a private method should in fact be public or the functionality extracted into another class where it can be tested, or end up making other compromises.
Many programming/scripting languages off a Reflections class, so with that in mind, why can't we automate a way of making our private methods testable? For example, let's say we have a class with a private method that we want to test, surely something like this will work:
class ClassWeWantToTest {
private somePrivateMethod([args, ...]) {
// Do stuff.
}
}
class ClassWeWantToTest_TestWrapper extends ClassWeWantToTest {
public somePrivateMethod_test([args, ...])
{
return this->somePrivateMethod([args, ...]);
}
}
Such testing layers can be made manually and automatically in languages that allow it. There could even be a third party tool that understands the syntax, which will parse a class and generate a layer. Obviously, private methods will only be made public to the tests. In normal use, the private methods remain private.
Why hasn't it been done already? Is this a really stupid idea? I assume it is because it hasn't been done already. It would certainly help with class-clutter, where classes are just being created to help with testability. I know, it would expose the entire class, but so what? The developer knows how it works and can now test more aspects of his code without having to work blind. The developer would be able to work with the class with or without the wrapper which would give even more flexibility.

Many programming/scripting languages off a Reflections class, so with that in mind, why can't we automate a way of making our private methods testable?
You can, but you are putting the priorities the wrong way around.
The point of TDD is to improve your designs. One important element of the design is that the parts that are important to test are also easy/cost-effective to test.
Writing the same spaghetti code we've always written, but with tests, misses this.
More broadly, if you have a "private" method that is complicated enough that you aren't comfortable with the risks when you are only testing the public interfaces, then that's a big hint that what you really have is a concept that is separate and distinct from that of the enclosing method/class. Ergo, the remedy is to redesign your solution so that you can get your test probes where you want them.
You may want to review Martin Fowler on Published methods
There's something to be said for the public-published distinction being more important than the more common public-private distinction.

Related

Why is public/private such an important programming aspect? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Why do in most programming languages do you get the ability to have private and or public methods/functions classes and properties?
Does it make much of a difrence to let's say.. have all classes, methods and properties be public?
I know that if you have all your methods, classe ans properties set to private nothing will work.
So at least I know that much.
But does the distinction between the two matter? What's the big deal if one class knows another Class "that is meant to be private" exists?
When you make something public, you enter a contract with the user class: "Hey, this is, what I offer, use it or not." Changing the public interface is expensive, because you have to change all code using that public interface, too. Think of a developer of a framework like Cocoa used by thousands of developers. If you change one public methods, for example removing one, thousands of apps break. They have to be changed, too.
So making everything public simply means that you cannot change anything anymore. (You can, but the people will get angry at one point.)
Let's think of having a class implementing a list. There is a method to sort it: sortListWithKey. You make that public because you want the users of the class to get a sorted list. This is good.
There are several algorithms for sorting. Let's say, you implement one that needs to calculate the meridian (the middle element). You need this method internally for your sorting algorithm. So it is enough, to implement it privately. Changing the whole structure of data holding including the implemented sorting algorithm is no problem and will not break existing code using that class.
But if you made the meridian method public (remember: you implemented it, because you needed it internally), you still have to keep it, even the new sorting algorithm does not need it. You cannot remove it anymore, even with the new structure it is very hard (and/or expensive) to keep the method.
So make that part of your implementation public that is useful for the users, but no more. Otherwise you shackle yourself.
If humans had perfect memory, documentation and communication skills, and made no mistakes, then there might not be a useful difference. But using or changing something from the wrong file and then forgetting about it (or not documenting it clearly for the rest of the team, or yourself in the future) is too common a cause of hard-to-find bugs.
Marking things private makes it a bit more work to create the same types of bugs, and thus less likely that lazy/sleepy programmers will do all that extra work just to mess up the application.
In computer science it is called information hiding. You, as a programmer, want to offer only necessary methods or properties to other programmers which will use your public API and this is the way how you can achieve so-called low coupling between modules.

What are the pros and cons of creating a new class? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
This is a probably a very basic question, but it's one I'm actually running into as I'm learning more about Actionscript 3 in particular. However, my first question is very general: When is appropriate to put functionality in a new class rather than a new function in the same class? According to this Java tutorial, which focuses on basic object-oriented principles, a class is supposed to be a "blueprint of an object". I always understood this to mean that any functionality or behavior that the object would use should be contained within the class. However, according to the single responsibility principle, each class should have only one reason to change. For example, you should have one class to compile a report and one class to print it rather than a single Report class.
Can you guys help me understand the pros and cons to creating a new class? What are the costs to splitting an object into multiple classes? Are there compile-time or performance costs for keeping related functionality in the same class, or for splitting it into two? Are there perhaps times that you would want to split things out, while you might want to keep them together other times?
As far as I remember, there isn't a big difference between having 1 class which can do everything or several classes which can do the same.
It's about readability and how you can extend the code. It's also just about clean code and coupling.
If you have a class called "Printer" you don't want to have "WaterCoolerSound()" in it. Of course the more objects you have the higher the chance is that you can run out of memory. But I am not entirely sure whether one object with all functionality or several classes with the same functionality spread out, takes more memory.
In fact, you could say that if you JUST need a little bag to hold on to some data and not be able to dance like a bear at the same time, it would make sense to have two separate classes.
It's advisable not to think about the performance before you have the code. From the maintainability and understandability viewpoint, of course, smaller classes, with smaller methods are superior. (see The Single Responsibility Principle again :)
Don't get so confused about making classes for just a function. A class should have only related functions.If the functions are of different kinds which will do totally different functionalities and use totally different kind of variables then only u should make a separate class.

Private vs Protected - Visibility Good-Practice Concern [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I've been searching and I know the theoretic difference.
public - Any class/function may access the method/property.
protected - Only this class and any subclasses may access the method/property.
private - Only this class may access the method/property. It won't even be inherited.
That's all fine and well, the question is, what's the practical difference between them? When would you use private and when would you use protected? Is there a standard or acceptable good practice over this one?
Up until now, to retain the concept of inheritance and polymorphism, I use public for anything that should be accessed from the outside (like constructors and main class functionality), and protected for internal methods (logic, helper methods etc). Am I on the right track?
(Note that this question is for me, but also for future reference as I haven't seen a question like this one SO).
No, you're not on the right track. A good rule of thumb is: make everything as private as possible. This makes your class more encapsulated, and allows for changing the internals of the class without affecting the code using your class.
If you design your class to be inheritable, then carefully choose what may be overridden and accessible from subclasses, and make that protected (and final, talking of Java, if you want to make it accessible but not overridable). But be aware that, as soon as you accept to have subclasses of your class, and there is a protected field or method, this field or method is part of the public API of the class, and may not be changed later without breaking subclasses.
A class that is not intended to be inherited should be made final (in Java). You might relax some access rules (private to protected, final to non-final) for the sake of unit-testing, but then document it, and make it clear that although the method is protected, it's not supposed to be overridden.
Let me preface this by saying I'm talking primarily about method access here, and to a slightly lesser extent, marking classes final, not member access.
The old wisdom
"mark it private unless you have a good reason not to"
made sense in days when it was written, before open source dominated the developer library space and VCS/dependency mgmt. became hyper collaborative thanks to Github, Maven, etc. Back then there was also money to be made by constraining the way(s) in which a library could be utilized. I spent probably the first 8 or 9 years of my career strictly adhering to this "best practice".
Today, I believe it to be bad advice. Sometimes there's a reasonable argument to mark a method private, or a class final but it's exceedingly rare, and even then it's probably not improving anything.
Have you ever:
Been disappointed, surprised or hurt by a library etc. that had a bug that could have been fixed with inheritance and few lines of code, but due to private / final methods and classes were forced to wait for an official patch that might never come? I have.
Wanted to use a library for a slightly different use case than was imagined by the authors but were unable to do so because of private / final methods and classes? I have.
Been disappointed, surprised or hurt by a library etc. that was overly permissive in it's extensibility? I have not.
These are the three biggest rationalizations I've heard for marking methods private by default:
Rationalization #1: It's unsafe and there's no reason to override a specific method
I can't count the number of times I've been wrong about whether or not there will ever be a need to override a specific method I've written. Having worked on several popular open source libs, I learned the hard way the true cost of marking things private. It often eliminates the only practical solution to unforseen problems or use cases. Conversely, I've never in 16+ years of professional development regretted marking a method protected instead of private for reasons related to API safety. When a developer chooses to extend a class and override a method, they are consciously saying "I know what I'm doing." and for the sake of productivity that should be enough. period. If it's dangerous, note it in the class/method Javadocs, don't just blindly slam the door shut.
Marking methods protected by default is a mitigation for one of the major issues in modern SW development: failure of imagination.
Rationalization #2: It keeps the public API / Javadocs clean
This one is more reasonable, and depending on the target audience it might even be the right thing to do, but it's worth considering what the cost of keeping the API "clean" actually is: extensibility. For the reasons mentioned above, it probably makes more sense to mark things protected by default just in case.
Rationalization #3: My software is commercial and I need to restrict it's use.
This is reasonable too, but as a consumer I'd go with the less restrictive competitor (assuming no significant quality differences exist) every time.
Never say never
I'm not saying never mark methods private. I'm saying the better rule of thumb is to "make methods protected unless there's a good reason not to".
This advice is best suited for those working on libraries or larger scale projects that have been broken into modules. For smaller or more monolithic projects it doesn't tend to matter as much since you control all the code anyway and it's easy to change the access level of your code if/when you need it. Even then though, I'd still give the same advice :-)
Stop abusing private fields!!!
The comments here seem to be overwhelmingly supportive towards using private fields. Well, then I have something different to say.
Are private fields good in principle? Yes. But saying that a golden rule is make everything private when you're not sure is definitely wrong! You won't see the problem until you run into one. In my opinion, you should mark fields as protected if you're not sure.
There are two cases you want to extend a class:
You want to add extra functionality to a base class
You want to modify existing class that's outside the current package (in some libraries perhaps)
There's nothing wrong with private fields in the first case. The fact that people are abusing private fields makes it so frustrating when you find out you can't modify shit.
Consider a simple library that models cars:
class Car {
private screw;
public assembleCar() {
screw.install();
};
private putScrewsTogether() {
...
};
}
The library author thought: there's no reason the users of my library need to access the implementation detail of assembleCar() right? Let's mark screw as private.
Well, the author is wrong. If you want to modify only the assembleCar() method without copying the whole class into your package, you're out of luck. You have to rewrite your own screw field. Let's say this car uses a dozen of screws, and each of them involves some untrivial initialization code in different private methods, and these screws are all marked private. At this point, it starts to suck.
Yes, you can argue with me that well the library author could have written better code so there's nothing wrong with private fields. I'm not arguing that private field is a problem with OOP. It is a problem when people are using them.
The moral of the story is, if you're writing a library, you never know if your users want to access a particular field. If you're unsure, mark it protected so everyone would be happier later. At least don't abuse private field.
I very much support Nick's answer.
I read an article a while ago that talked about locking down every class as much as possible. Make everything final and private unless you have an immediate need to expose some data or functionality to the outside world. It's always easy to expand the scope to be more permissible later on, but not the other way around. First consider making as many things as possible final which will make choosing between private and protected much easier.
Make all classes final unless you need to subclass them right away.
Make all methods final unless you need to subclass and override them right away.
Make all method parameters final unless you need to change them within the body of the method, which is kinda awkward most of the times anyways.
Now if you're left with a final class, then make everything private unless something is absolutely needed by the world - make that public.
If you're left with a class that does have subclass(es), then carefully examine every property and method. First consider if you even want to expose that property/method to subclasses. If you do, then consider whether a subclass can wreak havoc on your object if it messed up the property value or method implementation in the process of overriding. If it's possible, and you want to protect your class' property/method even from subclasses (sounds ironic, I know), then make it private. Otherwise make it protected.
Disclaimer: I don't program much in Java :)
When would you use private and when would you use protected?
Private Inheritance can be thought of Implemented in terms of relationship rather than a IS-A relationship. Simply put, the external interface of the inheriting class has no (visible) relationship to the inherited class, It uses the private inheritance only to implement a similar functionality which the Base class provides.
Unlike, Private Inheritance, Protected inheritance is a restricted form of Inheritance,wherein the deriving class IS-A kind of the Base class and it wants to restrict the access of the derived members only to the derived class.
Well it is all about encapsulation if the paybill classes handles billing of payment then in product class why would it needs the whole process of billing process i.e payment method how to pay where to pay .. so only letting what are used for other classes and objects nothing more than that public for those where other classes would use too, protected for those limit only for extending classes. As you are madara uchiha the private is like "limboo" you can see it (you class only single class).

How should I document a inherited members? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
Consider that I have a complex class structure where many elements inherit from other elements. I may have a method GetStuff(string stuffName, int count) defined in an interface, which is inherited by other interface, which is then implemented abstractly by an abstract class, which is then implement explicit in a concrete class etc. etc...
How should I handle inherited members such as GetStuff() when documenting my code with XML comments which will be used with a tool such as Doxygen or Sandcastle? It seems wrong to just copy and paste the same description at each level. Should I be considering a different audience at the interface level vs the concrete class level? For example the documentation for GetStuff() at the interface may consider people implementing the interface, whereas the documentation at the concrete level may instead consider people who will be using the class?
Document the interface method according to its code contract. Do not comment on its implementation, only on its semantic purpose, i.e. what it’s supposed to do, not how. The audience for this documentation is both your implementors and your users: the method will both be implemented as well as called.
Document the abstract method simply by saying that it implements the interface method and linking to it. There is nothing extra to be said about it, and duplicating the comment violates the DRY (Don’t Repeat Yourself) principle: you would have to remember to make any change to it in both places. (Of course, in the case of an abstract method that doesn’t implement an interface method, document it in the same way that you would document an interface method.)
Document the concrete implementation by saying that it implements the interface method and/or that it overrides the abstract member. Optionally add information about its implementation if it is relevant to the caller — for example, its performance characteristics, or situations in which it might throw, etc.
remark
on part of post
by Eric Anastas
It seems wrong to just copy and paste
the same description at each level.
I can imagine it being wrong to just copy. It is however possible to let doxygen copy it for you and then change what you would like to change for that implementation/scope.
For more information, you can look at the description for #copydoc.

Correct software-engineering approach to make Lua bindings to my C++ classes? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to figure out the best way to register my C++ Classes constructors with Lua (from a software design perspective, not a coding perspective)
How shall I do this ?
My Ideas:
1) Make some kind of "init Lua bindings" file which binds each of the C++ constructors that I want to have available in Lua ? (problem: this file would tend to get bigger and bigger and difficult to sync/debug)
2) Each class is responsable to register it's own constructor with my "LuaManager" Class
(problem: it would be stupid to bind the same constructor to Lua over and over again for the same Class of kind A, so ideally, each kind of scriptable Class should bind it's constructor with Lua only Once when using this approach.)
Ideas, or opinions are very welcome.
I understand what you mean by asking
from a software design perspective,
not a coding perspective
however I'm not sure there's clear distinction between the two. Or, more correctly, the coding approach you take will determine your design options. For example, if you use SWIG, the options in your question don't really make sense, since you write a separate "interface" file. If you are using luabind, the options do make sense, but I would definitely choose 1) in that case as luabind headers slow compilation dramatically and I'd like to have them included in as few compilation units as possible. If your "coding" approach doesn't have that luabind shortcoming then 2) seems like the more sensible thing to do.
Your second approach will work well. One way to avoid multiple registrations is to use a static initialization list approach. Each class would add a Lua registration function to a static std::set pre-main. Then you'd walk this std::set when your application starts and add each class constructor binding to your Lua runtime. This would ensure your class bindings are registered only once.