Passing this to a constructor - java

In most of my java applications, I have a Controller (Logic) class and a GUI class. I usually need the Logic class to call methods on the GUI class, and vice versa. Now, when the Logic constructs the GUI, I pass a reference to "this" in the constructor so the GUI can call methods on the Logic. Here is some example code.
public class Logic {
private int num = 2;
private final GUI gui;
public Logic(){
gui = new GUI(this);
}
public int getNum(){
return num;
}
}
public class GUI {
private final Logic logic;
public GUI(Logic logic){
this.logic = logic;
}
public void calledLater(){
int num = logic.getNum();
}
}
My question is: Is this the best OO way to create an aggregation relationship, or am I messing up my design?

In the design you've posted, there's a tight coupling between your UI and your model. This is somewhat frowned upon if building large/formal/serious/long-lived systems. There's a well known pattern of architecting UI/Model architecture known as Model-View-Controller that addresses this.
Whether or not you need to worry about going to town on making an MVC styled architecture really depends on the context of your app and your desires for it in the future. But you should read up on MVC and know that it is there.
Btw, I see in your code a "code smell": two objects, A and B, each holding a reference to each other. There is usually a more desirable way of doing things than having cyclic references. You can avoid this by having, for example, object A holding a reference to B (and perhaps even 'owning' it), and B pushing data of interest to A via notifications, or the observer pattern, etc. This avoids B having to have any specific info about A, or even having to know that it exists. Voila, less coupling in your design, so you end up with more scope for code re-use, and a less brittle system that is easier to change.
An important and central design pattern in Cocoa (and Cocoa Touch) is the delegate pattern. This pattern involves using protocols (similar to interfaces in other langs like Java) to decouple the producer and consumer of information, events, etc.
I suggest reading this excellent reference from Apple about fundamental design patterns in Cocoa Touch.

Passing this to a UI class is not in itself a problem, as long as the methods of the class are not called through this, as in your example. You call getNum right in the constructor of the GUI, which should be avoided: your Logic class may not be ready to return the correct result.
One thing to note is that you couple your GUI to the Logic class, which may be too much coupling. You should consider extracting an interface from Logic, and let GUI interact only with what's intended for it:
interface DataSourceForTheGui {
int getNum();
}
class Logic implements DataSourceForTheGui {
int getNum() {
return n;
}
}
class GUI {
private readonly DataSourceForTheGui data;
public GUI(DataSourceForTheGui data) {
this.data = data;
}
public void display() {
int k = data.getNum();
}
}

Well... I'm ok with GUI holding an instance of Logic. After all, if the GUI is supposed to use the Logic object, it's going to have to access it somehow.
However, I would rather see Logic NOT construct GUI. If you really want model and view to be separate, I think that you would construct Logic somewhere, and construct GUI with the Logic object. Then, if Logic ever needs to update the GUI for whatever reason, you should have it generate an event.
In that case, Logic needs to have a list of event listeners, so that whenever it generates an event, all the event listeners are notified. The GUI then registers with Logic as a listener, and is thus able to receive all the events.
Some good classes for this are java.util.EventListener and java.util.EventObject.
But really, that's only necessary if Logic needs to communicate up to GUI asynchronously. Otherwise, just stick with Logic not constructing the GUI.

The best thing (or at least the easiest to understand) is to have the initial thing created as an outside class (called directly by the main class or the main class itself). So your code would look somewhat like this.
public class MainClass{
public static void main(String[] args){
l = new Logic();
g = new GUI(l);
l.setGUI(g);
}
public static Logic l;
public static GUI g;
}

I'd say it will work, but I'd never ever reference a GUI object from your business logic.
I'll answer with comments. What are you trying to do?
your user should instruct your GUI, and the GUI should properly instruct the Logic to do what it needs to do, and return results back to the GUI.
Few other comments:
I'd make your Logic num member a constant since it's not changing
If you're not changing your Logic object ever for your GUI, there's no reason to pass it into your constructor.
If you want to change your Logic object, I'd make a property called Logic in your GUI class so you can get access to it and change it when necessary.
If you really want to get fancy, you'd keep your Data Access Layer (business logic) in a separate library from your GUI so all of your interfaces/applications can utilize it. Then you'd import your Logic library into any interfaces that need it.

Related

Is it ok to keep common code in a separate class and make the method static in java?

