At what point should large functions be made static? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
When a function gets even moderately large, I generally change it to become static. For example, if a classes toString() gets pretty big, I usually change it to
public String toString() {
return ClassName.toString(this);
}
private static final String toString(ClassName c_n) {
//.........
}
If the function is not excessively large, is it overkill to do this?
EDIT
I'm getting shot down big time here. :)
I understand how the static modifier should be used in general (for singletons, for stuff unrelated to a specific instance, for utility functions). I'm asking this from an optimization point of view: To avoid a large function's byte code from being duplicated in memory, for each instance of a class. I'm obviously wrong about how it works.

Making the function static depending on the length of the function is totally wrong. Static variables/method are belong to class, not to instances.
So, if there are common functionality between the instances, not depending on any instances, then they can be static.
Here, you have made the toString() as static. But, this method should be describe an instance. Making this as static will give error prone results.
Does it make sense to call this method, even if no object has been constructed yet?" If so, it should definitely be static. Otherwise, that should be instance method

You should make a method static if it doesn't depends of an instance of the class where it is declared. It has nothing to do with the length of the function.

Code (methods) is not replicated per instance, it doesn't need to as it is the same for all instances and is not modified.
Only instance data (properties) is replicated.

Related

Does encapsulation of class methods/fields matter if they are only accessed by the class itself? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
Short context: I made a tetris clone in java (all the game data and methods are a Class) and I am concerned about whether encapsulation matters in this case.
Almost all of the fields and methods are marked as "default", without any getters and setters because the user is not supposed to access them.
Methods manipulate variables directly without any arguments passed, of course only when the thing it is manipulating is unique (there can not be two current pieces, two next block lists, two held pieces and so on)
Do I really need getters and setters if the user is never supposed to get raw members of the class? Methods just directly get and set the values. If I have a simple int that I want to get or set, I am just doing it directly.
No return value, if one exact thing is supposed to happen every time. For example: if a collision happens during spawning, gameOver() is triggered immediately instead of returning false, then doing it outside of function. I chose to not have a return value because it is much simpler to do it inside function instead of surrounding each function call with an if statement doing the same thing.
Do I need to fix some of these things, and how should I, preserving stability in both readability and performance?
It does not.
Why? The understanding is that a class’s fields and methods are working in conjunction towards a common goal. So they are not enemies or careless actors that you have to protect yourself against.
It is only to prevent external actors from mucking up class invariants that you hide your fields and methods as much as possible and expose only that which is necessary.
If you have to use setters and getters to enforce discipline in the code within a class, then you have much bigger problems to handle than maintaining proper encapsulation (and other OO principles.)
No, you do not need getters and setters if you do not intend on anything accessing the member variables from outside of the class.
In your case because the member variables are only accessed from within the class itself then the access modifier(s) should be changed to private.
The use of the default keyword means that you do not want to provide an access modifier and that variable should be available to any other class in the same package.
More info can be found Here

