In OOP why need to put something Private , for example. I know that any private member can not be accessed but with the same class objects. But why I need to do that while I am the only coder of my project. The same question extends to Protected, protected from who!
private and protected are not there to prevent other coders from accessing the internals of a class, but (also) to prevent yourself from creating a program without clearly defined interfaces.
If every class in your project can modify every other class, you're not only prone to introduce bugs because of the huge state space, but also preventing yourself from:
Changing the implementation (while keeping the interface the same) of any class.
Ever introducing anyone not familiar with all the internals of all the classes to the project. Unless you have a perfect memory and can recite every line of code you've ever written, that includes future you.
Mocking up objects for unit testing
Interacting with other versions of your program/library. Suppose you do change internals of one class, and you manage to track down every reference to that internal property in your project. Even then, you may need to interface with the old version of your program again. This becomes especially hard if used properties instead of getter/setter methods.
Access modifiers achieve two different things:
They limit the amount of code that can cause side effects, making it easier to establish invariants.
They protect clients of the class from changes to the internal representation.
For small projects, these advantages might not be immediately visible, especially for beginners.
Protected from your future self, who could otherwise accidentally forget what parts of an object are a detail that should be decoupled from the rest of the system, and which parts are a solid interface that can be relied on by the rest of the system.
the language tries to force you, to write "good" code. "good" means that the code is structured, clean and not susceptible to error. so you have to declare types, private members and so on. if you don't want that, you could use a language thats lesser in this aspects, like python. but this means, that your program could (could!) be more insecure or if it gets very big, easy to misunderstand. it's the same as with comments. you haven't to write them. especially when you are the only programmer. but it's a good style and you will be very thankfull for that if you read your program again, in a half year.
You mark the members of a class private that must not be accessed from outside the class. E.g., you use it to hide implementation details, so you can change the implementation without affecting other code using your class. Hiding implementation details is one of the key aspects of OOP (encapsulation). If you create a Car class, and then you write a lot of code that uses the Car class, and you suddenly realize that your implementation performs very poorly and you need to refactor it, if all of the Car implementation details are private to the Car class, you know that none of the code using Car accesses those things and you can change them at will. If you didn't mark them private, you might have used some of them in that other code, which would then break.
Similarly, protected (in Java, anyway) is for the same purpose but allows classes derived from your class to access those members. This is fairly weak protection, because of course it means that you can't change the implementation details of the base class without affecting derived classes.
Think about it this way: The protection level defines what you can change later without care for any other piece of code besides this class (private), without care for any other piece of code besides this class and every class inheriting from this class (protected) and without care for any other piece of code besides every piece of code using this class (public).
private or protected come from encapsulation concept. and it comes from data hiding concept. I believe this intoduction is clear and useful at least for me :
Encapsulation is the process of combining data and functions into a
single unit called class. Using the method of encapsulation, the
programmer cannot directly access the data. Data is only accessible
through the functions existing inside the class. Data encapsulation
led to the important concept of data hiding. Data hiding is the
implementation details of a class that are hidden from the user. The
concept of restricted access led programmers to write specialized
functions or methods for performing the operations on hidden members
of the class. Attention must be paid to ensure that the class is
designed properly. (Sripriya Rajagopalan)
Note: Answers are well, and this answer is to complete them
If you define a member (variable or method) of a class as private, you won't be able to use it from outside, using another class, using the dot operator. Protected helps you to protect the member variable or method from being inherited.
Related
I am in a Introduction to Java class and I was doing a bit of research on variables. It seems that knowledgeable programers state that it is bad practice to define the variables in public visibility. I see them stating it is bad practice but I can not find a rhyme or reason to their claims. This is how I defined my variables in a application for my course.
public class DykhoffWk3Calculator
{
/*
* This class is used to define the variables in a static form so all
* classes can access them.
*/
public static double commissionRate = .03, startSalary = 45000,
accelerationFactor = 1.25;
public static double annualSales, commissionTotal, totalCompensation,
total, count, count2;
private static Object input; Object keyboard;
public static class UserInput
{ //Then continue with my other classes
I thought this was a logical method of defining them so all classes, not just main, could access them. Can someone explain to me why this is bad practice, and where variables should be defined? Any assistance would be greatly appreciated.
In short: because all of your public "surface area" for a class effectively defines its API.
If you expose things through methods, then you can change the details of how they work later. But if you expose a field, and some other class outside of your control (and quite possibly outside of your knowledge) starts referencing that field, then you're stuck with exposing that field for the rest of time. Or until you decide to break backwards-compatibility.
I thought this was a logical method of defining them so all classes, not just main, could access them.
As a general rule, you don't want "all classes" to access them. The vast majority of work with software, is spent maintaining code, not writing it for the first time. And so experienced developers realise that best practices for code, are generally the ones that make it most maintainable, not necessarily the ones that make it most convenient to write in the first place.
And if you have a variable that could be accessed from anywhere, at any time, and you want to make some tweaks to how it is modified - how can you be sure that this is safe? How long will it take you to track down all the ways that this is referenced, and determine what the effects of your change will be? (And specific to public fields, you can kiss goodbye to any sort of reusability regarding running at the same time from multiple threads, or running reentrantly.)
Broadly speaking, reducing the "surface area" of classes is a really good thing to do. Restricting the ways that other classes can interact with this one, makes it much easier to control and understand the relationships, as well as making it easier to make internal changes "invisible" to those other classes. Think about what this class does, what it will provide to other classes, as defining an interface (whether an actual interface or not). And only expose to other classes, the bare minimum that is required to fulfil those requirements.
And that never involves letting them have arbitrary access to variables.
So the general point is that you in fact DON'T want anyone to be able to access those values. Not only can I see those variables, but I can also change them to anything I like. This can lead to problems in larger, more complex programs.
Furthermore, if you wanted to later change how the class uses/stores these values, you couldn't without having to go out and change all the other classes that access those public variables directly. Instead, you should offer methods that provide just the amount of access that you want to give.
The standard analogy is that of driving a car. You know how to turn the wheel, hit the brake, etc, but not how the car actually does these things. So if the engine needed to be dramatically changed, or you got in a new car, then you'd still know how to drive. You don't need to worry about what's happening behind the scenes.
Firstly you state it wrong.
its bad to make your variable public i.e:
public String name = null; this is bad. You should always do it as
private String name = null;
To understand why, you need to dig a bit into the ideology of OOPs
OPPS ideology states that each object of your class will have 2 things:
Properties: something which we also call variables or state.
Behavior: something which we call methods or functions.
Properties identify the object over a period of time. Behaviors allow you to manage the properties of the object so that the same object over time can appear to be in different states.e.g: a Product object over a period of can be an 'Available line item' or 'Added to cart' or 'Sold' or 'Out of stock' depending on its state. Since state is critically important to the object so the object should not allow direct nonsense mutation operations on its state. Objects should keep their variables private to them and expose behaviors that the outside world can use to interact with the object and change the state based on the operation executed in the behavior. e.g: calling the 'addToCart()' behavior on the Product object that was in 'Available line item' state would probably mean: changing not just its state to 'Added to cart' but probably making other users aware that the number of this Products now available is 1 less.
So long story short: don't expose properties directly to outside work for mutation unless needed. This means dont make them public and also dont give setter methods if not needed.
By Convention Fields, methods and constructors declared public (least restrictive) within a public class are visible to any class in the Java program, whether these classes are in the same package or in another package.Which means that a change in the value of a field will definitely affect other classes accessing that field..thus breaking the whole sense of encapsulation.
Public variables in general in a class are a bad idea. Since this means other classes/programs, can modify the state of instances.
Since it is the responsibility of a class to protect its state and ensure the state is "consistent", one can enforce this by defining public setters (since this allows to run code to check/repair state).
By setting the variables public, the state is not protected. If later not all representable states are valid states, one has a problem.
Example:
Say you want to implement an ArrayList<T>, then it will look like (not fully implemented):
public class ArrayList<T> {
public int size = 0;
public Object[] data = new Object[5];
}
Now one can modify the size of the arrayList. Without adding an element. Now if you would ask the ArrayList<T> instance to remove/add/copy/...whatever, the data on which it works can be wrong.
Perhaps you can claim that a programmer is nice: he will not modify the object unless he needs to and according to the "rules". But such things eventually always go wrong, and what if you decide to modify your definition of the ArrayList (for instance using two int's for the size). In that case you would need to rewrite all code that sets such fields.
To conclude: private/protected is invented to protect a class instance from other instances that would turn the instance corrupt/invalid/inconsistent/...
It's been told me (and I have seen this statement in a few other places) that it's not recommended to store your constants in a separate class in Java, in order to use them in the other classes. But I haven't seen anywhere WHY is it so. What is the reason I should not store them in their own interface/class?
I came from C to Java and in C i would just make a .h file where i defined constants with #define
Constants in a dedicated file are frowned upon for stylistic reasons. Having a class dedicated to constants can encourage developers to add increasing numbers of unrelated (undocumented?) constants to a file that slowly bloats out of control.
By contrast, having constants associated with the classes they are related to is a more scalable and readable design.
So you can be an engineer and measure constants and their locations as a technical choice. This is great and fine when you work on performance critical systems or on cool small snippets. Once your application tends to grow however, it becomes harder and harder to grasp the business requirements and end-user needs reflected in the code.
So instead of thinking about style -- separate class, properties file or nested inside a class -- I tend to follow domain driven design -- if the set of constants exclusively belong to a specific class (entity), nest the constants; if the concept touches more than one of the entities in your domain model, feel free to make it a separate entity.
And please do remember, that since Java 5, you do have enums at your disposal.
A separate constants class is not object-oriented design. In OO, a class (or interface) represents a contract, and a class which only contains constants does not define any contract.
Another object-oriented consideration is that a separate constants class encourages misuse of inheritance. Inheritance is supposed to indicate that a class fully adheres to the contract defined by another class or interface. Inheritance should not be used just to share functionality or constants; that's what public methods and fields are for. Thus, this code is incorrect:
class SomeApplicationClass
implements ScrollPaneConstants // Incorrect, import ScrollPaneConstants instead
Issue is that they should be living outside of your source code entirely. You should be using something like Apache Commons Config, or at least loading from a .properties file.
I will also note that I'm interpreting "single" with respect to a reasonable scope. For instance, there should not be one Config file for all Java developers used stored on Google's servers with a request form for modifying. There probably should not be done for your entire code base; however, per UOR or package is a reasonable scope, and is the one I use in practice.
why we use private keyword?i know it limits the access to a var or a method,but why we have to limit the access?
If you expose all of the methods and variables publicly, when another programmer tries to do something with a class you have written it will be really hard because he wont know which methods take care of the internal behavior of your class, which are the methods he is not supposed to use because he would mess up the internal state of the objects and cause a bug.
You don't "have to" do anything of the sort. It's just good practice to only expose that which absolutely must be exposed, especially when you're creating a large program where connections increase exponentially, and risk of side effects increase with it. It's really all about managing complexity. Read up on encapsulation and information hiding and how this helps reduce complexity in large systems. A good book is Grady Booch's Object-Oriented Design for more on this.
In OO world to achieve encapsulation it is very essential to understand the functionality or behavior of object you would like to expose and each access identifier plays important role in it.In Code Complete book McConnell strongly encourages making all variables private.
Consider you are building a utility library and you are going to expose methods to external world as utilities. But those methods may call few methods which are private. So calling those private methods directly may not make any sense and in worst case, they may even harm the state of the object too. There are lots of examples to explain the usage of private even in jdk.
In String class, there is a private method checkBounds which just checks for valid constructor arguments in case of public String(byte bytes[], int offset, int length, String charsetName)
Exposing this method (making it public) makes no sense for String class.
private as the name implies it is something which resides private/unaccessable from the outer class. Object Oriented Programming language has one important concept called Encapsulation which means to restrict the access to some of the object's components. While developing a code you need to hide some objects from the other class, in these case delete those object/variable as private. A private access is only to the class where is it defined.
I was wondering why Java has been designed without the frienddirective that is available in C++ to allow finer control over which methods and instance variables are available from outside the package in which a class has been defined.
I don't see any practical reason nor any specific drawback, it seems just a design issue but something that wouldn't create any problem if added to the language.
Here are a few reasons off the top of my head:
friend is not required. It is convenient, but not required
friend supports bad design. If one class requires friend access to another, you're doing it wrong. (see above, convenient, not required).
friend breaks encapsulation. Basically, all my privates are belong to me, and that guy over there (my friend).
In general i think it was because of the added cognitive complexity and low number of cases in which it creates an improvement.
I would say that the extremely huge number of lines of java in production at this moment can attest that the friend keyword is not really a big loss :).
Please see #dwb's answer for some more specific reasons.
Only a very naive and inexperienced programmer would advocate against friends. Of course it can be misused, but so can public data, yet that capability is provided.
Contrary to popular opinion, here are many cases, in particular for infrastructure capabilities, where friend access leads to BETTER design, not worse design. Encapsulation is often violated when a method is FORCED to be made public when it really shouldn't be, but we are left with no choice because Java does not support friends.
In addition to the aforementioned package visibility, Java also offers inner and anonymous classes which are not only friends by default, but also automatically have a reference to the containing class. Since creating such helper classes is probably the only reasonable way to use friend in C++, Java doesn't need it since it has another mechanism for that. Iterators are a very good example of this.
Completely agree with spaceghost's statement in his answer
Contrary to popular opinion, here are many cases, in particular for infrastructure capabilities, where friend access leads to BETTER design, not worse design.
My example is simple - if a class A has to provide a special "friend" interface to class B in java we have to place them into the same package. No exceptions. In that case if A is a friend of B and B is a friend of C, A has to be a friend of C which isn't always true. This "friendship transitivity" breaks encapsulation more then any problems which C++ friendship could lead to.
Why not simply think that Java requires friend classes to be co-located ? The package-private visibility allows everyone from the same package to access those members. So you're not only limited to explicitly declared friends, but you allow any (existing or future) friend to alter some members that are specifically designed for this purpose (but not your private stuff). You're still able to fully rely on encapsulation.
Just to add to the other answers:
There is the default package visibility in Java. So, you could call all classes in the same package neighbors. In that case you have explicit control of what you show to the neighbors - just members with package visibility.
So, it's not really a friend but can be similar. And yes, this too leads to bad design...
In my opinion some kind of friend feature (not necessarily very similar to C++'s) would be very helpful in some situations in Java. Currently we have package private/default access hacks to allow collaboration between tightly coupled classes in the same package (String and StringBuffer for instance), but this opens the private implementation interface up to the whole package. Between packages we have evil reflection hacks which causes a whole host of problems.
There is a bit of an additional complication in does this in Java. C++ ignores access restrictions whilst resolving function overloads (and similar) - if a program compiles #define private public shouldn't do anything. Java (mostly) discards non-accessible members. If friendship needs to be taken into account then the resolution is more complicated and less obvious.
I have an application that has several classes used for storing application-wide settings (locations of resources, user settings, and such). Right now these classes are just full of static fields and methods, but I never instantiate them.
Someone suggested I make them Singletons, What's the case for/against?
I consider the Singleton pattern to be the most inappropriately applied design pattern. In ~12 years of software development I'd say I've maybe seen 5 examples that were appropriate.
I worked on a project where we had a system monitoring service that modeled our system with a System class (not to be confused with Java's built-in System class) that contained a list of Subsystems each with a list of Components and so on. The designer made System a Singleton. I asked "Why is this a Singleton?" Answer: "Well, there is only one system." "I know, but, why did you make it a Singleton? Couldn't you just instantiate one instance of a normal class and pass it to the classes that need it?" "It was easier to just call getInstance() everywhere instead of passing it around." "Oh..."
This example is typical: Singletons are often misused as a convenient way to access a single instance of a class, rather than to enforce a unique instance for technical reasons. But this comes at a cost. When a class depends on getInstance(), it is forever bound to the Singleton implementation. This makes it less testable, reusable, and configurable. It violates a basic rule I follow and that probably has a common name in some design principles essay somewhere: classes should not know how to instantiate their dependencies. Why? Because it hardcodes classes together. When a class calls a constructor, it is bound to an implementation. getInstance() is no different. The better alternative is to pass an interface into the class, and something else can do the constructor/getInstance()/factory call. This is where dependency injection frameworks like Spring come in, though they are not necessary (just really nice to have).
So when is it appropriate to use a Singleton? In that rare case where instantiating more than one of something would literally ruin the application. I'm not talking about instantiating two Earths in a solar system app - that's just a bug. I mean where there is some underlying hardware or software resource that will blow up your app if you call/allocate/instantiate it more than once. Even in this case, classes that use the Singleton should not know it is a Singleton. There should be one and only one call to getInstance() that returns an interface that is then passed to constructors/setters of classes that need it. I guess another way of saying it is that you should use a Singleton for its "singleness" and not for its "globally accessibleness".
By the way, on that project I mentioned where System was a Singleton... Well System.getInstance() was laced throughout the code base, along with several other inappropriate Singletons. A year later some new requirements came down: "We are deploying our system to multiple sites and want the system monitoring service to be able to monitor each instance." Each instance... hmmm... getInstance() ain't gonna cut it :-)
Effective Java says:
Singletons typically represent some system component that is intrinsically
unique, such as a video display or file system.
So if your component warrants single instance accross the entire application and it has some state, it makes sense to make it a singleton
In your case, the settings of the application is a good candidate for singleton.
On the other hand, a class can only have static methods if you want to group certain functions together, such as utility classes, examples in jdk are java.util.Arrays java.util.Collections. These have several related methods that act on arrays or collections
Singleton will give you an object reference, that you can use all over your app...
you will use singleton if you want objects and/or polymorphism...
If you don't ever need to instantiate them, I don't see the point of singletons. Well, I should amend that - if these classes cannot be instantiated, then it doesn't make sense to compare them to singletons - the singleton pattern restricts instantiation to one object, and comparing that to something that cannot be instantiated doesn't make sense.
I find my main use of singletons generally involves a class that has static methods that, after maybe preparing an environment, instantiate an instance of themselves. By utilising private constructors and overriding Object.clone() to throw CloneNotSupportedException, no other classes can create a new instance of it, or if they're ever passed an instance of it, they cannot clone it.
I guess I'd say that if your application settings are part of a class that is never instantiated, it's not relevant to say "It should/shouldn't be a singleton."
I think you no need to create signleton class.
just make this class constructor private.
Like Math class in java.
public final class Math {
/**
* Don't let anyone instantiate this class.
*/
private Math() {}
//static fields and methods
}
Singletons often show up in situations like you're describing- you have some sort of global data that needs to live in some place, and you'll only ever need one, preferably you want to make sure that you can only have one.
The simplest thing you can do is a static variable:
public class Globals{
public static final int ACONSTANT=1;
This is fine, and ensures that you'll have only one, and you have no instantiation issues. The main downside, of course, is that it's often inconvenient to have your data baked in. It also runs into loading issue if, for example, your string is actually built, by, say, building something from an outside resource (there's also a gotcha with primitives - if your static final is an int, say, classes that depend on it compile it inline, which means that recompiling your constants may not replace the constants in the app - e.g., given public class B{ int i = Globals.ACONSTANT; } changing Globals.ACONSTANT and recompiling only Globals will leave B.i still =1.)
Building your own singleton is the next simplest thing to do, and is often fine (though look up discussions on problems inherent in singleton loading, e.g. double-checked locking).
These sorts of issues are a big reason why many apps are built using Spring, Guice, or some other framework that manages resource loading.
So basically:
Statics
Good: easy to code, code is clear and simple
bad: Not configurable- you've got to recompile to change your values, may not be workable if your global data requires complex initialization
Singletons fix some of this, Dependency Injection frameworks fix and simplify some of the issues involved in singleton loading.
Since your class is holding global settings, a pro for a singleton could be that you have more control about creation of the singleton. You could read a configuration file during object creation.
In other cases if methods are static there would be no benefit like in javas Math class which has only static members.
A more obvious need for singletons is when you implement factories as singletons, because you can interchange different implementations of this factory.
Sometimes what people think belong as Singleton objects really can be private members of a class. Other times they should be unique global variables. Depends on what the design needs them to be.
If there should be one, and exactly one instance of an object: use a Singleton. By that, I mean if the program should HALT if there's more than one object. A good example is if you're designing a video game that only supports rendering to a single output device, ever. Trying to opening the same device again (shame on you for hardcoding!) would be forbidden. IMHO a case like that often means you shouldn't be using classes in the first place. Even C allows you to trivially encapsulating such a problem without the complexity of making a Singleton class, and still maintain the elements of OO that apply to a singleton. When you're stuck in a language like Java/C# , the singleton pattern is what you've got to work with, unless purely static members will do the trick on their own. You can still simulate the other way through those.
If it's merely a case of interfacing objects, you probably should think more object oriented. Here's another example: let's say our game engines rendering code needs to interface resource and input managers, so it can do it's job. You could make those singletons and do sth like ResourceManager.getInstance().getResource(name). Or you could create an application class (e.g. GameEngine) that has ResourceManager and InputManager as private members. Then have the GameEngine pass these as necessary to methods of the rendering code. Such as r.render(resourcemanager);.
For singletons—can easily be accessed from anywhere, it's like a global variable, but there can only be one copy of it.
Against singletons—many uses of singletons can be solved by encapsulating it within in a parent object and passing a member object to another member objects methods.
Sometimes just using a stupid global variable is the right thing. Like using GOTO or a compounded (and/or) conditional statement instead of writing the same error handling code N times with copy and paste.
Code smarter, not harder.
You should use singletons for modularization.
Imagine the following entities in singleton:
Printer prt;
HTTPInfo httpInfo;
PageConfig pgCfg;
ConnectionPool cxPool;
Case 1.
Imagine if you did not do that, but a single class to hold all the static fields/methods.
Then you would have one big pool of static to deal with.
Case 2.
In your current case, you did segregate them into their appropriate classes but as static references. Then there would be too much noise, because every static property is now available to you. If you do not need the information, especially when there is a lot of static information, then you should restrict a current scope of the code from seeing unneeded information.
Prevention of data clutter helps in maintenance and ensure dependencies are restricted. Somehow having a sense of what is or is not available to me at my current scope of coding helps me code more effectively.
Case 3 Resource identity.
Singletons allow easy up-scaling of resources. Let us say you now have a single database to deal with and therefore, you place all its settings as static in the MyConnection class. What if a time came when you are required to connect to more than one database? If you had coded the connection info as a singleton, the code enhancement would comparative much simpler.
Case 4 Inheritance.
Singleton classes allow themselves to be extended. If you had a class of resources, they can share common code. Let's say you have a class BasicPrinter which is instantiable as singleton. Then you have a LaserPrinter which extends BasicPrinter.
If you had used static means, then your code would break because you would not be able to access BasicPrinter.isAlive as LaserPrinter.isAlive. Then your single piece of code would not be able to manage different types of printers, unless you place redundant code.
If you are coding in Java, you could still instantiate a totally static content class and use the instance reference to access its static properties. If someone should do that, why not just make that a singleton?
Of course, extending singleton classes have their issues beyond this discussion but there are simple ways to mitigate those issues.
Case 5 Avoid information grandstanding.
There are so few pieces of info that needs to be made globally available like the largest and smallest integers. Why should Printer.isAlive be allowed to make a grandstand? Only a very restricted set of information should be allowed to make a grandstand.
There is a saying: Think globally, act locally. Equivalently, a programmer should use singletons to think globally but act locally.
Effective Java says:
Singletons typically represent some system component that is intrinsically
unique, such as a video display or file system.
So if your component warrants single instance across the entire application and it has some state, it makes sense to make it a singleton.
(The above nakedly borrowed from naikus)
In many cases the above situation can be handled by a 'utility class' in which all the methods are static. But sometimes a Singleton is still preferred.
The main reason for advocating a Singleton over a Static Utility Class is when there is a non-negligible cost involved in setting it up. For example if your class represents the file system, it will take some initialization, which can be put in the constructor of a Singleton but for a Static Utility Class will have to be called in the Static Initializer. If some executions of your app might never access the file system then with a Static Utility Class you have still paid the cost of initializing it , even though you don't need it. With a Singleton if you never need to instantiate it you never call the initialization code.
Having said all that, Singleton is almost certainly the most-overused design pattern.