Long method and testing private methods - design problem - ruby-on-rails

I have a quite long method. It copy an ActiveRecord object with all relations, and changes relations in some cases. To make code more readable, I use private methods. I would like to test them. Technicaly, in Ruby it is no problem, but I suspect, I have bad design. Do you have any advices how to deal with such case?

One school of thought is that each and every private method that matters should be tested implicitly by testing a class's public interface. If a private method didn't get called through the public interface, it is redundant. If your private method is that complex to require its own tests, you should consider putting it in a class of its own and test that class.
In short, it shouldn't be necesary to explicitly test your private methods.
as the saying go's: "Don't touch your privates."

Related

Unit testing private method - objective C

I use GHUnit. I want to unit test private methods and don't know how to test them. I found a lot of answers on why to or why not to test private methods. But did not find on how to test them.
I would not like to discuss whether I should test privates or not but will focus on how to test it.
Can anybody give me an example of how to test private method?
Methods in Objective-C are not really private. The error message you are getting is that the compiler can't verify that the method you are calling exists as it is not declared in the public interface.
The way to get around this is to expose the private methods in a class category, which tells the compiler that the methods exist.
So add something like this to the top of your test case file:
#interface SUTClass (Testing)
- (void)somePrivateMethodInYourClass;
#end
SUTClass is the actual name of the class you are writing tests for.
This will make your private method visible, and you can test it without the compiler warnings.
A little late, but I just got onto the TDD train.
Private methods shouldn't be tested. Because you write private methods to support your public methods, thus testing your public methods indirectly tests the private methods which support them.
The principle "private methods shouldn't be tested" is supported by the principle "when you need to test private methods, it probably means that you should move those methods to the separate class", thus making them public.
If a method is private, you never should test it.
Think about this. You should test behaviour and contract of your methods instead internal implementation
Agreed with #Lord Zsolt
Also please note next (from Test-Driven iOS Development ISBN-10: 0-321-77418-3, ISBN-13: 978-0-321-77418-7 )
Testing Private Methods
I have often been asked, “Should I test my
private methods?” or the related question “How should I test my
private methods?” People asking the second question have assumed that
the answer to the first is “Yes” and are now looking for a way to
expose their classes’ pri- vate interfaces in their test suites.
My answer relies on observation of a subtle fact: You already have tested
your private meth- ods. By following the red–green–refactor approach
common in test-driven development, you designed your objects’ public
APIs to do the work those objects need to do. With that work specified
by the tests—and the continued execution of the tests assuring you
that you haven’t broken anything—you are free to organize the internal
plumbing of your classes as you see fit. Your private methods are
already tested because all you’re doing is refactoring behavior that
you already have tests for.
You should never end up in a situation
where a private method is untested or incompletely tested, because you
create them only when you see an opportunity to clean up the
implementation of public methods. This ensures that the pri- vate
methods exist only to support the class’s public behavior, and that
they must be invoked during testing because they are definitely being
called from public methods.

Rails: what are the main reasons for making methods private?

If the end_user cannot access the source code of the app, why we still need to make some methods private?
I'm reading the Pragmatic Agile Web Development with Rails and I couldn't understand why we need to make the following method private (even after reading the explanation):
private
def current_cart Cart.find(session[:cart_id])
rescue ActiveRecord::RecordNotFound
cart = Cart.create
session[:cart_id] = cart.id
cart
end
end
It says that it will never allow Rails to make it available as an action, but as a coder, why would I ever do that myself?
As you say there may be no external reason to make it private. However, it also prevents you — or somebody else using your code — from accidentally making use of the method where you're not supposed to.
See it as a sanity check on your own future behaviour if you will.
It aims to encourage good practices and good code.
The idea is that you have two separate parts to your code:
"Above the line" (Public). This is the interface to the rest of the world. This is the API, where calls are made when using instances of the object. Once created, you know that THIS is the area where changes can affect current usages of the code.
"Below the line (Private). This is where detailed logic resides. This code can be changed and refactored freely without any affect to the public interface.
It may help guide your test writing
Private methods may or may not be (unit) tested.
Public methods are more encouraging of both unit and integrated tests as the fact that is is public means that it is serving as the public face for that code and as it is public it might be called from any other point in the future, so having good tests to make sure it continues to work as advertised is essential.
It may help with security as you have greater control who calls private methods (i.e. only public methods in the same class calling them).
It may help reduce name collisions as you have less names in the public space.
End user might not be able to access your code but someone else in your team can definitely access it and they might change it.
The other benefit of encapsulation is that it allows one class ("server") to make a contract with another class ("client") to provide some service with only a very few things being required to be known about the "server" class such as method signature and return type. The benefit is only realized if the contract of what is required and what is returned remains the same. So, in your example, there is no benefit since the contract was broken by Class A.
Instead of class A changing int type to float, class A should create another new variable of type float for other classes to use so that class B is not "broken" or that contract is not broken between them. Class C could refer to new float variable and Class B could still refer to old int variable and everyone is happy. Better yet, methods would used to retrieve values such as: "getUsersAddress" and "getUSersPhoneNumber" depending on what was wanted.
The real benefit of good encapsulation is that Class A can be completely re-written from top to bottom and as long as the contract is honored as to what Class A is expected to do(have methods "getUsersAddress" and "getUSersPhoneNumber"), then everything in Class B and C works the same. Think carefully about what is exposed and how it is exposed. Things that will change often and break other classes need to be considered carefully before exposing. Good encapsulation means hiding things that are expected to change often so to avoid breaking other classes.
It says that it will never allow Rails to make it available as an action,
Hmm, is this in a Rails Conroller class? And is the book you are working through written for Rails 2.x?
In Rails 2.x, by default any public method in a Controller can be triggered by someone accessing the url /name_of_controller/name_of_method .
But there are some methods in your controller that you don't want anyone on the web to trigger, they weren't intended as 'action methods'. So in Rails 2.x, you mark those as protected or private, something not public. "action method" means a method you intend to be directly triggered via a URL.
In Rails 3.x, routing has generally changed such that only certain methods you explicitly route to are available to be triggered via a URL. However, it might still make sense to mark non-action-methods in a Controller as protected or private so:
It's more clear from skimming the source which methods are action methods and which aren't
As a precaution in case someone changes the routing in such a way that would allow a URL to trigger those methods not intended as action methods
Or for general reasons of code organization that other answers mention, that are not specific to Rails controller classes.
There are several reasons as mentioned above. The interesting thing about this encapsulation in ruby is that it can be violated.
See the "send" method and its brother "public_send".
And for a very common metaprogramming technique that uses this method see:
dynamic finders

