using instance initializer to deal with constructor overloading - java

A pattern I sometimes see is that a constructor might take either no argument or one argument. Now, I wonder whether the 'better' approach is to move common code to the most defined constructor - or to use the instance initializer in this case. For example, one way of always generating an ID for every class created:
public SomeClass(){
this("Hello");
}
public SomeClass(String s){
this.s = s;
this.id = generateId();
}
versus writing it like this:
{
this.id = generateId(); // method does not depend on the class
}
public SomeClass(){
this("Hello");
}
public SomeClass(String s){
this.s = s;
}
The reason for using the Instance Initializer would be because I want to always run the method when the class is created, and in the future someone else might change the class's constructors and forget to do this. Whilst it is less likely to remove the instance initializer (without realizing what you are doing).
But on the other hand, I am not sure how about readability in this case.
The examples are a bit contrived, not real-world examples.

The reason for using the Instance Initializer would be because I want
to always run the method when the class is created, and in the future
someone else might change the class's constructors and forget to do
this. Whilst it is less likely to remove the intance initializer
(without realising what you are doing).
Doing the one (using the Instance Initializer) or the other one (constructor) should not be used as trick to avoid coding error when the class is modified.
And anyway, why Initializer would give better insurance about it ?
You want to ensure that the constructor do what it designed to do ?
Writing an unit test that validates this behavior and that is automatically executed at each build.
That's all.

I think the reasonable solution here:
private final Whatever id = generateId();
In other words:
make sure the compiler knows that this should be initialized (so use final)
and instead of using an init block (rather uncommon) simply do initialize once, "in place"

I have never seen a use of instnace initializer in real life. (I actually did see it and played with it for a bit in one of theoretical questions on this site). In real life though you often can see a static initializer block:
public class Bla {
static {
//do something
}
....
}
As for common code what could be done is to have a method called init() that is called by all constructors. In your example it would look like
public SomeClass(){
this("Hello");
}
public SomeClass(String s){
init();
this.s = s;
}
private init() {
this.id = generateId(); // method does not depend on the class
}

Related

What is the alternative to a static initialization block?

