Can Result objects be allowed to have behavior? - java

This is in reference to the ResultObjectPattern.
Usually, the ResultObject will be rather simple with just private instance variables referring to various components of the result, and getter methods (possibly setters too?) for those.
Now, would it be a bad idea to add behavior methods to the ResultObject? For example, let's say the ResultObject pushed out one or more of its instance variables to a cache and retrieve them back only when needed, or provided methods that do some computation,-- would that be okay, or would these be things that'd rather be handled by a separate (singleton/utility) class such as a ResultObjectManager?

I think if behavior is strongly related to data and behavior is not beyond the scope of RO responsibilities - is not bad idea.

I'd say that when the choice is between adding an instance method to a regular class and adding a static method to anything or any method to a singleton, I'll add the instance method to the regular class. It's the OO way.

Related

Is there a way to get all of the non-null members of a class without reflection or getters?

I have a class that that can potentially assign values to 50+ plus variables. I don't want to write getters for all of these fields. I would rather have some way that can report which fields have had a value assigned to them and, what that value is.
I had originally made these private and, I know that reflection basically breaks private. Additionally, Securecoding.org states this about reflection:
In particular, reflection must not be used to provide access to classes, methods, and fields unless these items are already accessible without the use of reflection. For example, the use of reflection to access or modify fields is not allowed unless those fields are already accessible and modifiable by other means, such as through getter and setter methods.
My main concern is mucking up my code by declaring dozens of instance variables(and possibly getters). Later in this project, I will have two more large sets of instance variables that need to be declared as well. I know that I can reduce the use of getters with some clever maps and enums but, that still takes parsing dozens ofnull values. Could anyone suggest another way?
I know only 4 ways to access field of class
directly unless field is private
Using method, e.g. getter.
Using constructor.
Using reflection
The ways 1 and 4 are beyond the discussion.
Constructor usage is not convenient here because huge number of fields.
So, methods the possibility.
It is up to you whether you want to use bean convention or for example builder pattern, but if you need this class for persistency or for serialization into XML or JSON etc you need at least getters.
Now, if you just want to validate the instance after its creation you can declare your interface Validatable that declares method validate() and call it when your object should be ready. You have to however implement and maintain this method for each class.
Alternative way is to use one of available validation frameworks. In this case you validation can be done using annotations. You should remember however that behind the scene such frameworks use reflection.
Here are some links for further reading:
http://commons.apache.org/proper/commons-validator/
http://java-source.net/open-source/validation
http://docs.oracle.com/javaee/6/tutorial/doc/gircz.html

When is using public fields acceptable?

I have a main class that has a thread pool, which is used by quite a few other classes for performing actions on a database. I currently have a getter method to get the pool which works fine but seems a bit clumsy.
Are there any circumstances where it is acceptable to use a public field instead of getter/setter methods?
Are there any circumstances where it is acceptable to use a public field instead of getter/setter methods?
The main reason that public fields are bad are that they expose the implementation to the outside world. That leads to unwanted coupling; i.e. classes that are overly dependent on the implementation details of other classes. That tends to make code harder to understand and harder to change. And if the field is not final, you need to search the entire code-base to be sure that nothing is "interfering" with the field. (OK, IDE's make this easier ... but contrast a public field with a private field that has no setter.)
A secondary reason is that you cannot override a field. Once you have exposed a field in a superclass, there is nothing you can do in a subclass can do to modify or restrict its meaning. (By contrast, getters and setters can be overridden ...)
The only situation where it is acceptable (from a stylistic perspective) to have "public" fields is when the class which declares the fields is a private nested or inner class. The consequence is that all dependencies on the field are restricted to the source file that contains the declaration ... which negates the problems above.
UPDATE - I forgot public static final ... but we tend not to think of those as fields at all. Anyway, it is normal practice to access public static final fields directly. The idea of a constant is to deliberately expose the name, type and value ... and the override issue doesn't apply because of the nature of static fields.
I currently have a getter method to get the pool which works fine but seems a bit clumsy.
"Clumsy" is a matter of opinion / taste. Personally, I don't think that obj.getInstance() is clumsy compared with obj.instance. It is just the Java way1.
The flipside is that if you didn't have a getInstance() method, all of the classes that used the pool would have to have hard-coded references to the instance field. If (for some reasons) you needed to change something about the way the pool was accessed (e.g. add a security check, add a counter, make pool creation lazy, make sure that access is properly synchronized), then you have to change each and every place where you have coded reference to the field. But with a getter, you just have one place to change.
1 - Obviously, other languages do this differently. But you are not writing those languages. Java is what it is.
There are many reasons for using getter & setter instead of a public field. One I've found in SO is
Because 2 weeks (months, years) from now when you realize that your
setter needs to do more than just set the value, you'll also realize
that the property has been used directly in 238 other classes :-)
You can also have a look at this post, which also quotes that i've give above and provides a few other examples. Read and then you can decide whether to use a public field in your case.
Keeping your class fields private and using getter/setter methods provides a layer of abstraction and makes it easier to maintain in the long run. See this: What's the deal with Java's public fields?