Should pure java methods be static? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
Lets say we have a pure java method. Its a simple validation method. It validates if the input is correct, and throws an exception if not.
static void validateInputIsOk(String input) throws InvalidArgumentException {
if (input == null || !input.equals("Valid input")) {
throw new InvalidArgumentException(new String[]{"Bad input"});
}
}
Its pure, and its static, its small, and easy to reason about.
So i`ve been reading a lot about java static methods and a lot of people advises against this.
Mainly due to testability.
Now that part i fully get. Its not easy mocking a static method. If I use this validator inside some other unit, then I must either accept it will be a part of the test (which could be ok since its pure), or use some sort of static mock framework.
But in order to make it mockable, and non static, I would have to sacrifice the simplicity and readability of my code. I would have to deal with creating the object, and possibly passing it as a parameter to the unit using it.
So in this light I would favour making my pure methods static, and not bother mocking them. It seems the to keep my code most simple and clean.
Would you think im right? Is it something im missing here?
I would argue that you only should mock methods that are public. I would also argue, that you only should test methods that are public. If your tests get too big this way, you should consider splitting up your implementation into more public classes, not necessarily make them non static.
Methods that have no side-effects, the term is functions, should be static. And are good style. Math offers many such functions.
For testing, one would not mock these functions, but test them in isolation.

Any reason to make private methods in a Spring singleton bean static? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I did some research but didn't find an answer that I am looking for. In Spring, DAO and service classes are declared as interface. Classes implementing interfaces are usually singleton Java beans. Question: do you see any reason that I should make private methods that don’t rely on instance variables static? Why?
For example, I have several private methods in a DAO class converting database data to domain object and these private methods don’t use instance variables. I understand some people might suggest that I should extract them to a utility.
The word singleton is used in multiple ways, which can cause a bit of confusion. A "hard" (physical, class-based, JVM) singleton is a class that ensures that only one instance can exist in the entire JVM, usually through an enum or a constant. This pattern should be avoided if the object has any state or configuration at all, since that can cause unexpected coupling between parts of an application. (It's usually fine if the object represents either a pure function, such as CASE_INSENSITIVE_ORDER, or a value.)
In contrast, a singleton-scoped bean (logical, container-based) simply means that the container that is managing it will keep a single shared instance and supply it to all consumers that want one (instead of, for example, creating a separate private copy for each consumer). In most Spring applications, it's actually preferred for these to implement a Java interface that serves as the contract between the two sides, so the methods can't be static.
As to performance questions, static carries a meaning--specifically, that the method or field doesn't have a relationship to a specific instance of that class. Use it when the meaning is appropriate (such as most of the methods in Math), and don't change the meaning of your code in this way for any theoretical performance reason.

Is it bad practice to use a method's return as a parameter in java? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
Is it considered bad practice to use a method that returns an object as a parameter? I have the following method:
public static boolean checkForBlanks(PageDescription pageDesc){
// do some stuff
}
And this method is called within another method:
checkForBlanks(aPage.getPageDescription());
Is it better practice to create a PageDescription object using the getPageDescription method first, then pass that as a parameter(The checkForBlanks methods will check a number of fields on this object) or is there any advantage to be had with the current implementation?
The PageDescription object is not used anywhere else in the calling method, so it is used explicitly in the checkForBlanks method only.
Since the instance returned by aPage.getPageDescription() is only used once within your method, there is no advantage in assigning aPage.getPageDescription() to a variable prior to passing it to checkForBlanks().
In such cases it is simply a matter of preference. I don't like the concept of tieing the hands behind the back in order to fit some misguided concept of code.
In general I prefer the idea of good looking code is good.
checkStuff(storage.getEntry()); is a easy line of good that is clear and everyone can easily follow it.
World.getSomething().doStuff(Storages.getStorage(key).getEntry()); is for example less clear to read.
Keep it clean and simple. That is the best way to go by it. If you look a week later at your code and have no clue what the heck you did, then you did something wrong.
Good code is in the end:
Have fun coding.
you should go with this (good);
checkForBlanks(aPage.getPageDescription());
instead of this (bad):
PageDescription pageDescription = aPage.getPageDescription();
checkForBlanks(pageDescription);
pageDescription in the second variant is an unnecessary local variable because there is no value read from afterwards. So you blow up your code (okay, just one line), and it will cost CPU time and Memory consumption for creating the object. Both is not needed.

What is the most intuitive way to pull an int from an array? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So, I have an object in a class called "arrays":
static arrays VideoGame = new arrays(arrays.product[9], arrays.price[9]);
and a function:
public static void getPrice(int price){
System.out.println("The cost is: " + price);
}
In my main file I call that function like this:
arrays.getPrice(arrays.price[9]);
Is there anything like
arrays.getPrice(VideoGame.price);
that lets you actually use the VideoGame object with the function?
EDIT: I forgot to say that "arrays" is a class I made with functions that create arrays.
I'm just going to go out on a limb and try to answer as best I can.
Assuming arrays is some custom class you made that just defines two arrays and offers getters/setters for those arrays:
Yes, what you seem to what to do is entirely possible although it seems pointless for all practical application. To do so you would just define a variable named "price" in your arrays class and make it public.
You could then use your exact code
arrays.getPrice(VideoGame.price);
However, by adding price to arrays this variable is then added to every instance of arrays. This can be avoided by adding the "static" keyword modifier to your new price variable which means that it will be instantiated at most once. Additionally, when you add the static keyword, I believe you no longer need to specify your specific object - meaning your code could now look even like:
arrays.getPrice(arrays.price);
By making a variable public, you avoid having to make a getter/setter for it, although this is discouraged.

Categories