My projects had some developer who loved a static initialization block. What is the alternative to this? What is the downside of this alternative?
public class BlockTest {
String test = new String();
static{
test = "test string";
}
}
As far as I understood the static initialization block is used to set values of static field if it cannot be done in one line. But I do not understand why we need a special block for that. This leads to less readability and some confusion.
The example is not good. First of all it does not compile, you cannot assign a instance variable from static init block. But if even it were correct
public class BlockTest {
static String test = new String();
static{
test = "test string";
}
it would make no sense since it is equivalent to
public class BlockTest {
static String test = "test string";
but this static init block has no alternative
public class Object {
private static native void registerNatives();
static {
registerNatives();
}
...
It can be used for performing all the tasks that needs to be done when the class is referred for the first time, even before the instances of the class are created. It could have call to different methods or just initialization of static members. Static block ensures that these activities will be performed only once in the lifetime of the class and will be performed before any other operation takes place with regard to the class.
Programmer can depend on static block as it is ensured that the block will be executed only once and before any other activity related to that class is performed.
Moreover, I do not think it hampers readability at all. It again may vary from person to person.
If you have static members in your class which require a longer handling, you won't get around a static initializer (constructor). These must be initialized somewhere after all. You could do that in the constructor of your class, but then you would reinitialize these values EVERYTIME you create a new object.
There is no real alternative if you must handle more than just a simple initialization.
See this post and this.
If you have simple assignments, you can do the assignment directly in the member declaration. No need for a separate block which just extends the complexity and readabillity.
An alternative would be to use a lazy initialization. Advantage is that it can also be arbitrary complex, but is only executed when actually needed. But of course this only works if you have getters in your classes. If you access the members directly, then this would be a big change.
IMHO,There is no need for static block.
String test = "test string";
And From docs
Instance variables can be initialized in constructors, where error handling or other logic can be used. To provide the same capability for class variables, the Java programming language includes static initialization blocks.
But
Note: It is not necessary to declare fields at the beginning of the class definition, although this is the most common practice. It is only necessary that they be declared and initialized before they are used.

Better to use object method during initialization or after, if you only have one method?

This question is bound to scream poor programming practice, however, I'm curious if there is any performance risk involved here.
Imagine you have a class that only has one method attached (excluding the constructor) to it, for simplicity sake we'll say:
public class TestClass{
public TestClass(){
// Set values or whatever you want in the constructor
}
public String printString(){
System.out.println("print");
}
}
Now considering there is only one method, obviously anytime you use the class you'll probably want to call the method printString. So are there any negatives (besides sanity) to putting a call to printString in the constructor? Rather than doing testClass test = new testClass() then making a call test.printString()?
Again, this question is about performance - not programming practice.
what you can do is use Enum
public enum TestEnum {
TestEnum;
public String printString() {
System.out.println("print");
return null;
}
}
There will not be much difference in performance point of view but from coding point of view you will have no need to create object every time. Also you can have static utility class as enum.
You can put printString into an enum Utility class or Singleton like
public enum TestClass {;
public static void printString(){
System.out.println("print");
}
}
However, from a performance point of view, creating a new object each time is very small compared to the cost of writing a line to the console. The different is notional.
There is no performance difference in opinion as compiler has same statements to compile (whether you put the statement in calling class or in constructor) and JVM has exact statements to execute.

Change private member to default for testing

Is that good idea to change private class members to default(package access) for testing their behavior? I mean test case should destinate in test directory but in same package as tested member's class.
EDIT: All you guys tell the true. But classes have helper private methods often. And these methods can be complicated so need to be tested. And that is too bad - to test public methods for ensure correct working for private complicated methods. Don't you think so?
I generally prefer writing my classes and tests in a way that writing the tests against the public API makes sense. So basically I'm saying if you need to access the private state of your class under test you're probably already too involved in the internals of that class with your test..
No, it isn't. Because changing the test object may change the result. If you really need to call private members or methods during test, it's safer to add an accessor. This still changes the class, but with a lower risk. Example:
private void method() { /* ... */ }
// For testing purpose only, remove for production
#Deprecated // just another way to create awareness ;)
void testMethod() {
method();
}
OK - one more solution, if you need to test private methods: you can call any method with reflection and instantiation API.
Assuming, we have:
public class SomeClass {
private Object helper(String s, String t) { /* ... +/ }
}
then we can test it like
#Test public void testHelper() {
try {
SomeClass some = new SomeClass();
Method helperMethod = some.getClass().getDeclaredMethod("helper", String.class, String,class);
helperMethod.setAccessible(true);
Object result = helperMethod.invoke(some, "s", "t");
// do some assert...
catch(Exception e) {
// TODO - proper exception handling
}
}
I understand what you mean about needing to test private methods, and I also see why people say only test the public methods. I have just encountered some legacy code that has a lot of private methods, some of which are called by public methods, but some are threads, or called by threads, which are kicked off when the object is constructed. Since the code is riddled with bugs and lacks any comments I am forced to test the private code.
I have used this method to address the issue.
MainObject.cs
class MainObject
{
protected int MethodOne(); // Should have been private.
....
}
TestMainObject.cs
class ExposeMainObject : MainObject
{
public int MethodOne();
}
class TestMainObject
{
public void TestOne()
{
}
}
Since the test objects aren't shipped I can't see a problem with it, but if there is please tell me.
Testing trumps privacy modifiers. Really, how often is a bug caused by having "a little too much" visibility for a method? Compared to bugs caused by a method that was not fully tested?
It would be nice if Java had a "friend" option, like C++. But a limitation in the language should never be an excuse for not testing something.
Michael Feathers chimes in on this debate in "Working Effectively with Legacy Code" (excellent book), and suggests that this may be a smell of a sub-class that wants to be extracted (and have public methods).
In our shop (~ 1M LOC), we replace 'private' with '/TestScope/' as an indicator that a method should be effectively private, but still testable.
Trying to circumvent 'private' with reflection is IMHO a smell. It's making the tests harder to write, read, and debug in order to retain a 'fetish' of privacy, which you're working around anyway. Why bother?

Can I use methods of a class without instantiating this class?

I have a class with several methods and there is no constructor among these methods.
So, I am wondering if it is possible to call a method of a class without a creation of an instance of the class.
For example, I can do something like that:
NameOfClass.doMethod(x1,x2,...,xn)
In general I do not see why it should be impossible. I just call a function which does something (or return some values). If it is possible, what will happen if the method sets a value for a private variable of the class. How can I reach this value? In the same way?
NameOfClass.nameOfVariable
It's called static variables and static methods. Just try it and see that it compiles.
If the methods are static, yes.
But you won't be able to access non-static members.
1) YES, you can use the methods of a class without creating an instance or object of that class through the use of the Keyword "Static".
2) If you declare the method as "Static" then you can call this method by :
*ClassName.MethodName()*
3) E.g.
class Hello {
public static void print()
{
System.out.println("HelloStatic");
}
}
class MainMethod {
public static void main(String args[])
{
// calling static method
Hello.print();
}
}
4) The output of the above program would be : HelloStatic
As many have pointed out: This is only possible if the method is static. Maybe some OOP background is in order: A method should always belong to a class. So what is the use of calling a method without an instance of a class? In a perfect OO world there shouldn't be any reason to do that. A lot of use cases that have to do with static methods talk about assigning some kind of identity to your class. While this is perfectly reasonable in a programming world it isn't very convincing when it comes to object oriented design.
As we program in an imperfect world there is often a use case for a "free function" (The way Java or C++ implement sort() for example). As Java has no direct support for free functions classes with only static "methods" are used to express those semantics with the added benefit of the class wrapper providing a "namespace". What you think of this workaround and if you see it as a flaw in language design is IMO a matter of opinion.
In most languages you can do it only if method is static. And static methods can change only static variables.
I have a class with several methods and there is no constructor among these methods.
If you don't explicitly define a constructor then you get a default constructor provided by the compiler. So if those methods aren't static, try this:
NameOfClass x = new NameOfClass();
x.doMethod(x1,x2,...,xn);
A method on a class operates in the context an instance; it has access to the instance's member variables. You understand this, because you ask about what happens if the method accesses one of those variables.
You can understand why it doesn't work by asking yourself the question: "Where is the data?" If you don't have an instance, where is the instance variable? Where is the data? And the answer is that it doesn't have a place and therefore doesn't work.
The difference with a static function and static member variables is that you can answer the question about the location of the data. The static variables available regardless of whether there is a specific instance or not. The instance specific vs. class specific decision is one that you must make considering what you actually want to do.
That would be static methods.
I have a class with several methods
and there is no constructor among
these methods.
Do you mean you have something like:
public class X
{
public void foo()
{
}
}
or do you mean you have something like:
public class X
{
private X()
{
}
public void foo()
{
}
}
If it is the fist way then, yes, there is a constructor and it will look like this:
public X()
{
super();
}
if it is the second way then there is probably a method like:
public static X createInstance()
{
return (new X());
}
If you really mean can classes have methods that do things without ever creating an instance, then yes you can, just make all of the methods and variables static (usually this is not a good idea, but for some things it is perfect).
Since qre is a static method and doesn't have an access to instances of the enclosing class you'll have first to create an instance and then access it. For example:
public class Foo {
private int bar;
public static void qre() {
Foo foo = new Foo();
foo.bar = 5;
System.out.println("next bar: " + (++5));
}
}
In proper encapsulation, you should not "see" what is happening upon instanciation. To rely on a class's lack of a constructor is breaking this form. The designed of the class my have in mind to add formal state initialization in the constructor at a later date. Your "contract" with the class is only that you can use the methods as they are currently designed.
If you desire to use the functionality of that method without the class overhead, maybe it best for you to include that method in your existing "client" class (of course this is just "copy and paste" coding and is considered an anti-pattern of of software design.
If you are using lombok, here is what you can do:
package util;
import lombok.experimental.UtilityClass;
#UtilityClass
public class UtilFunctions {
public static int SumOfTwoNumber(int a, int b){
return a+b;
}
}
In UtilFunctions class here with #UtilityClass annotation, you can keep all the functions which you want to call anywhere in your project. For the sake of simplicity, I have created a function SumOfTwoNumber which I want to use in my main class. Here is how I can call it in the main class:
import util.UtilFunctions;
public class HeadFirstJavaApplication {
public static void main(String[] args) {
int a = 10, b = 20;
int sum = UtilFunctions.SumOfTwoNumber(a,b);
System.out.println(sum);
}
}
P.S: Don't forget to add lombok dependency to be able to use it. In case of gradle, here is how to add the lombok dependency:
dependencies {
compileOnly 'org.projectlombok:lombok:1.18.16'
annotationProcessor 'org.projectlombok:lombok:1.18.16'
testCompileOnly 'org.projectlombok:lombok:1.18.16'
testAnnotationProcessor 'org.projectlombok:lombok:1.18.16'
}

Ways for lazy "run once" initialization in Java with override from unit tests

I'm looking for a piece of code which behaves a bit like a singleton but isn't (because singleton's are bad :) What I'm looking for must meet these goals:
Thread safe
Simple (Understand & use, i.e. few lines of code. Library calls are OK)
Fast
Not a singleton; for tests, it must be possible to overwrite the value (and reset it after the test).
Local (all necessary information must be in one place)
Lazy (run only when the value is actually needed).
Run once (code on RHS must be executed once and only once)
Example code:
private int i = runOnce(5); // Set i to 5
// Create the connection once and cache the result
private Connection db = runOnce(createDBConnection("DB_NAME"));
public void m() {
String greet = runOnce("World");
System.out.println("Hello, "+greet+"!");
}
Note that the fields are not static; only the RHS (right hand side) of the expression is ... well "static" to some degree. A test should be able to inject new values for i and greet temporarily.
Also note that this piece of code outlines how I intend to use this new code. Feel free to replace runOnce() with anything or move it to some other place (the constructor, maybe, or an init() method or a getter). But the less LOC, the better.
Some background information:
I'm not looking for Spring, I'm looking for a piece of code which can be used for the most common case: You need to implement an interface and there won't ever be a second implementation except for tests where you want to pass in mock objects. Also, Spring fails #2, #3 and #5: You need to learn the config language, you must set up the app context somewhere, it needs an XML parser and it's not local (information is spread all over the place).
A global config object or factory doesn't meet the bill because of #5.
static final is out because of #4 (can't change final). static smells because of classloader issues but you'll probably need it inside runOnce(). I'd just prefer to be able to avoid it in the LHS of the expression.
One possible solution might be to use ehcache with a default setup which would return the same object. Since I can put things in the cache, this would also allow to override the value at any time. But maybe there is a more compact/simple solution than ehcache (which again needs an XML config file, etc).
[EDIT] I'm wondering why so many people downvote this. It's a valid question and the use case is pretty common (at least in my code). So if you don't understand the question (or the reason behind it) or if you have no answer or you don't care, why downvote? :/
[EDIT2] If you look at the app context of Spring, you'll find that more than 99% of all beans have just a single implementation. You could have more but in practice, you simply don't. So instead of separating interface, implementation and configuration, I'm looking at something which has only an implementation (in the most simple case), a current() method and one or two lines of clever code to initialize the result for current() once (when it is called for the first time) but at the same times allows to override the result (thread safe, if possible). Think of it as an atomic "if(o==null) o = new O(); return o" where you can override the o. Maybe an AtomicRunOnceReference class is the solution.
Right now, I just feel that what we all have and use daily is not the optimum, that there is a baffling solution which will make us all slap our heads and say "that's it". Just as we felt when Spring came around a few years ago and we realized where all our singleton problems came from and how to solve them.
The best idiom for threadsafe initialization code (imho) is the lazy inner class. The classic version is
class Outer {
class Inner {
private final static SomeInterface SINGLETON;
static {
// create the SINGLETON
}
}
public SomeInterface getMyObject() {
return Inner.SINGLETON;
}
}
because it's threadsafe, lazy-loading and (imho) elegant.
Now you want testability and replaceability. It's hard to advise without knowing what exactly it is but the most obvious solution would be to use dependency injection, particularly if you're using Spring and have an application context anyway.
That way your "singleton"'s behaviour is represented by an interface and you simply inject one of those into your relevant classes (or a factory to produce one) and then you can of course replace it with whatever you like for testing purposes.
Here is a solution that fulfills all my requirements:
/** Lazy initialization of a field value based on the (correct)
* double checked locking idiom by Joschua Bloch
*
* <p>See "Effective Java, Second Edition", p. 283
*/
public abstract class LazyInit<T>
{
private volatile T field;
/** Return the value.
*
* <p>If the value is still <code>null</code>, the method will block and
* invoke <code>computeValue()</code>. Calls from other threads will wait
* until the call from the first thread will complete.
*/
#edu.umd.cs.findbugs.annotations.SuppressWarnings("UG_SYNC_SET_UNSYNC_GET")
public T get ()
{
T result = field;
if (result == null) // First check (no locking)
{
synchronized (this)
{
result = field;
if (result == null) // Second check (with locking)
{
field = result = computeValue ();
}
}
}
return result;
}
protected abstract T computeValue ();
/** Setter for tests */
public synchronized void set (T value)
{
field = value;
}
public boolean hasValue()
{
return field != null;
}
}
You can use IoC techniques even if you dont use an IoC framework (Spring/Guice/...). And it is in my opinion the only clean way to avoid a Singleton.
I think one solution you could use is providing a protected method which can be overriden in the test (a solution I've used before for testing legacy code).
So something like:
private SomeObject object;
protected SomeObject getObject() {
if (object == null) {
object = new SomeObject();
}
return object;
}
Then in your test class you can do:
public void setUp() {
MyClassUnderTest cut = new MyClassUserTest() {
#Override
protected SomeObject getObject() }
return mockSomeObject;
}
};
}
I have to say I'm not overly keen on this pattern as it exposes the protected field where you might not really want it, but it's useful for getting you out of some situations where injection isn't an option

Categories