When should we consider using private or protected?

Just wondering, when should we actually must use private or protected for some methods in the model?
Sometimes I can't not be bothered to group my methods in private nor protected. I just leave it as it is. But I know it must be a bad practice, otherwise these 2 groupings won't be created in programming.
Thanks.
If you plan to call a method externally, record.method(), then "public"
If it will be used only internally, self.method(), then "private"
If you plan to use it internally, but also in descendants, self.method() # in subclass, then "protected"
I'll give my opinion, and maybe I'll get a kicking for it, but I don't bother with protected or private in Ruby. The reality is, Ruby treats you like an adult, if you want to run a private method from outside the class, you can (there are ways). You can run protected methods outside the class. You can even reassign constants... you can do whatever you like, basically.
And that's why I like it, it's your responsibility. My feeling is, that to mark something as protected or private you are doing two things:
Indicating that you don't think a consumer will need it.
Second guessing what someone else needs.
and in addition, you're making it harder to test, as it can be a real pain testing private methods (see What's the best way to unit test protected & private methods in Ruby? for ways around it)
For those last two reasons, I don't bother with them. If you really wanted some kind of barrier between your classes/methods and the consumers (be they code or developers) then there are other, more effective ways (proxies, obfuscation, encryption, password protected methods etc). Otherwise, why not give them access to the same tools you used?
I don't know Ruby as a special case, but I assume the answer would be the same as for other languages too, so here it is:
A private method can only be accessed by members of the same class, whereas a protected is also available for member of classes that extend the base class where the method is declared.

access control tripping me up