I would like to know if it safe and a good practice to keep common code in a separate class and make method static.
I have a class Car, that is constructed based on inputs from other classes. I need to apply some post construct processing after the Car object is created. Example below.
Class Travel uses Car and calls postConstructProcessing method.
CarProcessor is simillary used in other classes whenever car object is creates.
My question is should I make method process Static in CarProcessor.
Class car{
Type type;
Int model
Car(Type t, int m){
...
...
}
;
....
...}
Below class of code uses Car and calls postConstructProcessing method
public class Travel {
public void go(){
....
....
Car c = new Car(t,m);
new CarProcessor().process(c);
}
}
class CarProcessor{
public Car process(Car c){
If(c.type.value.equals("ABC"){
c.type.version=1.1;
}
if(c.model=5.7){
c.price=50k
}
}
}
My question is , is it safe and a good practice to make method process in CarProcessor static.
In general it's not great.
The most obvious problem is, if you are testing the go method, how do you replace/mock out CarProcessor::process?
The real problem is organizational though. When you are coding next time and looking for the functionality you'd expect to see in "Car" or "go", you type "car." or "go." into your IDE and hit ctrl-space, you'd expect to see all the interesting methods shown to you. How do you know to create a CarProcessor to proceed?
Some things are difficult to implement in OO though--in particular utilities. Look at the entire Math package in the java library. It's full of static methods that you just call. An oo fanatic would say these all belong in the Number class (maybe something like "Number.math.sqrt()?", but java didn't take that route--in fact they don't even have a good common number class (We have one, it's not good)--
But even when we have real classes like String, we lean towards "StringUtil" and such. This has led to a HUGE number of conflicting "Util" implementations of String. In this case part of the problem is that String is immutable and we can't really back-fill it with methods (probably a good thing). but in general, OO just isn't great for general-purpose utility methods.
Functions (which is what you are proposing) are not awesome, but are heavily used. If you have the ability to modify your business classes then that's almost always a better fit for this type of code.
Just to clarify: A Function is different from a Method--methods work on members (class variables), functions are stand-alone (Might as well be static).
Functions are a very old approach at organization. OO is a somewhat newer approach invented for when the sheer number of functions become too difficult to manage (conceptually).

Using multiple classes without creating objects of each

I am new to java and stackoverflow
I have
class Assemble()
class Start()
class Ignite()
class Move()
...... There are still 12 classes
I want use methods inside these classes
but
i should not create objects of them
i cannot use extends for all these also
i there any way possible?
Please bare anything silly, i am not able to figure out.
And this is my first question hear.
the finaly class is
class run
{
public void run_simple()
{
// hear i should be able to access all methods of above class
}
}
If you use an object oriented language (as java) the way it is meant, your whole program is about creating and using objects (as mentioned in many comments). There are some valid technical reasons not to create objects and to use static methods ("it's tedious" is not one of them). There are environments that forbid to use inheritance.
Please state these reasons, otherwise we have to assume that you don't understand some basic concepts of object oriented languages and that your "restrictions" must be ignored.
Most "restrictions" of object oriented programming are intended to help you structure your solution/program. If you see them as real restrictions, the structure of your program might very well be bad.
I'd like to give an example on how something like this might look "the OO way". This might not fully match your project, but should show you that creating objects must not be an issue programmer effort wise.
First we need an interface that defines what one of your actions (thats what I call your classes) looks like
interface Action {
public void run();
}
The following classes define the concrete actions. Their constructors might take parameters configuring details on how to execute them. In the run()-method of each class, you program on what an action does when executed.
class Assemble implements Action {
public void run() {...}
}
class Start implements Action {...}
class Ignite implements Action {...}
class Move implements Action {...}
The controller does the "run everything". That's basically your "overhead" for creating objects!
class Controller {
/** Returns a list of the configured action objects. */
public static List<Action> buildActions() {
List<Action> actions = new LinkedList<Action>();
actions.add(new Assemble(parameter)); // or whathever parameters you need
actions.add(new Start(parameter1, parameter2));
actions.add(new Ignite());
actions.add(new Move());
}
/** Build the list of actions and run one after the other. */
public static void main(String[] args) {
List<Action> actions = buildActions();
for (Action action: actions) {
action.run();
// here you could add logging, profiling etc. per Action.
}
}
}

Checking subclasses for relevance before instantiating them?

