Should I put if(variable < 10) in own method? [closed] - java

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 have a check in a loop where I have to check if the number of occurrence is less than 10 which could be written as either
if(occ < 10){
}
or
if(checkIfOccurencyIsLessThan10(occ)){
values.add(current+"0"+occ);
}
else{
values.add(current+occ);
}
I'm reading Clean Code a handbook of agile software craftsmanship, where they say a method should do the least amount, and code should be hacked up into more pieces. Is this necessary right here? I'm trying to get a better grasp on how long a method should be, and how much it should be doing.

It depends on if this condition is spread across multiple pieces of code, and if this check could change in the future to include checking additional edge cases. If both of those things are true or could be true, then sure, extracting the check to its own function is wise. However, I would definitely say you should rename the function to not specify the functions implementation, because that defeats the purpose of being able to change out the conditional, right? Naming it something like occurenceNeedsZero is a much more flexible solution. Because if you come up with other use cases that need checking you can add them to this function as well!
However, if your question is "should I always make a simple conditional check such as "is x < 10" into its own function, then I would say no. That would be overengineering, in my opinion. Functions should be used to 1) separate logical portions of code, 2) increase readability, or 3) extract small pieces of code that are spread across multiple locations and likely to change in the future, as it simplifies future refactoring.
There are probably more cases than those 3, but those are the big ones.

It's better to use a static final variable to store this 10, instead hard code.
If there are other places need to check if occ < 10, you need extract it as a method. Otherwise it is unecessary.

Related

If tests are using bdd approach ( Given, when then ) in it's logic should naming be also BDD? [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 1 year ago.
Improve this question
I have a few questions,
first - should naming of the method also follow BDD approach when Given, When, Then is used inside a method?
For example, Given_Preconditions_When_StateUnderTest_Then_ExpectedBehavior or It will be excessive and repeat itself and it's better to use something like methodNameUnderTest_givenCondition_expectedBehavior
as naming?
Second:
Do I need to write comments in tests marking Given, When, Then. Example:
#Test
void findById() {
// GIVEN
Visit visit = new Visit();
given(visitRepository.findById(1L)).willReturn(Optional.of(visit));
// WHEN
Visit foundVisit = service.findById(1L);
// THEN
assertThat(foundVisit).isNotNull();
then(visitRepository).should().findById(anyLong());
}
I personally like having the method name resemble what the method is testing in a bdd approach. So I don't think there are requirements, but it depends on your preference.
I always use a should_when principle, in naming my tests.
shouldFindVisit_whenIdExists
Short and simple, with given_when_then the name could quickly grow big, even though I don't think it is a big problem in tests!
For your second question, I think it depends on your preference again, but I think yes, it always helps seeing where I currently am in my test. And I can structure my test more easily in case I add something to it.
void shouldFindVisit_whenIdExists() {
// given
Visit should = ...;
// when
actual = service.findById(...);
// then
assertThat(actual, is(should));
}
I also always prefix my expected variables with a should, to mark them as what it should expect in the end. And the actual results from the service call in the when section as actual.
The verification in the end then is very clear and simple.

How to find the position of single bit set in a long very fast [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a long with a single bit set and I need to know which it is, e.g. the index. I need to calculate this as fast as possible.
The naive idea is to divide by 2 and check whether the result is 1. But this would need up to 63 iterations (worst case).
My next idea was to make like a binary search, e.g. to look wether it is bit 63-32 or 31-0 then 63 - 48, 47 - 31, 31 - 16, 15 - 0 and so on having many if-else statements, but this gives me hell of a bunch of code...
Furthermore I'd like to minimize object creation and memory used. You might suggest that I'm wrong then with Java and should use perhaps C/C++. Well it's for a school competition and I don't have a choice :)
I'd like to see some sample code!
Use Long.numberOfTrailingZeros - this will be exactly the index you are looking for.
Long.numberOfLeadingZeros can be also useful if you count bits starting from the highest one.
Both methods are JVM intrinsics, i.e. they are treated specially by JIT compiler. These methods are translated to a special CPU instruction (TZCNT / LZCNT) and thus are very efficient.
You could prepare a Map<Int, Int>, holding the number of the set bit for each possible value, but I'm not sure if it is really faster than a loop.
Maybe bit shifting is faster than dividing by 2.