ok, i'm about at that point in my ruby career where this should be tripping me up.
I have a model called distribution.rb where I have the follwoing protected method:
def update_email_sent_on_date
if self.send_to_changed?
self.date_email_delivered = DateTime.now
end
end
I then call this method from my controller:
distribution.update_email_sent_on_date
however, I'm getting this error:
NoMethodError (protected method `update_email_sent_on_date' called for #<EmailDistribution:0x131a1be90>):
the distribution object is indeed an EmailDistribution (a subclass of distribution where the method is defined). I thought this would work. In any case, I also tried moving the method to the subclass EmailDistribution but no luck. Same error message.
I'd also like to step back and say that what I'm trying to do overall is store the timestamp of when another field in the distribution model is updated. If there's a simpler way, please enlighten me.
I think you're getting tripped up because you are using the protected declaration when you actually want the private declaration.
The protected term in ruby acts differently in other conventional languages.
In Ruby, private visibility is what protected was in Java. Private methods in Ruby are accessible from children. This is a sensible design, since in Java, when method was private, it rendered it useless for children classes: making it a rule, that all methods should be "protected" by default, and never private. However, you can't have truly private methods in Ruby; you can't completely hide a method.
The difference between protected and private is subtle. If a method is protected, it may be called by any instance of the defining class or its subclasses. If a method is private, it may be called only within the context of the calling object---it is never possible to access another object instance's private methods directly, even if the object is of the same class as the caller. For protected methods, they are accessible from objects of the same class (or children).
This is a slightly clearer explanation IMHO, from the book Eloquent Ruby by Russ Olsen:
Note that in Ruby, private methods are callable from subclasses. Think about it: You don't need an explicit object reference to call a superclass method from a subclass.
The rules for protected methods are looser and a bit more complex: Any instance of a class can call a protected method on any other instance of the class.
Lastly, it's good to note that in ruby you can always call private or protected methods regardless of whether they are accessible by using the send method. So if you were in a pinch and just needed to work you could just call it like this and then worry about the private/protected declarations later:
distribution.send(:update_email_sent_on_date)
Read this for more a better explanation..

A pragmatic view on private vs public

I've always wondered on the topic of public, protected and private properties. My memory can easily recall times when I had to hack somebody's code, and having the hacked-upon class variables declared as private was always upsetting.
Also, there were (more) times I've written a class myself, and had never recognized any potential gain of privatizing the property. I should note here that using public vars is not in my habit: I adhere to the principles of OOP by utilizing getters and setters.
So, what's the whole point in these restrictions?
The use of private and public is called Encapsulation. It is the simple insight that a software package (class or module) needs an inside and an outside.
The outside (public) is your contract with the rest of the world. You should try to keep it simple, coherent, obvious, foolproof and, very important, stable.
If you are interested in good software design the rule simply is: make all data private, and make methods only public when they need to be.
The principle for hiding the data is that the sum of all fields in a class define the objects state. For a well written class, each object should be responsible for keeping a valid state. If part of the state is public, the class can never give such guarantees.
A small example, suppose we have:
class MyDate
{
public int y, m, d;
public void AdvanceDays(int n) { ... } // complicated month/year overflow
// other utility methods
};
You cannot prevent a user of the class to ignore AdvanceDays() and simply do:
date.d = date.d + 1; // next day
But if you make y, m, d private and test all your MyDate methods, you can guarantee that there will only be valid dates in the system.
The whole point is to use private and protected to prevent exposing internal details of your class, so that other classes only have access to the public "interfaces" provided by your class. This can be worthwhile if done properly.
I agree that private can be a real pain, especially if you are extending classes from a library. Awhile back I had to extend various classes from the Piccolo.NET framework and it was refreshing that they had declared everything I needed as protected instead of private, so I was able to extend everything I needed without having to copy their code and/or modify the library. An important take-away lesson from that is if you are writing code for a library or other "re-usable" component, that you really should think twice before declaring anything private.
The keyword private shouldn't be used to privatize a property that you want to expose, but to protect the internal code of your class. I found them very helpful because they help you to define the portions of your code that must be hidden from those that can be accessible to everyone.
One example that comes to my mind is when you need to do some sort of adjustment or checking before setting/getting the value of a private member. Therefore you'd create a public setter/getter with some logic (check if something is null or any other calculations) instead of accessing the private variable directly and always having to handle that logic in your code. It helps with code contracts and what is expected.
Another example is helper functions. You might break down some of your bigger logic into smaller functions, but that doesn't mean you want to everyone to see and use these helper functions, you only want them to access your main API functions.
In other words, you want to hide some of the internals in your code from the interface.
See some videos on APIs, such as this Google talk.
Having recently had the extreme luxury of being able to design and implement an object system from scratch, I took the policy of forcing all variables to be (equivalent to) protected. My goal was to encourage users to always treat the variables as part of the implementation and not the specification. OTOH, I also left in hooks to allow code to break this restriction as there remain reasons to not follow it (e.g., the object serialization engine cannot follow the rules).
Note that my classes did not need to enforce security; the language had other mechanisms for that.
In my opinion the most important reason for use private members is hiding implementation, so that it can changed in the future without changing descendants.
Some languages - Smalltalk, for instance - don't have visibility modifiers at all.
In Smalltalk's case, all instance variables are always private and all methods are always public. A developer indicates that a method's "private" - something that might change, or a helper method that doesn't make much sense on its own - by putting the method in the "private" protocol.
Users of a class can then see that they should think twice about sending a message marked private to that class, but still have the freedom to make use of the method.
(Note: "properties" in Smalltalk are simply getter and setter methods.)
I personally rarely make use of protected members. I usually favor composition, the decorator pattern or the strategy pattern. There are very few cases in which I trust a subclass(ing programmer) to handle protected variables correctly. Sometimes I have protected methods to explicitly offer an interface specifically for subclasses, but these cases are actually rare.
Most of the time I have an absract base class with only public pure virtuals (talking C++ now), and implementing classes implement these. Sometimes they add some special initialization methods or other specific features, but the rest is private.
First of all 'properties' could refer to different things in different languages. For example, in Java you would be meaning instance variables, whilst C# has a distinction between the two.
I'm going to assume you mean instance variables since you mention getters/setters.
The reason as others have mentioned is Encapsulation. And what does Encapsulation buy us?
Flexibility
When things have to change (and they usually do), we are much less likely to break the build by properly encapsulating properties.
For example we may decide to make a change like:
int getFoo()
{
return foo;
}
int getFoo()
{
return bar + baz;
}
If we had not encapsulated 'foo' to begin with, then we'd have much more code to change. (than this one line)
Another reason to encapsulate a property, is to provide a way of bullet-proofing our code:
void setFoo(int val)
{
if(foo < 0)
throw MyException(); // or silently ignore
foo = val;
}
This is also handy as we can set a breakpoint in the mutator, so that we can break whenever something tries to modify our data.
If our property was public, then we could not do any of this!

Resources