Java newbie here. Here's what I'd like to do:
Enumerate over a list of classes, each of which extends the same superclass.
Ask the class whether it's interested in an event.
If the class is interested, instantiate the class and call the object's event handler.
The idea is that steps 2 and 3 will prevent instantiation of classes that aren't interested. However, because I'm calling a method before instantiation, the check would have to be done statically. Java (rightly) doesn't allow the overriding of static methods, so it seems that I have to instantiate the class in step 2, making the sequence look like this:
Enumerate over a list of classes, each of which extends the same superclass.
Instantiate each class and ask the object whether it's interested in the event.
If the object is interested, call its event handler. If it's not interested, throw it away.
Am I missing a general way to accomplish the first set of steps?
Note that this question is mostly theoretical. Object creation overhead may be low enough to render it moot. I'm interested in the possibilities, though.
Since we're speaking about theory, I'm pointing at some facts and speaking in terms of design.
Static methods are not associated to a particular instance of a class, so overriding is not an option since it depends on having an instance. I'm talking about Java, because I recall some other languages that allow class method overriding.
The workaround to this is to define a static method in each subclass that returns the events it is interested in, so you can know this data before instantiation.
Another option is to put a specific class in charge of those objects instantiation and making that class keep a table associating an event with a list of interested classes (table that you can initialize and configure). This approach seems more maintainable because you won't have to change code if you want to unsuscribe a class from an event.
In the end, you just instantiate all the classes thata re associated to a certain event:
public class EventClassCreator {
private Map<String, List<String>> subscriptions;
public EventClassCreator() {
subscriptions = new HashMap<String,Set<String>>();
}
public void addSubscription(String event, String class) {
if(subscriptions.containsKey(event))
subscriptions.get(event).add(class);
else {
Set<String> subscriptionsForEvent = new HashSet<String>();
subscriptionsForEvent.add(class);
subscriptions.put(event, subscriptionsForEvent);
}
}
//You just need to make an event that loops over the list of classes,
//checks a subscription and instantiates a class if it is in the
//proper list.
}

Private Methods Over Public Methods

