Sharing an object through several classes [closed] - java

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 8 years ago.
Improve this question
I need to share 1 instance between several classes.
The Connect class has methods to create a URL and to download data, and the ui is the interface (swing form) through which I get the data to build the url (dates theat comprise the url).
What's the best way to do it?
Thought of:
1) Making it global by:
public class Global {
public static Connect c;
}
2) Making the instance in main(), and passing it through objects.
public static void main(String[] args) throws IOException {
Connect c = new Connect(); // get url to download from
ui form = new ui(c); // the form to get data from
.
.
.
What seems more reasonable, if any?
Thank you.

The preferred way is usually to pass the instance into the constructor of whatever class needs it. That way, it's not a guess whether or not someone has set up Global.c and when it should be available to use. It also clearly documents that each class requires a Connect object. Another benefit is that if your code ever changes and you want your UI class to no longer rely on the same Global Connect instance, you no longer have to change all your code that pulls a magic instance from this global context, and you can just pass in a different object.
Do a search for something along the lines of "why are global variables bad" or "why are singleton accessors bad" and you'll get a lot more detail than my explanation. There are uses for them, but if you can avoid them up front you may save some headache down the line. As with everything, there are trade-offs for each.

you must be very careful with the first option. As I see it there are a lot of drawbacks here:
Its not an object oriented style of programming. It rather smells like old fashioned C code
What happens if you should support a lot of such an instances.
Now what happens if you need to change them (in fancy terms if these instance are not immutable)?
Now what happens if your application goes multi-threaded?
While some of these points are validly applicable to the second solution you've described, in terms of maintainability and readability of your code the first solution is just a mess...
So to me the second one is better.
Hope this helps

Related

BestPractices: Is it bad OOP to subclass standard classes into a new one that does same thing, but "presuming" future changes? [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 8 years ago.
Improve this question
I have had similar cases in the past, and this is just an example to illustrate:
I'm going to implement a new feature in my android app (but this applies to any kind of OO project), and at this point I need to implement some "action" in the "setVisibility" method from EVERY edittext in EVERY activity I have.
To do it, I have to subclass "EditView", and override "setVisibity" method:
#Override
public void setVisibility(int visibility)
{
super.setVisibility(visibility);
// --> do my stuff here! <--
}
So far, so good... the problem is to change all activities I have (more than 200, and thounsands code lines), and then I think: "why on earth didn't I start the project subclassing the standard EditText, 'cos I knew some point I'll need to implement something like this".
That's the point: Is it bad OOP to subclass a "standard class" into a new one that does exaclty same thing, but just "presuming" cases like that? I mean, subclass everything, like buttons, activities, etc.
AFAIK, desing pattern and OOP discourage the "presuming factor", but I'd to hear what you guys "do in real life" (or think about that), based on your programming experience.
Also, maybe this type of question ("what you think", "what your oppinion") isn't a good practice here in SO, but I can't find any better place to put it on.
There's no reason to stub out code unless you're actually making changes. It's wasted effort, and just bloats your codebase.
If you find yourself in a situation where you're repeatedly making the same modification, consider refactoring to share common code. Or in certain cases, there's merit to generating those pieces of code (for example, Avro does this).
No, it's not bad, and I recommend you always do it on any class you'll reasonably extend over time. For example in our iOS projects we always start with a UIViewController subclass called ViewControllerBase that does nothing but extend Apple's base class (the same can be said for Activity on Android).
When we need to add something in later that should apply to every view controller (analytics perhaps), it's easy to do.
Fortunately, even if you have a lot of classes in your code it's easy to inject your custom base class with a simple search and replace across your codebase.
Do be careful though as once you have a class that's in everything, small changes can of course have broad and possibly unexpected effects. Be sure to test thoroughly!
EDIT:
Regarding subclassing everything, I'd say no. You quickly reach a point of diminishing returns on your time and utility. A common view controller base is pretty standard, as for buttons and so on probably not so much. It depends entirely on what you want to do that you think might need custom functionality. If you want to log every user action, then maybe you do want to subclass every control, but in that case it might be better to just log touch events. At the end of the day though, are you really going to parse all the data that gets generated? Probably not. So make sure you have a solid use case before you go crazy subclassing.
In my opinion there are some cases in which it makes sense to derive classes of a Framework.
At work we used derived classes for the UI-Elements to have control over their behavior.

How can I get a friend to stop thinking global and start thinking relative? [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 8 years ago.
Improve this question
I have a friend who is struggling to learn OO programming (in a Computer Science class), mainly, I believe, due to the fact that he does not understand the relativity/difference between "type" and the actual "instance." It appears to be an issue in understanding how data is stored.
He knows variables, and control structures, and quite a few algorithms, but I think understanding scope and the way objects are defined in Java is confusing to him. The most confusing part is the "template" part, where the methods and variables are defined, but are "owned" by each object.
As this post kind of shows, I'm horrible at explaining this concept, even when I know I'm explaining it to people.
So what I want to know, is how can clearly explain to him instances and classes (as a type, versus the actual data). He knows the basic concept, I think, but does not fully understand the difference between type and data, and how the data is passed around.
More info:
Here's the sort of confusion he is experiencing. We're working with overriding a Critter object in GridWorld (The horribly designed AP test object thing). In any event, we are suppose to redefine some methods.
He'll end up trying to use methods as properties (quite possibly a typo, but also because stuff like GetLocation() may be confusing), or he'll try to use methods on the wrong variable, or not use the right type of variable.
The difference between "Integer nameHere" and "nameHere Integer" is confusing, I think, to him. He may try to do Integer.equals() when he should do nameHere.equals(). I show him the API, but I think it's just plaining confusing.
How do you explain the difference between type and variable, but not only that, but show how a variable can have other variables in it, how when you write
public getSomething()
{
return something;
}
You are getting specific data from the class you instantiated, oh, and by the way, it's different for every single object?
How can I get him to stop thinking "global" and start thinking "relative"? How do you explain "relative"?
I like to use TVs to explain OOP concepts. There are "TVs" as a class, but then there's your TV, in your house. It can do some things that ALL TVs can do, like show a picture, turn on and off, etc.
But it also has a locally defined scope because it is one instance of the class of TVs in the world. If you enter channel 32 on a TV in NYC you get one thing. If you do it in Bangalore, you get something else. Entering a channel is like calling the TV's setChannel(int channel) method.
It's not surprising to users of such real world objects that they work this way. My advice for this particular problem is to stop using abstract and technical language to describe the basic concepts. There are plenty of things in computer science that can't be explained using material objects in the real world, but this isn't one of them.
One can think of classes as a mould, like a mould define how a final product would look like, classes define what all data can be stored, how it can be retrieved, accessed etc.
One can put raw material in mould and get the product and start using it.
Similarly one can create an instance of Class and start using it.
Each object can hold different data (like in mould you can put green liquid, red liquid etc) but there is only a single way to access data defined my class semantics (like final shape of mould product would be identical).
Hope it helps

Is every cyclic references between Java packages bad? [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 1 year ago.
Improve this question
I've been using Sonar code quality management platform for some time, and for the most cases I find it very helpful in revealing hidden design flaws of my code base.
However, there's one rule that gives me more annoyance than help and that is its check for 'cyclic package reference' violations.
I guess I fully understand where such a dependency between packages is a bad thing. For example, in a typical 3-tier presentation/service/persistence layered design, it's almost always a bad idea to let the database handling code have a reference back to UI related classes. I have no problem with calling it a 'violation'.
But let's consider other cases, i.e. like designing an IDE-like application. Say, we have a main package which contains an Application interface, which defines List<View> Application.getViews() method to reference application's views.
However, when the View interface has an Application getApplication() method to refer back to its parent application, which I believe is a quite common design, it will introduce a cyclic reference, provided each of the interfaces are separated in com.myapp.ui, and com.myapp.ui.view respectively.
Of course, you can just put the View interface into the com.myapp.ui to break the cycle. But when you have various other view related APIs in com.myapp.ui.view, many of them another abstract APIs like AbstractView, ContentView, AbstractContentView, etc. I wonder if it's more advisable to keep them in separate packages for a management purpose.
And consider the said application has many other similar cases like com.myapp.ui.action, com.myapp.ui.perspective, etc. which would really make com.myapp.ui package crowded if we are to put them all in there.
So, what approach do you suggest to handle such a situation? Are really every cyclic package references a bad thing? Or if I have to live with them, how do you configure Sonar to check only real, problematic cycles?
Every absolute -- except this one ;) -- is going to be wrong some of the time. So, is every cyclic reference bad? No. You have to use your judgement.
But if you do introduce a cyclic dependency, it's worth asking if you really need it, and why. The tl;dr is that more often than not, you may find that breaking the cycle can improve your modularity, and in particular your ability to test components separately.
To use your example, does a view really need a getApplication(), which presumably returns a relatively "heavy" object (ie, one that itself needs a database, network, etc etc)? Maybe... but maybe not. If what you really need from that getApplication is something with a few callbacks (such as when a user initiates some action), then it could be useful to create an interface in some common package for that callback. So, rather than:
com.foo.app.Application
com.foo.view.View
Application getApplication()
You'd have:
com.foo.common.Callback // maybe just a Callable, Runnable, etc?
com.foo.app.Application
provides a Callback for some action foo
com.foo.view.View
Callback getFooCallback()
The question you should be asking is: what does that give me? It could be that you have to stub out so much that it doesn't give you much -- though that may suggest you can break apart your classes some. But it could be that it actually makes it easier to test your view, because now your unit test can (1) test the view without spinning up a whole application, and (b) provide a "dummy" callback that does something like saving a string that describes the action, and then your unit test asserts that it saved the right string.
And indeed there is an open JIRA ticket to prevent considering a cycle between father/child packages as a quality flaw : http://jira.codehaus.org/browse/SONAR-3452

Is Using a Static Configuration Class Good Practice? [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 8 years ago.
Improve this question
In my project I am developing at the moment, I have many configuration settings. Things such as
Alarm times
Amount of items to retrieve from the server
LocationManager integers such as minium location
These are all static final and are all in a class that corresponds to the value.
My question is, are there any problems with moving all of these values to a single static class?
My thinking is that when it comes to testing and tweeking the app, it will be easier to manage.
Building on #Snicolas's answer...
You should indeed persist your CONFIGURATION settings outside of code (file or database). BUT you should not "read" that configuration each time a value is required, that would be inefficient.
Using a class to manage configuration (ie. AppSettings) is a good idea. Making it static is one way to provide singleton-like access. In C# and ASP.NET a web app will guarantee one and only one instance of a static class and therefore multiple un-related requests from different users will share the exact same static values.
But in your case (I see the tag 'android') using Java your best bet may be a Singleton approach. I don't know how garbage collection works in Java but I'd say you should use a singleton to ensure one-and-only-one instance of your settings. The singleton Ensures an instance exists (or creates one if not) and then provides it to the caller.
This may also make it easier to support the ability to change configuration values while the app is running -- you can "watch" for setting changes on a regular basis.
I'm not a Java man but I'd be surprised (well no not really) if there wasn't already a library for handling this very problem.
I am pretty sure you are not talking about constants as you mentionned alarm times.
The problem with using only static fields inside a dedicated class is that your class can be garbage collected if the device is under memory pressure. In that case, they would simply be lost and reset when you would use them again.
So you should really consider persisting them in a file or in a database depending on the amount of data you wanna store. SharedPreferences can be usefull for a small amount of data, otherwise, consider using a database. That's a much more scalable solution and access times are better for larger data sets.
In the Rails world, it's good practice to implement a configuration model class that lazily loads and caches configuration information, which is persistently stored in serialized form in a simple two-column (key and serial data value) table or (less often) a flat file. A configuration editor is then just a View for this model.
This ought to be a good solution in Android as well.
Another idea will be to store these constants in a properties file. And load the constants when you need them. http://viralpatel.net/blogs/loading-java-properties-files/
If you find it convenient, it's a good practice.

An own class for everything [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 8 years ago.
Improve this question
I'm making a customer administration software. There are several JPanels with much content on it, constantly communicating with a database. In the database is customer data, products etc.
For a faster access to the database data, at first I load it all in its own ArrayList, e.g. ArrayList<Customer>. If the user changes this data, it has to be changed in both the class and the database.
As the JPanel View looks very "full" (crammed with other JPanels and JTabbedPanes, switching through with the CardLayout), I thought it would be better to create an own class for every "main" JPanel and link them all with View.
For example an own class for the JPanel Customer, where all the customer data can be seen and edited, the same for products etc.
Does is make sense or is it inconvinient? I only want to do so to outsource the code and to make the classes clearer, especially View.
Is there something like a design pattern dealing with this problem?
So your program consists of a single class that subclasses JPanel and that contains references to all other components used in your UI? And you want to know if you should break out portions of that UI into other classes.
In short YES. You can always decompose any class into aggregated classes by moving portions of that code out into a new class, and have the original class contain a reference to the new class. This is called delegation or Extract Class refactor. You can read about this technique in Martin Fowler's Refactoring book.
Creating other UIs that are parts of the total UI, like CustomerPanel, is a good way to think about it. By doing this you can also decouple parts of your UI. Be careful when you create these smaller classes to move all dependencies to the new class. If you feel like passing a reference back to the main UI to the aggregated class then you probably haven't fully decoupled your classes. That should be a sign either you haven't given enough responsibility to the class you are extracting, or there is some other dependency they should be sharing.
Basically the rule is if you extract a class, it shouldn't have a reference back to the class that contains it. References should be more of a tree than a graph. It's ok for them to share a model class, but its not ok to create cycles between views.
You probably would find this interesting:
GUI guidelines for swing
I am not sure if I understood your intent, but looks like you want to achieve the level of decomposition which will allow you to outsource certain UI components and reuse them, well, basically achieve as lower coupling as possible. Apart from what #chubbard said, I would suggest you to look into MVP pattern and use event-based interaction between components rather than referencing them. This can eliminate unwanted dependencies and bring more reusability.

Categories