The concept of private - private

Private is a access specifier. It means that anything say a instance private declared private cannot be accessed by methods of another class.
What is the point of being private if it can be changed by public methods.
Maybe it is because either because my book's poor explanation or my understanding problem that I just don't get what private is.
The book says that being private is a process of hiding the data and providing methods for data access. (Encapsulation)
Also, here is a example where a error would occur. But I have no idea what is it:
public class BankRobber
{
BandAccount momSavings =
new BankAccount (1000);
...
momSaving.balance = -1000;
}}
A

The point of "private" is not to make it impossible for other classes to access the member, but to make it impossible for other classes to access the member except in ways that are allowed by the public (or protected) methods.

Related

How to implement a general class for singleton?

I've been trying to implement a state management project for my design patterns course. I have implemented the singleton because I know that's essential for keeping state of a class. What I would like to do is: Create a general class, so that others could use it in their projects. How do I do that? My code so far:
class StateManager{
static final StateManager _instance = StateManager._singleton();
StateManager._singleton();
factory StateManager(){
return _instance;
}
}
My other solution to try and make it general:
class AppProvider extends StateManager<AppProvider>{
int i = 10;
String data = "adas";
}
class StateManager<T extends AppProvider>{
static final StateManager _instance = StateManager._singleton();
StateManager._singleton();
factory StateManager(){
return _instance;
}
}
I want the AppProvider class to be the client class, and I want the StateManager to automatically handle the fact that AppProvider should be a singleton, and maintain the state of AppProvider.. I really don't know how to do that.
Forcing a class to be a singleton through inheritance alone is not going to work. That's not something that the language supports. Constructors are not inherited, neither are static members, and you need those to access the singleton.
In order to be able to create an instance of a class at all, the class needs a generative constructor.
That generative constructor will create a new instance every time it's invoked, because that's what generative constructors do.
For a subclass to be able to extend a class, the superclass must have an accessible generative constructor too, but at least the superclass can be made abstract.
In order to force a class to be a singleton (if you really want that, because a singleton is really something of an anti-pattern; it makes the class act like it's just a bunch of global variables, and that makes testing harder), each such class needs to have a public static way to access or create the instance, and a private generative constructor.
So, basically, your first approach does what is needed, and since the constructors are not inherited, you need to do that for every singleton class, and there is nothing useful to inherit.
So, there is nothing you can do with inheritance to make singleton-ness be inherited, and you can't even help because everything a singleton needs is static.
A different approach is to make the state classes entirely private, so you don't have to worry about someone else creating instances, and give them a constant generative constructor each, and then only refer to them using const _ThisState() or const _ThatState().
This puts the responsibility on the user (you!) to only create one instance of each state object, but it also gives a very easy way to do that, because const _ThisState() will provide the same instance every time.
Or use the enum pattern, and have:
abstract class State {
static const State thisState = const _ThisState();
static const State thatState = const _ThatState();
const State._();
void handle(Context context, Object argument);
}
class _ThisState implements State {
const _ThisState();
void handle(Context context, Object argument) { ... }
}
class _ThatState implements State {
const _ThatState();
void handle(Context context, Object argument) { ... }
}
and then just refer to the state instances as State.thisState. I find that more readable than creating instances of seemingly unrelated classes.

Properties in nested classes in VB.NET

I keep running into the error "Cannot refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class". I'm working on a VB.NET MVC application. I have a model that has top level security Properties contained within the top level class that should be available to classes within that class. My properties always follow this structure:
Private _SecurityVar = Nothing
Public Shared Property SecurityVar
Get
If _SecurityVar = Nothing Then
_SecurityVar = User.IsInRole("SecurityFunction")
End If
Return _SecurityVar
End Get
Set(value)
End Set
End Property
My problem is is that I can't access _SecurityVar b/c it's not shared. I don't want _SecurityVar available within my view, just SecurityVar. I then need to access these top level variables from within classes that are contained within this class, such as a list of orders. I don't want to simply return User.IsInRole("SecurityFunction") because I would then be hitting the database multiple times; which would be extremely inefficient, especially when it comes to building a large table. How do I get around this, is there a better way?
Instead of sharing.. make your subclasses aware of their parentage.
In the subclass add
Private myParent as <ParentClassName>
Public Sub New(Parent as <ParentClassName>)
MyParent = Parent
End Sum
In the parent class create the subclass using
Dim Child as New <YourSubClassName>(Me)
Then when you need something from the parent in the subclass
Var = myParent.<Property Name>
If you plan on moving those subclasses around you also need to make the _Parent Public or add a method so you can change it later.
If you don't want to allow the subclass full access to the parent class you can "group" your shared variables in another class in the parent and pass that instead.
Just make your private variable shared too
Private Shared _SecurityVar = Nothing

When to declare a callback method Private or Protected in ROR?

I was taking a look at some best practices in ROR, and I noticed that callback methods are declared in the protected section instead of the private. I've always used private when declaring callback methods, so I was wondering if it is better to use protected and why. Is there any substantial difference in this implementation?
private - only available to be accessed within the class that defines them.
protected - accessible in the class that defines them and in other classes which inherit from that class.

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..

Long method and testing private methods - design problem

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."

Resources