I was examining the StringTokenizer.java class and there were a few questions that came to mind.
I noticed that the public methods which are to be used by other classes invoked some private method which did all of the work. Now, I know that one of the principles of OOD is to make as much as you can private and hide all of the implementation details. I'm not sure I completely understand the logic behind this though.
I understand that it's important to make fields private to prevent invalid values being stored in them (just one of many reasons). However, when it comes to private methods, I'm not sure why they're as important.
For example, in the case of the StringTokenizer class, couldn't we just have put all of the implementation code inside the public methods? How would it have made a difference to the classes which use these methods since the API for these methods (i.e. the rules to call these public methods) would remain the same? The only reason I could think of why private methods are useful is because it helps you from writing duplicate code. For example, if all of the public methods did the same thing, then you can declare a private method which does this task and which can be used by the public methods.
Other question, what is the benefit of writing the implementation in a private method as opposed to a public method?
Here is a small example:
public class Sum{
private int sum(int a, int b){
return a+b;
}
public int getSum(int a, int b){
return sum(a,b);
}
}
Vs...
public class Sum{
public int getSum(int a, int b){
return a+b;
}
}
How is the first sample more beneficial?
In order to add something, a private method can ALWAYS be changed safely, because you know for sure that is called only from the own class, no external classes are able to call a private method (they can't even see it).
So having a private method is always good as you know there is no problem about changing it, even you can safely add more parameters to the method.
Now think of a public method, anyone could call that method, so if you add/remove a parameter, you will need to change also ALL the calls to that method.
The only reason I could think of why private methods are useful is because it helps you from writing duplicate code.
In addition to consolidating duplicate code (often expressed as "Don't Repeat Yourself" or "DRY"), use of private methods can also help you to structure and document your code. If you find yourself writing method which does several things, you may wish to consider splitting it into several private methods. Doing so may make it clearer what the inputs and outputs for each piece of logic are (at a finer granularity). Additionally, descriptive method names can help supplement code documentation.
When writing clean code in Java or any other object-oriented language, in general the cleanest most readable code consists of short concise methods. It often comes up that the logic within a method could be better expressed in separate method calls to make the code cleaner and more maintainable.
With this in mind, we can envision situations where you have many methods performing tasks towards a single goal. Think of a class which has only one single complex purpose. The entry point for that single goal may only require one starting point (one public method) but many other methods which are part of the complex operation (many private helping methods).
With private methods we are able to hide the logic which is not and should not be accessible from anywhere outside of the class itself.
Public methods are generally code that other classes which implement that class will want to use. Private methods are generally not as useful outside the class, or don't(alone) serve the purpose of what the class is meant to accomplish.
Say you're in your IDE of choice, and you implement a some class A. Class A is only designed to do one thing, say document generation. Naturally you will have some mathematical and byte operation methods in Class A that are required to do document generation, but people trying to use Class A are not going to need these other methods, because they just want a document. So we make these methods private to keep things simple for any future users of our class.
The purpose of declaring a method private is to
hide implementation details
exclude the method from being listed as public API
make sure the logic behind the code is not used/misused externally
most of the time your method's execution depends on other methods being run before it; then you can also be sure that you control the correct sequence of using your method
Use private for your methods unless you intend for your method to be safely used outside of the context of your class.
Making functions private gives you advantage in following cases :
Making function private gives JVM compiler the option of inlining the function and hence boosting up the application performance
If the class is inheritable and you extend it from a child class, then in case if you want to hide the functions from child class then you can do this (you can extend StringTokenizer).
If a piece of code has to be used in multiple functions the you move that code in private utility method
An advantage and also a good reason to use private methods inside public classes is for security and bug prevention. Methods that are declared as private are only accessible by the class they are part of. This means that your private method can't be accidentally called from else where within the program reducing bugs and other complications. If you declare your method as public it can be accessed by the whole problem and can cause complications.
You may have a number of methods that work on a certain piece of data that you don't want any other part of the program to be able to interfere with. Using data encapsulation via private methods and/or variables helps to prevent this and also makes your code easier to follow and document.

Java OO Design help - how to abstract out a save method?

I have a Preference class (module) that's used across several different apps. Basically it's a cache of the preferences so that the systems don't have to call the backend all the time. It's similar to a cache but with some additional niceties such as isPreferenceSelected, has some helper methods, etc.
The issue is that I'd like to include a savePreference within the class so that whoever uses it can just override that method, be it to a database, to a flat file, etc. The key is that this module just doesn't want to care. The issue is that it's not an abstract class so I can't override the static methods and even if it was, I don't want to create a million instances because I don't want to load the preferences each time. And I can't create a abstract singleton either.
Therefore I'm not sure what to do. Here is a code snippet of what I'd like to do with comments:
// Please ignore the missing Generics, etc.
public class Preference
{
private static HashMap preferences = new HashMap();
public static ...
// Some preferences are objects, such as images, etc.
public static setPreference(String name, Object value)
{
.. some helper code
preferences.put(name, value); // ignoring issues with if it already exists ;)
savePreference(name, value); // saves to database, flatfile, etc.
}
}
That was the core class/code that the different systems leverage. Now what I'd like to do is say in a webapp, a desktop app, etc., be able to use this class in my code such as:
public someFunction(...)
{
.. do some cool code
Preference.savePreference("logoImage", image);
}
And have the savePreference() method not just save the in-memory preferences, but also save it to the external source. Otherwise everywhere I have savePreference() I have to follow it by a db call savePreferenceToDB(), a FlatFile call such as savePreferenceToFlatFile(), and so on. This is very error prone, someone somewhere will forget to save it. Plus it really makes no sense to sprinkle the save to permanent storage code everywhere with this type of code when it should really only be done once. Also remember that the main module has no idea if the permanent storage is a database, an xml file, a flat file, etc.
Hint: If I did Preference.getInstance().savePreference() that wouldn't work because you can't abstract a singleton. And I can't create a static method savePreference() because it's not possible to override a static method.
The only options I can see is to create some kind of complex Factory pattern, but that seems like a lot of overkill to me. Therefore any suggestions would be greatly appreciated.
This sounds like something that your dependency injection (DI) container should be handling, not a complex factory pattern.
That is, I think you should ditch the usages of static, have whatever creates the other applications inject an instance of Preference into your applications. You can do this without a DI framework if you just take the Preference as a parameter in your constructor for whatever other classes depend on it.
Edit: Let me give you an example of dependency injection without a framework. Take the following set of classes:
public class Preference
{
private String userName;
public Preference(String userName)
{
this.userName = userName;
}
public void savePreference()
{
// Default implementation saves it to the screen. ;-)
System.out.println(userName);
}
}
public class Foo
{
private Preference p;
public Foo(Preference p)
{
this.p = p;
}
}
public class Bar
{
private Preference p;
public Bar(Preference p)
{
this.p = p;
}
}
public class Main
{
public static void main(String[] args)
{
Preference p = new Preference("Mike");
Foo f = new Foo(p);
Bar b = new Bar(p);
}
}
This is a simplistic example, but it satisfies your requirements:
The Preference instance is only created once
The Preference class can be extended by whoever implements the Main class to instantiate whatever kind of Preference subclass they want to, if they wanted to persist it in a relational database (or whatever)
By avoiding having static calls in the first place you also make it possible for your someFunction() example to be unit tested without pulling in a potentially big, complicated preferences framework. Rather, someone implements a mock Preference subclass and passes it into the class that runs someFunction(). Your code will be much more testable that way.
#Mike says:
... I think you should ditch the usages of static
#Stephane responds:
... what is the major issue with static methods?
It is not just static methods. It is also the singleton instance.
Basically, they are inflexible:
They make it difficult to do things in alternative ways, as illustrated by your problem. If you didn't use a static method and a private singleton instance, you could create a Preferences interface and/or abstract base class, together with implementations that load and save the in-memory preferences in different ways.
Static instances tend to make testing harder. For instance, if you had a preferences UI that made use of your Preferences class, you couldn't unit test the UI classes using a "mock" version of Preferences. (Or at least, it would be a lot harder to do.)
Statics tend to make it difficult to reuse your code because of the hard dependencies on specific named classes and specific implementations.
Statics are non-OO. This is not intrinsically a bad thing, but it does mean that you can't make use of the nice properties of OO ... like overriding and polymorphism ... when you use statics.
If you have a significant number of these static methods / static objects in your application, a DI framework is a good solution. But as #Mike says, using Factory methods and passing objects in constructors will work just as well in many cases.
You commented:
One of the reasons I have it as a static class is because the preferences are loaded at startup. After that they stay in memory in the one static object. With DI, each time I create the object, I'd have to reload the information into memory from the data source. This defeats the whole purposes of having a Preferences Object (that pretty much acts like a cache with benefits).
This does not require you to use a static instance.
With DI (or explicitly wiring instances via constructors), you don't create the Preferences object more than once. You create it once, and then inject it as many times as required.
There is a halfway between your current approach with a static method that wraps a static instance of a hard-wired class and full DI. That is a what can best be described as a static holder; e.g.
public interface Preferences {
// Preferences API
}
public abstract class PreferencesBase implements Preferences {
// Implement as much if the API as makes sense
}
public class FileBackedPreferences extends PreferencesBase {
// Implement (protected) persistence methods.
}
public class DatabaseBackedPreferences extends PreferencesBase {
// Implement (protected) persistence methods.
}
public class ApplicationPreferences {
private static Preferences instance;
private ApplicationPreferences() { }
public Preferences getInstance() { return instance; }
// Call this once during application startup with the
// Preferences instance to be used by the application.
public void initPreferences(Preferences instance) {
if (this.instance != null) {
throw new IllegalStateException(...);
}
this.instance = instance;
}
}
I think it might take some rework of your design (unfortunately, I don't have a decent whiteboard in my apartment yet, so I can't easily sketch things out to conform), but I immediately thought Strategy pattern as soon as you said this:
The issue is that I'd like to include a savePreference within the class so that whoever uses it can just override that method, be it to a database, to a flat file, etc. The key is that this module just doesn't want to care.
You might have an abstract Preferences class that has every method but saving (and loading) implemented. In the sense of the pattern, this would be the Strategy interface. Your different types of saving and loading would be handled by the concrete implementations.
Create an interface for your preference manipulation class:
public interface PreferenceHandler {
void savePreference();
void readPreference();
}
Pass an instance of type PreferenceHandler to your class with all the static methods.
Invoke the methods on that class within your class.
Though, not lovin' all those static methods. It's probably why you're having so many issues here. Create a factory that gives you a copy of the class if you don't want to be creating lots of copies of it. But static methods really impede code re-use and extension. Or perhaps use a framework like Spring to manage classes of this sort.

Categories