Java - long one line statements vs multiple lines [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 6 years ago.
Improve this question
My question is general. When should I consider splitting a statement to multiple lines?
I'm writing code on my own, and never worked in a team. I always prefer to make my code as compact as it can get.
For instance, instead of writing:
depth = depth - randomNumbers.nextInt(depth) -1;
Expression expA = createRandomExp(depth);
Expression expB = createRandomExp(depth);
SubtractionExpression subExp = new SubtractionExpression(expA,expB);
return subExp;
I will just write:
return new SubtractionExpression(createRandomExp(depth - randomNumbers.nextInt(depth) - 1), createRandomExp(depth - randomNumbers.nextInt(depth) - 1));
The pros as I see it are:
Less lines of code.
No need for declaration of variables.
Cons:
Can be less readable
Some stuff are written multiple times, like: randomNumbers.nextInt(depth) -1
What are the standards in the industry? And what should I consider when writing statements? Some guidelines might help.
I came over this, but it doesn't really answer my question.
Multiple lines make easy to read when another developer needs to read your code, and use comment lines to clarify functions, variables, classes, etc. Also, You may leave the company you work and someone needs to improve your code or there may be a dysfunctionality in your code so in case of those reasons, you should write your code with multiple lines in order to makes it easier to read and understand.
There should not be any standarts to my knowledge but above reasons will be enough to write codes with multiple lines not in a one line.Additionaly, when you get compiler error while writing single line codes, compiler will say "error found in X line" and you may not be able to understand where is the error in that line. However, multiple lines will ease the situation. I suggest you to write multiple lines instead of single line.
It is good practice to not declare one-use variables. I really like aproach, when you use your "(" bracket as "{" bracket, like:
return new SubtractionExpression(
createRandomExp(
depth - randomNumbers.nextInt(depth) - 1
),
createRandomExp(
depth - randomNumbers.nextInt(depth) - 1
)
);

Does using the Random class "unnecessarily complicate" things? [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 7 years ago.
Improve this question
I handed in an assignment recently, for my Computer Science course. In it I used the Random classover the Math.random() method in order to generate random numbers. My lecturer marked me down for this, stating that it was an "unnecessary complication" and that I should avoid importing classes when not absolutely needed.
I've nothing against her for this, and I accept that this is her preferred method that does have it's merits, but I would appreciate the opinion of a wider (perhaps more experienced) group- since Math.random() calls the Random class anyway and (afaik) creates a new Random object each time the method is called, wouldn't it make sense to just cut out the middleman?
Thanks
Math.random() does use Random, but it uses a single instance.
However since Math.random() is equivalent to Random.nextDouble(); which is usually not very useful, it would be foolish to use it instead of the Random class, which has plenty of convenience methods that make your intention clear and bugs less likely, as demonstrated in the following snippet.
int x = (int)(Math.random() * 100); // Without parentheses you'll always get 0
int y = rnd.nextInt(100);
I suspect your lecturer has a strong theoretical knowledge about programming.
I'd argue that your instructor is flat-out wrong. Maintainability should be one of your primary goals, and reproducibility is essential to debugging and maintainability. Math.random() gives you no control over the seeding, and consequently no reproducibility if something weird is noted during testing and debugging.
I would not be surprised if this question became closed for being too subjective.
But anyway -
I would say this depends on the context. Did your 'mistake' of using Random cause bad perfomance, unreadable code, or anything at all? If not, then I think it is fine.
One can nitpick about these kind of things, but in reality - in my opinion at least - there are larger things to worry about than such theoretical problems.

Where to put braces in Java While loop? [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 9 years ago.
Improve this question
I understand that Java ignores indentation and that curly-brace hierarchies are recommended to increase readability of code. I come from Python with decent experience and I am learning Java right now. I am completely new to Java and I don't yet know the "Good Coding Practice" that comes with writing while loops.
Here are 2 ways to create a basic while loop:
while ( booleanCondition = true ) {
// do stuff
}
And the second way:
while (booleanCondition = true )
{
// do stuff
}
I am not one for splitting hairs over the number of lines of code, so the fact that the first loop is one line shorter is irrelevant to me. Personally, I like the second better because the loop is left-justified with only the condition on the top line. However, I don't want to start using this format if it is not recommended for Good Practice. Is the first way to do the while loop more/less recommended? What is the most common format if there is one?
Both works. This is actually based more towards the programmer's preference and style.
The second one is better since the bracket should start right below its name. It would be least confusing if you use nested loops or conditions. Anything nested would go one level inner and you would never make mistake of brackets and code would be perfectly readable.
while (booleanCondition = true )
{
//do stuff
while (booleanCondition = true )
{
//do stuff
}
}
In this you perfectly know which bracket is ending where. Every bracket ends right below it and there are no brackets in between. Simple and elegant style of coding.
Two schools of thought:
1) In 1997 Sun published a set of "Coding Conventions" for Java. They specify pretty much everything you can think of when it comes to writing Java code - indentation, variable naming, etc, etc: http://www.oracle.com/technetwork/java/codeconventions-150003.pdf . Follow those rules.
2) Do it however you'd like, but keep it consistent. There's any number of styles, etc out there (See: http://en.wikipedia.org/wiki/Indent_style) - pick one, use it in all files in a project.
Java conventions prescribe the first method.
7.6 while Statements
A while statement should have the following form:
while (condition) {
statements;
}
This is also the most commonly used one.
But in the end, it's up to yourself. Just keep it consistent within the project.
It depend on the developer , but basically java doc and IDE prefer the 1st option.
Also if the booleanCondition is boolean you dont need to check == with true :
while (booleanCondition) {
// do stuff
}

Categories

Resources