As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
In near future we might be enforced by a rule by which we can not have any hard coded numbers in our java source code. All the hard coded numbers must be declared as final variables.
Even though this sounds great in theory it is really hard/tedious to implement in code, especially legacy code. Should it really be considered "best practice" to declare numbers in following code snippets as final variables?
//creating excel
cellnum = 0;
//Declaring variables.
Object[] result = new Object[2];
//adding dash to ssn
return ssn.substring(1, 3)+"-"+ssn.substring(3, 5)+"-"+ssn.substring(5, 9);
Above are just some of the examples I could think of, but in these (and others) where would you as a developer say enough is enough?
I wanted to make this question a community wiki but couldn't see how...?
Definitely no. Literal constants have their places, especially low constants such as 0, 1, 2, ...
I don't think anyone would think
double[] pair = new double[PAIR_COUNT];
makes more sense than
double[] pair = new double[2];
I'd say use final variables if
...it increases readability,
...the value may change (and is used in multiple places), or
...it serves as documentation
A related side note: As always with coding standards / conventions: very few (if any) rules should be followed strictly.
Replacing numbers by constants makes sense if the number carries a meaning that is not inherently obvious by looking at its value alone.
For instance,
productType = 221; // BAD: the number needs to be looked up somewhere to understand its meaning
productType = PRODUCT_TYPE_CONSUMABLE; // GOOD: the constant is self-describing
On the other hand,
int initialCount = 0; // GOOD: in this context zero really means zero
int initialCount = ZERO; // BAD: the number value is clear, and there's no need to add a self-referencing constant name if there's no other meaning
Generally speaking, if a literal has a special meaning, it should be given a unique name rather than assuming things. I'm not sure why it is "practically" hard/tedious to do the same.
Object[] result = new Object[2]; => seems like a good candidate for using a Pair class
cellnum = 0; => cellnum = FIRST_COLUMN; esp since you might end up using an API which treats 1 as the starting index or maybe you want to process an excel in which columns start from 2.
return ssn.substring(1, 3)+"-"+ssn.substring(3, 5)+"-"+ssn.substring(5, 9) => If you have code like this littered throughout your codebase, you have bigger problems. If this code exists in a single location and is shielded by a sane API, I don't really see a problem here.
I've seen folks consider 0 and 1 accepted exceptions.
The idea is that you want to document why you have two Objects as above for example.
I agree with you about the dashes in SSN. The comment describes it better than 4 named constants.
In general, I like the idea of no magic numbers, but as with every rule, there are pragmatics involved. Legacy code, brings its own issues. It's a lot of work without a lot of productivity in terms of changed behavior to bring old code up to date this way. I would consider doing it in an evolutionary fashion: when you have to edit an old file, bring it up to date.
It really depends on the context doesn't it. If there are numbers in the code that does not indicate why they exist then naming them makes teh code more readable. If you see the number 3.14 in code is it PI? is there any way to tell or is that just a coincidence? Naming it PI will clear up the mystery.
In your example, why is cellnum = 2? why not 10? or 20? That should be named something, say INITIAL_CELL or MAX_CELL. Expecially if this same number, meaning the same thing appears again in the code.
Depends if it needs to be changed. Or for that matter, it can be changed.
If you only need 2 objects (say, for a pair like aioobe mentioned) then that isn't a magic number, it's the correct number. If it's for a variable tuple that, at this moment, is 2, then you probably should abstract it out into a constant.
Related
I have been going through the Java interview questions asked by my company and came across one that I can't seem to find the solution.
Here is the question:
Please write a method (function) accepting as single parameter a
string and reversing the order of the words in this string.
The " " is the word separator and any other char is considered as being part of a word. In order to simplify, please consider that there is always one space between the words.
Important - You are NOT allowed to use other strings or arrays or other data structures containing several elements - just plain atomic variables such as integers, chars etc.
Also, it is not allowed to use any other language specific string function other than the function giving you the length of the string.
Expected result:
"hello my beautiful world" -> "world beautiful my hello"
So, I can't use: chars[], str.split(), str.charAt(), str.substring(), StringBuilder, another declaration of String.
Should I use recursion to do it?
Since, String is Immutable and uses encapsulation,
There is no solution to your problem. You can't update the values directly, no setters are available and without the access to the getters (since you can only use .length), you can't read the value.
So, I would suggest to respond that Immutability and encapsulation prevent you from doing so.
In real life as a software engineer, you'll sometimes be asked to do things that are technically impossible or even nonsensical. Sometimes the person asking will be someone important like your boss or a big customer.
If someone actually asks you this interview question, then you're in one of those situations. That makes this question pretty interesting, and you might want to figure out what the best way to answer really is.
If someone asked me, this is how I would answer, and as an interviewer, this is the kind of answer I would award the most points for:
1) Explain how it's technically impossible to meet the requirements, but do it without making me feel stupid. This shows diplomacy.
2) Figure out what I really want. In this case, the interviewer probably wants to see if you know how to reverse the words in a string using low-level operations. This is a perfectly reasonable C language question, for example. Figuring out what the interviewer really wants shows experience and judgement.
3) Provide an answer that gives me what I want. Write this method in Java, but take a StringBuilder instead of a string, and call only length(), charAt(), and setCharAt(). This shows the expertise that the interviewer wants to see.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I need suggestion for the right approach to apply conditions in Java.
I have 100 conditions based on which I have to change value of a String variable that would be displayed to the user.
an example condition: a<5 && (b>0 && c>8) && d>9 || x!=4
More conditions are there but variables are the same more or less.
I am doing this right now:
if(condition1)
else if(condition2)
else if(condition3)
...
A switch case alternative would obviously be there nested within if-else's i.e.
if(condition1)
switch(x)
{
case y:
blah-blah
}
else if(condition2)
switch(x)
{
case y:
blah-blah
}
else if(condition3)
...
But I am looking for some more elegant solution like using an Interface for this with polymorphic support , What could be the thing that I could possibly do to avoid lines of code or what should be the right approach.
---Edit---
I actualy require this on an android device. But its more of a java construct here.
This is a small snapshot of conditions that I have with me. More will be added if a few pass/fail. That obviously would require more if-else's with/without nesting. In that case would the processing go slow.
I am as of now storing the messages in a separate class with various string variables those I have kept static so if a condition gets true
then I pick the static variable from the only class and display that
one. Would that be right about storing the resultant messages.
Depending on the number of conditional inputs, you might be able to use a look-up table, or even a HashMap, by encoding all inputs or even some relatively simple complex conditions in a single value:
int key = 0;
key |= a?(1):0;
key |= b?(1<<1):0;
key |= (c.size() > 1)?(1<<2):0;
...
String result = table[key]; // Or result = map.get(key);
This paradigm has the added advantage of constant time (O(1)) complexity, which may be important in some occasions. Depending on the complexity of the conditions, you might even have fewer branches in the code-path on average, as opposed to full-blown if-then-else spaghetti code, which might lead to performance improvements.
We might be able to help you more if you added more context to your question. Where are the condition inputs coming from? What are they like?
And the more important question: What is the actual problem that you are trying to solve?
There are a lot of possibilities to this. Without knowing much about your domain, I would create something like (you can think of better names :P)
public interface UserFriendlyMessageBuilder {
boolean meetCondition(FooObjectWithArguments args);
String transform(String rawMessage);
}
In this way, you can create a Set of UserFriendlyMessageBuilder and just iterate through them for the first that meets the condition to transform your raw message.
public class MessageProcessor {
private final Set<UserFriendlyMessageBuilder> messageBuilders;
public MessageProcessor(Set<UserFriendlyMessageBuilder> messageBuilders) {
this.messageBuilders = messageBuilders;
}
public String get(FooWithArguments args, String rawMsg) {
for (UserFriendlyMessageBuilder msgBuilder : messageBuilders) {
if (msgBuilder.meetCondition(args)) {
return msgBuilder.transform(rawMsg);
}
}
return rawMsg;
}
}
What it seems to me is "You have given very less importance to design the product in modules"
Which is the main factor of using OOP Language.
eg:If you have 100 conditions and you are able to make 4 modules then therotically for anything to choose you need 26 conditions.
This is an additional possibility that may be worth considering.
Take each comparison, and calculate its truth, then look the resulting boolean[] up in a truth table. There is a lot of existing work on simplifying truth tables that you could apply. I have a truth table simplification applet I wrote many years ago. You may find its source code useful.
The cost of this is doing all the comparisons, or at least the ones that are needed to evaluate the expression using the simplified truth table. The advantage is an organized system for managing a complicated combination of conditions.
Even if you do not use a truth table directly in the code, consider writing and simplifyin one as a way of organizing your code.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
In many cases, mostly when you are looping through an array and assigning values to the elements, there is a scope to use post increment operator. Is it considered a good practice.
For example, in the following code where the copying is being done which one is better.
int [] to_assign;
int [] to_include;
int [] from_assign;
// Version 1
int count = 0;
while(i<<some_value>){
if(to_include[i]==1)
to_assign[count++] = from_assign[i];
}
// Version 2
int count = 0;
while(i<<some_value>){
if(to_include[i]==1)
{
to_assign[count] = from_assign[i];
count++;
}
}
It's purely a matter of style. Personally, I'd use whichever one makes the most logical sense. If the increment is logically part of the operation, then use the post-increment. If not, use a separate increment operation.
Also, when you use an increment operator alone, it is generally preferred to use a pre-increment. While it won't matter with simple types like integers, with more complex types, it can be much more efficient in languages like C++ that have operator overloading because a pre-increment doesn't need two instances to be around at the same time. There's no performance impact with Java, because it doesn't have operator overloading, but if you want a consistent style rule, it should be pre-increment rather than post-increment.
I'd argue that the second solution is perhaps slightly cleaner to read. I.e. the eye observes that an assignment is being made, and then that there is an increment. Having them both together on the same line makes it slightly less easy to read at a glance. So, I'd prefer solution two.
That said, this is a matter of preference. I don't think one can speak of an established best or better practice here.
In the days when every last ounce of performance mattered, the first version would have been preferred, because the compiler has a higher change of emitting slightly more optimal assembly in the first solution.
Any good compiler will optimize this for you anyway. All are good as long as they are human-readable.
"++" is a leftover from the days of pointer arithmetic -- there are some of us who prefer "+= 1" for integers. But the compiler should manage simple cases like this correctly, regardless.
Modern compilers optimize this kind of code anyway, so in the end it doesn't matter how and where you're incrementing the variable.
From a style perspective, the first version is smaller, and for some easier to read.
From a code comprehension point of view, the second version is easier to understand for beginner developers.
From a performance point of view, ignoring compiler optimizations, this is even faster:
// Version 3
int count = -1;
while(i<<some_value>){
if(to_include[i]==1)
{
to_assign[++count] = from_assign[i];
}
}
It's faster because in theory count++ creates a temporary copy of the value before the increment, while ++count increments and uses the same variable. But again, this kind of premature optimization is not needed any more, since compilers can detect such frequent cases and optimizes the generated code.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Apart from readability, are there any differences in performance or compile-time when a single-line loop / conditional statement is written with and without brakets?
For example, are there any differences between following:
if (a > 10)
a = 0;
and
if (a > 10)
{
a = 0;
}
?
Of course there is no difference in performance. But there is a difference in the possibility of introducing errors:
if (a>10)
a=0;
If somebody extends code and writes later,
if (a>10)
a=0;
printf ("a was reset\n");
This will always be printed because of the missing braces. Some people request that you always use braces to avoid this kind of errors.
Contrary to several answers, there is a finite but negligible performance difference at compile time. There is zero difference of any kind at runtime.
No, there is no difference, the compiler will strip out non-meaningful braces, line-breaks etc.
The compile time will be marginally different, but so marginally that you have already lost far more time reading this answer than you will get back in compile speed. As compute power increases, this cost goes down yet further, but the cost of reducing readability does not.
In short, do what is readable, it makes no useful difference in any other sense.
A machine code does not contain such braces. After compilation, there is no more {}. Use the most readable form.
Well, there is of course no difference between them as such at runtime.
But you should certainly use the 2nd way for the sake of maintainence of your code.
Why I'm saying this is, suppose in future, you need to add some more lines to your if-else block to expand them. Then if you have the first way incorporated in your old code, then you would have to add the braces before adding some new code. Which you won't need to do in 2nd case.
So, it is far easier to add code to the 2nd way in future, than to the 1st one.
Also, if you are using the first way, you are intended to do typing errors, such as semi-colon after your if, like this: -
if (a > 0);
System.out.println("Hello");
So, you can see that your Hello will always get printed. And these errors you can easily remove if you have curly braces attached to your if.
It depends on the rest of the coding guidelines. I don't see any
problem dropping the braces if the opening brace is always on a line
by itself. If the opening brace is at the end of the if line,
however, I find it too easy to overlook when adding to the contents. So
I'd go for either:
if ( a > 10 ) {
a = 0;
}
regardless of the number of lines, or:
if ( a > 10 )
{
// several statements...
}
with:
if ( a > 10 )
a = 0;
when there is just one statement. The important thing, however, is that
all of the code be consistent. If you're working on an existing code
base which uses several different styles, I'd alway use braces in new
code, since you can't count on the code style to ensure that if they
were there, they'd be in a highly visible location.
I would like to know other people's opinion on the following style of writing a for loop:
for (int rep = numberOfReps; rep --> 0 ;) {
// do something that you simply want to repeat numberOfReps times
}
The reason why I invented this style is to distinguish it from the more general case of for loops. I only use this when I need to simply repeat something numberOfReps times and the body of the loop does not use the values of rep and numberofReps in any way.
As far as I know, standard Java for example doesn't have a simple way of saying "just repeat this N times", and that's why I came up with this. I'd even go as far as saying that the body of the loop must not continue or break, unless explicitly documented at the top of the for loop, because as I said the whole purpose is to make the code easier to understand by coming up with a distinct style to express simple repetitions.
The idea is that if what you're doing is not simple (dependency on value of an inreasing/decreasing index, breaks, continues, etc), then use the standard for loop. If what you are doing is simple repetition, on the other hand, then this distinct style communicates that "fact" (once you know the purpose of the style, of course).
I said "fact" because the style can be abused, of course. I'm operating under the assumption that you have competent programmers whose objective is to make their code easier to understand, not harder.
A comment was made that allude to the principle that for should only be used for simple iteration, and while should be used otherwise (e.g. if the loop variables are modified in the body).
If that's the case, then I'm merely extending that principle to say that if it's even simpler than your simple for loops (i.e. you don't even care about the iteration index, or whether it's increasing or decreasing, etc, you just want to repeat doing something N times), then use the winking arrow for loop construct instead.
What a coincidence, Josh Bloch just tweeted the following:
Goes-to Considered Harmful:
public static void main(String[] a) {
int i = 10;
while (i --> 0) /* i goes-to 0 */ {
System.out.println(i);
}
}
Unfortunately no explanation was given, but it seems that at least this pseudo operator has a name. It has also been discussed before on SO: What is the name of this operator: “-->”?
You have the language-agnostic tag, but this question isn't really language agnostic. That pattern would be fine if there wasn't already a well established idiom for doing something n times in your language.
You go on to mention Java, whicha already has a well-established idiom for doing something n times:
for (int i = 0; i < numberOfReps; i++) {
// do something that you simply want to repeat numberOfReps times
}
While your pattern works just as well, it's confusing to others. When I first saw it my thoughts were:
What's that weird arrow?
Why is that line winking at me?
Unless you develop a pattern that has a significant advantage over the standard idiom, it's best to stick with the standard so your fellow coders don't end up scratching their heads.
Nearly every language these days has lambda, so you can write a function like
nTimes(n, body)
that takes an int and a lambda, and more directly communicate intent. In F#, for example
let nTimes(n,f) =
for i in 1..n do f()
nTimes(3, fun() -> printfn "Hello")
or if you prefer extension methods
type System.Int32 with
member this.Times(f) =
for i in 1..this do f()
(3).Times(fun() -> printfn "Hello")