Is passing 'this' in a method call accepted practice in java

Is it good/bad/acceptable practice to pass the current object in a method call. As in:
public class Bar{
public Bar(){}
public void foo(Baz baz){
// modify some values of baz
}
}
public class Baz{
//constructor omitted
public void method(){
Bar bar = new Bar();
bar.foo(this);
}
}
Specifically, is the line bar.foo(this) acceptable?
There's nothing wrong with that. What is NOT a good practice is to do the same inside constructors, because you would give a reference to a not-yet-completely-initialized object.
There is a sort of similar post here: Java leaking this in constructor
where they give an explanation of why the latter is a bad practice.
There's no reason not to use it, this is the current instance and it's perfectly legitimate to use. In fact there's often no clean way to omit it.
So use it.
As it's hard to convince it's acceptable without example (a negative answer to such a question is always easier to argument), I just opened one of the most common java.lang classes, the String one, and of course I found instances of this use, for example
1084 // Argument is a String
1085 if (cs.equals(this))
1086 return true;
Look for (this in big "accepted" projects, you won't fail to find it.
Yes, but you should be careful about two things
Passing this when the object has not been constructed yet (i.e. in its constructor)
Passing this to a long-living object, that will keep the reference alive and will prevent the this object from being garbage collected.
It's perfectly normal and perfectly acceptable.
this stands for the current object. What you are doing is sytatically correct but i don't see a need of this if you are calling the method in the same class.
It is bad practice to pass the current object in a method call if there less complex alternatives to achieve the same behaviour.
By definition, a bidirectional association is created as soon as this is passed from one object to another.
To quote Refactoring, by Martin Fowler:
Change Bidirectional Association to Unidirectional (200)
Bidirectional associations are useful, but they carry a price. The
price is the added complexity of maintaining the two-way links and
ensuring that objects are properly created and removed. Bidirectional
associations are not natural for many programmers, so they often are a
source of errors
...
You should use bidirectional associations when you need to but not
when you don’t. As soon as you see a bidirectional association is no
longer pulling its weight, drop the unnecessary end.
So, theoretically, we should be hearing alarm bells when we find we need to pass this and try really hard to think of other ways to solve the problem at hand. There are, of course, times when, at last resort, it makes sense to do it.
Also it is often necessary to corrupt your design temporarily, doing 'bad practice things', during a longer term refactoring of your code for an overall improvement. (One step back, two steps forward).
In practice I have found my code has improved massively by avoiding bidirectional links like the plague.
Yes. you can use it.Its just common in programming to pass this.But there are pros and cons about using that.Still it is not hazardous to do so.
Just to add one more example where passing this is correct and follows good design: Visitor pattern. In Visitor design pattern, method accept(Visitor v) is typically implemented in a way it just calls v.visit(this).
Acceptable
Snippet from Oracle JAVA docs:
Within an instance method or a constructor, this is a reference to the
current object — the object whose method or constructor is being
called. You can refer to any member of the current object from within
an instance method or a constructor by using this.
Using this with a Field
The most common reason for using the this keyword is because a field
is shadowed by a method or constructor parameter.
Everything in java is passed by value. But objects are NEVER passed to the method!
When java passes an object to a method, it first makes a copy of a reference to the object, not a copy of the object itself. Hence this is pefectly used method in java. And most commonly followed usage.

Single instance with methods in java

I am wondering about programming decision - which I think is matter of style.
I need to have single instance of class which has only methods and no attributes.
To obtain that in java I have two options:
create an abstract class with static methods within, thus it will not be possible to create any instance of the class and that is fine,
use a singleton pattern with public methods.
I tend to go for second approach although met with 1. Which and why is better of those, or there is third option.
Would it make sense for that singleton to implement an interface, allowing you to mock out those methods for test purposes?
I know it goes against testing dogma these days, but in certain situations I think a static method is fine. If it's the kind of behaviour which you're never going to want to fake for test purposes, and which is never going to be polymorphic with other implementations, I don't see much point in making a singleton. (Singletons are also generally the enemy of testability, although if you only directly refer to them in the injection part of your code, they can implement appropriate interfaces so their singletoneity never becomes a problem.)
It's worth mentioning that C# has "static classes" for this kind of situation - not only do they prohibit other code from deriving from or instantiating the class, but you can't even use it as a parameter. Basically it signals the intent very clearly.
I would definitely suggest at least having a private constructor to prevent instantiation by the outside world.
My personal view is that the class should contain a private constructor and NOT be abstract. Abstract suggest to a reader that there is a concrete version of the class somewhere, and they may waste time searching for it. I would also make sure you comment your code effectively.
public class myClass {
/** This class should never be instantiated. */
private myClass() {
}
public static void myMethod() {
}
...
//etc
...
}
For option #1, it may not even be that important to restrict instantiation of your static utility class. Since all it has is static methods and no state, there is no point - but neither harm - instantiating it. Similarly, static methods can't be overridden so it does not make sense - nor difference - if it is subclassed.
If it had any state, though - or if there is a chance that it will get stateful one day - it may be better to implement it as a normal class. Still I would prefer not to use it as a Singleton, rather to pass its sole instance around via dependency injection. This makes unit testing so much easier in the long run.
If it holds a state I would use the singleton pattern with private constructors so you can only instantiate from within the class. If it does not hold a state, like the apache commons utility classes, I would use the static methods.
I've never seen the problem with static methods. You can think of static methods as somehow breaking OO, but they make perfect sense if you think of static as a marker that something is stateless. You find this in the java apis in places like java.Math. If you're worried about subclassing you can always make it final.
There is a danger in that a class like that can end up as a "utility method garbage can", but as long as the functionality doesn't diverge too much then there's nothing wrong with it.
It's also clearer, as there's no need to manage an object lifecycle like you would with a singleton (and since there's no state, what's the point of that anyway?).
For a single instance, I suggest you have an enum, with one instance.
However, for a class with no attributes, you don't have to have an instance. You can use a utility class. You can use an enum, with no instances and only static methods. Note: this cannot be easily mocked out.
You can still implement an interface if you ever need to mock out the implementation in testing.

Is there a rule of thumb for when to code a static method vs an instance method?

I'm learning Java (and OOP) and although it might irrelevant for where I'm at right now, I was wondering if SO could share some common pitfalls or good design practices.
One important thing to remember is that static methods cannot be overridden by a subclass. References to a static method in your code essentially tie it to that implementation. When using instance methods, behavior can be varied based on the type of the instance. You can take advantage of polymorphism. Static methods are more suited to utilitarian types of operations where the behavior is set in stone. Things like base 64 encoding or calculating a checksum for instance.
I don't think any of the answers get to the heart of the OO reason of when to choose one or the other. Sure, use an instance method when you need to deal with instance members, but you could make all of your members public and then code a static method that takes in an instance of the class as an argument. Hello C.
You need to think about the messages the object you are designing responds to. Those will always be your instance methods. If you think about your objects this way, you'll almost never have static methods. Static members are ok in certain circumstances.
Notable exceptions that come to mind are the Factory Method and Singleton (use sparingly) patterns. Exercise caution when you are tempted to write a "helper" class, for from there, it is a slippery slope into procedural programming.
If the implementation of a method can be expressed completely in terms of the public interface (without downcasting) of your class, then it may be a good candidate for a static "utility" method. This allows you to maintain a minimal interface while still providing the convenience methods that clients of the code may use a lot. As Scott Meyers explains, this approach encourages encapsulation by minimizing the amount of code impacted by a change to the internal implementation of a class. Here's another interesting article by Herb Sutter picking apart std::basic_string deciding what methods should be members and what shouldn't.
In a language like Java or C++, I'll admit that the static methods make the code less elegant so there's still a tradeoff. In C#, extension methods can give you the best of both worlds.
If the operation will need to be overridden by a sub-class for some reason, then of course it must be an instance method in which case you'll need to think about all the factors that go into designing a class for inheritance.
My rule of thumb is: if the method performs anything related to a specific instance of a class, regardless of whether it needs to use class instance variables. If you can consider a situation where you might need to use a certain method without necessarily referring to an instance of the class, then the method should definitely be static (class). If this method also happens to need to make use of instance variables in certain cases, then it is probably best to create a separate instance method that calls the static method and passes the instance variables. Performance-wise I believe there is negligible difference (at least in .NET, though I would imagine it would be very similar for Java).
If you keep state ( a value ) of an object and the method is used to access, or modify the state then you should use an instance method.
Even if the method does not alter the state ( an utility function ) I would recommend you to use an instance method. Mostly because this way you can have a subclass that perform a different action.
For the rest you could use an static method.
:)
This thread looks relevant: Method can be made static, but should it? The difference's between C# and Java won't impact its relevance (I think).
Your default choice should be an instance method.
If it uses an instance variable it must be an instance method.
If not, it's up to you, but if you find yourself with a lot of static methods and/or static non-final variables, you probably want to extract all the static stuff into a new class instance. (A bunch of static methods and members is a singleton, but a really annoying one, having a real singleton object would be better--a regular object that there happens to be one of, the best!).
Basically, the rule of thumb is if it uses any data specific to the object, instance. So Math.max is static but BigInteger.bitCount() is instance. It obviously gets more complicated as your domain model does, and there are border-line cases, but the general idea is simple.
I would use an instance method by default. The advantage is that behavior can be overridden in a subclass or if you are coding against interfaces, an alternative implementation of the collaborator can be used. This is really useful for flexibility in testing code.
Static references are baked into your implementation and can't change. I find static useful for short utility methods. If the contents of your static method are very large, you may want to think about breaking responsibility into one or more separate objects and letting those collaborate with the client code as object instances.
IMHO, if you can make it a static method (without having to change it structure) then make it a static method. It is faster, and simpler.
If you know you will want to override the method, I suggest you write a unit test where you actually do this and so it is no longer appropriate to make it static. If that sounds like too much hard work, then don't make it an instance method.
Generally, You shouldn't add functionality as soon as you imagine a use one day (that way madness lies), you should only add functionality you know you actually need.
For a longer explanation...
http://en.wikipedia.org/wiki/You_Ain%27t_Gonna_Need_It
http://c2.com/xp/YouArentGonnaNeedIt.html
the issue with static methods is that you are breaking one of the core Object Oriented principles as you are coupled to an implementation. You want to support the open close principle and have your class implement an interface that describes the dependency (in a behavioral abstract sense) and then have your classes depend on that innterface. Much easier to extend after that point going forward . ..
My static methods are always one of the following:
Private "helper" methods that evaluate a formula useful only to that class.
Factory methods (Foo.getInstance() etc.)
In a "utility" class that is final, has a private constructor and contains nothing other than public static methods (e.g. com.google.common.collect.Maps)
I will not make a method static just because it does not refer to any instance variables.

Categories

Resources