Lets say I have helper (util) methods and caller
Helper methods:
public int getSomeIntermediateResult(String someString){
// Some operations with someString.
int x = ... ; //Not a constant, but assume it gets created with some computation in method.
return x;
}
public int overallHelperFunction(String someString){
int intermediateResult = getSomeIntermediateResult(someString);
return getFinalOverallResult(someString, intermediateResult);
}
// THIS FUNCTION MUST only be called with the {someString}
// AND the intermediateResult created by getSomeIntermediateResult(someString) only, otherwise it makes no sense.
public int getFinalOverallResult(String someString, int intermediateResult){
// .. donSome Other Stuff and return
}
Here is he trouble I am having, I have two callers
public int callerOne(String someString){
return overallHelperFunction(someString);
}
This one is fine, I can directly call overallHelperFunction which takes care of everything.
The second one is the issue.
public int callerTwo(String someString){
int intermediate = getIntermediateResult(someString);
int finalResult = getFinallOverallResult(someString, intermediate);
return intermediate + finalResult; // I have to REUSE intermediate here.
}
Now this is the main issue.
The thing is the function getFinallOverallResult doesn't make sense if its called with two disjoint someString and intermediateResult so make it a public interface is risky if it gets in the hands of a wrong caller, but at the same time, I need it exposed for callerTwo. What should I do in this case? I did document getFinallOverallResult, but there is no actual restriction of it being called with random params.
Thanks!
Related
I have a java program that models a tv and has stuff like power, channel, volume etc. It also has a unique Serial number that is automatically set (increments 1)
However, for my last array item array[2] I need to referernce my array[0] doing this works but my serialNo is no longer unique and just increments 1 (acts like a new tv has been created)
I think your problem lies in the usage of
public static int serialNo() {
return serialNo++;
}
Each time you call this method, you increment the content of the static field.
There is no direct relation between a TV and its serial number.
I suggest that you create a private field serialNumber in the TV class and assign e.g. in the constructor serialNo to serialNumber and then increment.
serialNo is static member of Tv class, this is what Oracle's documentation says about statics.
Fields that have the static modifier in their declaration are called
static fields or class variables. They are associated with the class,
rather than with any object. Every instance of the class shares a
class variable, which is in one fixed location in memory. Any object
can change the value of a class variable, but class variables can also
be manipulated without creating an instance of the class.
In this case, serialNo is not really associated with any object. So, there won't be something like serialNo of the reference at array[2] in this code.
Now, coming back to the question, you have a for loop that increments serial number as shown below:
for (int i = 0; i < tvDetails.length; i++) {
System.out.println(SERIAL_NO + "\t\t" + tvDetails[0].serialNo() + "\n");
It executes tvDetails.length times (3) ad hence, the number gets incremented. If you don't want it to be incremened there then you need to make a couple of changes:
Remove return serialNo++; from serialNo() method and just return serialNo:
public static int serialNo() {
return serialNo;
}
Increment serialNo in Tv's constructor, e.g.:
public Tv(boolean tvPower, int channel, int volumeLevel) {
this.tvPower = tvPower;
this.channel = channel;
this.volumeLevel = volumeLevel;
serialNo++;
}
The problem is here:
public static int serialNo() {
return serialNo++;
}
This violates the SRP, the Single Responsibility Principle, by doing four things:
* Initializes an instance's serialNo,
* Generates a global "next serial no",
* Reports the global serial no, and
* Reports the instance's serial no, impossible for a static member.
Don't use the same name for different things.
public class Tv {
private static int universalSerial; // not thread-safe
public static int getUniversalSerial() {
return universalSerial;
}
static int dispenseUniversalSerial() {
return universalSerial++;
}
private final int serial;
public Tv () {
this.serial = dispenseUniversalSerial();
}
public int getSerial() {
return serial;
}
#Override public boolean equals(Object other) {
if (this == other) { return true; }
if (! (other instanceof Tv)) { return false; }
Tv otherTv = (Tv) other;
return serial == otherTv.serial;
}
#Override public int hashCode() {
return serial;
}
#Override public String toString() {
return "Tv " + serial;
}
}
Notice how the four tasks are split up between static and instance behaviors. Notice how the different names label different things. Notice the elimination of name parts like No that indicate implementation. Notice the coordinated overrides of the Big Three methods, equals, hashCode, and toString. Notice the lack of override for the fourth member of the Big Three, compareTo. That's deliberate. Notice the lack of thread safety. Notice that the instance serial field is final.
All of those decisions have purpose, and are boilerplate for value classes. The example implementation here is bog standard for non-thread-safe, non-comparable value classes with a factory. You should be able to code one of these up in about 10 minutes. It's a great kata to practice it.
Is it necessary to always initialise the result variable in the function
For example
Public class Calculator
result=addition(a,b);
Public static int addition(int a, int b)
int result;
result =a+b;
return result;
You don't need to have a result variable at all. You need to make sure that every possible way that execution can reach the end of your function (without just throwing an exception) means you get to a return statement, and every return statement has an appropriate express to evaluate, but that doesn't mean you need a separate variable. Your example could be written as:
public static int addition(int a, int b) {
return a + b;
}
If you do use a variable, you'll need to make sure it's definitely assigned before you can read from it, including in a return statement. For example, this won't work because result hasn't been definitely assigned:
public static int addition(int a, int b) {
int result;
if (a < b) {
result = a + b;
}
return result; // Invalid! result may not have a value
}
Where possible, it's generally a good idea to initialize a variable at the point of declaration. So if I were writing this code and wanted a result variable, I'd have:
public static int addition(int a, int b) {
int result = a + b;
return result;
}
Now, looking at your sample code again, you've got another variable used when you call the method:
result=addition(a,b);
It's not clear where that variable would be declared (which is one reason to avoid just posting pseudo-code in questions) but it's completely separate from the result variable in addition, which is local to the addition method. The two variables happen to have the same name, but they're otherwise unrelated. For example, you could easily have:
int sum = addition(a, b);
or call another method with the result instead of assigning it to a variable:
System.out.println(addition(a, b));
Or you could just ignore it entirely:
addtion(a, b); // Valid, but pointless unless there are side-effects
I have a class with several methods. Now I would like to define a helper method that should be only visible to method A, like good old "sub-functions" .
public class MyClass {
public methodA() {
int visibleVariable=10;
int result;
//here somehow declare the helperMethod which can access the visibleVariable and just
//adds the passed in parameter
result = helperMethod(1);
result = helperMethod(2);
}
}
The helperMethod is only used by MethodA and should access MethodA's declared variables - avoiding passing in explicitly many parameters which are already declared within methodA.
Is that possible?
EDIT:
The helper mehod is just used to avoid repeating some 20 lines of code which differ in only 1 place. And this 1 place could easily be parameterized while all the other variables in methodA remain unchanged in these 2 cases
Well you could declare a local class and put the method in there:
public class Test {
public static void main(String[] args) {
final int x = 10;
class Local {
int addToX(int value) {
return x + value;
}
}
Local local = new Local();
int result1 = local.addToX(1);
int result2 = local.addToX(2);
System.out.println(result1);
System.out.println(result2);
}
}
But that would be a very unusual code. Usually this suggests that you need to take a step back and look at your design again. Do you actually have a different type that you should be creating?
(If another type (or interface) already provided the right signature, you could use an anonymous inner class instead. That wouldn't be much better...)
Given the variables you declare at the top of your method can be marked as final (meaning they don't change after being initialized) You can define your helper method inside a helper class like below. All the variables at the top could be passed via the constructor.
public class HelperClass() {
private final int value1;
private final int value2;
public HelperClass(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
public int helperMethod(int valuex) {
int result = -1;
// do calculation
return result;
}
}
you can create an instance of HelperClass and use it inside the method
It is not possible. It is also not good design. Violating the rules of variable scope is a sure-fire way to make your code buggy, unreadable and unreliable. If you really have so many related variables, consider putting them into their own class and giving a method to that class.
If what you mean is more akin to a lambda expression, then no, this is not possible in Java at this time (but hopefully in Java 8).
No, it is not possible.
I would advise you create a private method in your class that does the work. As you are author of the code, you are in control of which other methods access the private method. Moreover, private methods will not be accessible from the outside.
In my experience, methods should not declare a load of variables. If they do, there is a good chance that your design is flawed. Think about constants and if you couldn't declare some of those as private final variables in your class. Alternatively, thinking OO, you could be missing an object to carry those variables and offer you some functionality related to the processing of those variables.
methodA() is not a method, it's missing a return type.
You can't access variables declared in a method from another method directly.
You either has to pass them as arguments or declare methodA in its own class together with the helpermethods.
This is probably the best way to do it:
public class MyClass {
public void methodA() {
int visibleVariable=10;
int result;
result = helperMethod(1, visibleVariable);
result = helperMethod(2, visibleVariable);
}
public int helperMethod(int index, int visibleVariable) {
// do something with visibleVariable
return 0;
}
}
If this class is used in multi-threaded environment and say 100 threads calling this method at same time .
Case 1 : instance method
public class test {
public int add(int a , int b ){
return a+b ;
}
}
case 2: static method
public class test {
public static int add(int a , int b ){
return a+b ;
}
}
Please answer both cases .
Since you are not using any state/instance variable you do not need to synchronize the method or the object.
A friendly suggestion: make the method static. Ans call it on the class.
It does not need any synchronization because all the variables are local. i.e, no variable is actually shared between any of the callers.
If you did this, you would need sync because var c is shared. Before c was retrieved in the final 'return c' another thread may have already modified it.
public class test {
int c = 0;
public int addKeep(int a , int b ){
c = a + b;
return c;
}
}
An other answer here says to make it static. Well, it depends on what you need to do. If the add(int a, int b) is a behaviour that subclasses could override, then keep it as an instance method. If it was part of a Math.class per-se, then make it static as it will likely never be needed to be over-riden.
If object is mutable and you are doing read-update operations then only we need to use synchronization block for getter and setters(i.e. mutating methods ).
Problem details. I need to create a framework to perform various checks, like:
- is Date A between dates B and C?
- is Integer A greater than Integer B and smaller than Integer C?
etc.
So far, i am thinking of two possible implementations, detailed bellow.
Impl1 - using a single class to perform the checks, based on the check type.
import java.sql.Time;
import java.util.Date;
public class SearchManager {
public final static int SEARCH_TYPE_DATE = 0;
public final static int SEARCH_TYPE_INT = 1;
public final static int SEARCH_TYPE_STRING = 2;
public final static int SEARCH_TYPE_TIME = 3;
private final int searchType;
public SearchManager(int searchType) {
this.searchType = searchType;
}
public final boolean doCompare(Object minValue, Object maxValue, Object toBeCompared) {
switch (this.searchType) {
case SEARCH_TYPE_DATE: {
return compareDates((Date) minValue, (Date) maxValue, (Date) toBeCompared);
}
case SEARCH_TYPE_INT: {
return compareIntegers((Integer) minValue, (Integer) maxValue, (Integer) toBeCompared);
}
case SEARCH_TYPE_STRING: {
return compareStrings(String.valueOf(minValue), String.valueOf(maxValue), String.valueOf(toBeCompared));
}
case SEARCH_TYPE_TIME: {
return compareTimes((Time) minValue, (Time) maxValue, (Time) toBeCompared);
}
default:
return false;
}
}
private boolean compareDates(Date min, Date max, Date toBeCompared) {
boolean result = false;
// actual comparison
return result;
}
private boolean compareIntegers(Integer min, Integer max, Integer toBeCompared) {
boolean result = false;
// actual comparison
return result;
}
private boolean compareStrings(String min, String max, String toBeCompared) {
boolean result = false;
// actual comparison
return result;
}
private boolean compareTimes(Time min, Time max, Time toBeComparedDate) {
boolean result = false;
// actual comparison
return result;
}
}
Impl2 - Using an abstract class or interface, and having an implementation of the comparison method for each search type.
public abstract class AbstractSearch {
public final static int SEARCH_TYPE_DATE = 0;
public final static int SEARCH_TYPE_INT = 1;
public final static int SEARCH_TYPE_STRING = 2;
public final static int SEARCH_TYPE_TIME = 3;
public AbstractSearch() {
super(); //just for fun
}
protected abstract boolean doCompare(Object minValue, Object maxValue, Object toBeComparedValue);
}
Now, in this example, for X different search types, as you can imagine, X implementations of the AbstractSearch will be created.
Just imagine yourself that the class AbstractSearch from the 2nd implementation will need to perform additional tasks, other than the method doCompare(..) and that is why an interface is not my 1st candidate for this solution, and to write something like
public abstract class AbstractSearch implements Searcheable
would not help me a lot, since AbstractSearch or SearchManager will handle ALL the comparisons, and, if a new comparison type should be needed, an additional type/subclass implementation will be declared for corresponding super classes from Impl1 or Impl2.
My question is about which implementation is faster? And this is very important, since the comparison process will be called in loops containing thousands of elements.
Thank you for reading/answering my question.
EDIT1: Also, please have in mind the fact that minValue and maxValue will be extracted from the classes that extends the AbstractSearch, for the second example, or classes extending SearchManager, as for the 1st example. These implementation will actually be graphical components allowing the user to enter a minimum and a maximum value, and then, these value will be compared in a loop with some bean property, of objects displayed in a table.
EDIT2: I am doing some benchmarks, with dummy implementations (i just want to compare the method call time vs switch execution time). The results are..surprising:
Using AbstractSearch (500k loops): -0.047 seconds
Using SearchManager (500k loops): -0.422 seconds
Having these results, it is safe to assume that using inheritance is much faster than using a switch (or even worse an if-else test) ?
If you want to make this code as fast as possible, also try using overloaded methods like this:
public final static boolean doCompare(Date min, Date max, Date toCompare) {
// ...
}
public final static boolean doCompare(int min, int max, int toCompare) {
// ...
}
// ...and so on
At compile time, the compiler will generate a direct call to the appropriate method, based on the types which you pass. (If you are passing Object references which might point to an instance of any of the 4 types, this won't work.)
If the values which you are comparing are ints, passing them to a method which takes Object arguments will require boxing and unboxing, which adds overhead.
If performance is really important, I recommend you use static methods, since they are a bit faster in many Java implementations.
Also, rather than using compareTo, you can probably squeeze out a bit more performance by using your own inline code for the comparisons.
EDIT: You said in the edited question that min and max will actually be passed in by a subclass of SearchManager. In that case I would make SearchManager abstract, and put different implementations of doCompare in each subclass of SearchManager. What I said about static methods won't work in this case.
I would think that the best idea would be to combine both ideas (and make it more type safe) and take advantage of the fact that all the types that you provide in your example (Date, Time, String, and Integer) are Comparable
public final <A> boolean doCompare (Comparable<A> min, Comparable<A> max, A target)
{
return (min.compareTo(target) < 0) && (max.compareTo(target) > 0)
}
This is definitely a lot faster than the first implementation since it does not have to do any type checks (all checks will be done compile time) and is type safer and no slower than the second (while also being more flexible about type).
Is this just something that you can do with a comparison? (It looks like it.) Is this method essentially the same for all three implementations?
If so, just write
static <T extends Comparable<T>> boolean doCompare(T min, T max, T toCompare) {
// impl here
}
Fun question! Why don't you benchmark your two implementations?