The code standard at my work, is to put the "{" on their own line instead of after the arguments of a method. We're using lots of method extraction as we are in a refactoring heavy state.
Unfortunately, auto-extracted methods place the "{" on the wrong line and since no dev notices it every time, our standard isn't so standard anymore. Is there a way to change it? Thanks
I want this
void foo () {
//stuff
}
to be this
void foo ()
{
//stuff
}
In Window > Preferences > Java > Code Style > Formatter, edit your active profile.
Method declaration in the Braces tab allows you to define this behaviour.
Related
I recently upgraded my IDEA and now using IntelliJ IDEA 2022.2 Ultimate Edition.
I found the Complete Current Statement in Scala code behaves differently as in Java code, which is very annoying.
For example in Java code:
public static void main(String[] args) {
String foo = "bar"
}
Press Complete Current Statement shortcut(shift+cmd+enter for me) anywhere in line #2, will add a ; at the end of the line, and an auto-indent will be applied too:
public static void main(String[] args) {
String foo = "bar";
}
Then press Complete Current Statement again will bring you to a new line when there is nothing more to adjust.
public static void main(String[] args) {
String foo = "bar";
}
In previous version of IntelliJ, I roughly remember the behavior is same for Scala code.
But in this version of IntelliJ, when I try to do samething in Scala code, for example:
def foo (): Unit = {
throw new RuntimeException
}
When I press Complete Current Statement in line #2, nothing happens.
Could anyone please help me checkout why or how should I config to align with Java code's behavior? Thank you very much!
You don't need to use that in Scala because semicolons are optional, and almost never used. Actually, your Scala code sample is already what you would call a "complete statement".
For formatting what I do and recommend is having set File -> Settings -> Tools -> Actions on save and check Reformat code and optionally Optimize imports, and it will do both whenever you save your source file using Ctrl + S. I believe it's Cmd + S on your Mac.
This uses the default Intellij Formatter for Scala. Scala also has it's own Formatter called Scalafmt with customizable setups more control of formatting different Scala features based on your preferences. This is located at Settings -> Editor -> Code Style -> Scala.
If for some reason you would still like to use your shortcut key, then the only thing the Complete current statement can do to your Scala code is auto-indenting the current line, which for some reason it doesn't so it seems to be a bug on Intellij's side. But what you can do is replace the Auto-Indent Lines shortcut key to use your Complete current statement shortcut key instead and get the same behavior.
I am trying to clean up our legacy code, and noticed there are many if conditional code that can be merged.
Example -
if (file != null) {
if (file.isFile() || file.isDirectory()) {
/* ... */
}
}
This can be refactored to,
if (file != null && (file.isFile() || file.isDirectory())) {
/* ... */
}
Manually performing this change is a pain. So, I was trying to check on inspection tool and template refactoring in intelliji to help me with this bulk code refactoring.
Could not locate this eclipse IDE too.
Kindly suggest, is there an option in Intelliji/Eclipse for this
In IntelliJ IDEA put the text cursor on the first if keyword, press Alt+Enter and invoke Merge nested 'if's.
You can also use Structural Search & Replace to perform this operation in bulk. Use the following search pattern:
if ($a$) {
if ($b$) {
$statement$;
} else $void$;
} else $void$;
Click Edit Variables... and set the minimum and maximum count of statement to 0,∞. Also set the minimum and maximum count of void to 0,0
Use the following replacement pattern:
if (($a$) && ($b$)) {
$statement$;
}
Note that this replacement will introduce redundant parentheses in some cases to prevent changes the semantics of the code. These can later be removed again by invoking Run Inspection by Name and running the Unnecessary parentheses inspection.
The AutoRefactor Eclipse plug-in can do this for you in batch.
See http://autorefactor.org/html/samples.html and select CollapseIfStatementSample.java. You can do this on a whole file, package, or even project.
There is a refactoring to remove unnecessary parentheses too: SimplifyExpressionSample.java (see e. g. line 144).
I'm using eclipse Neon, but this could be present in previous versions too.
The formatter allows to add a blank line at the beginning of a method body, but it does not allow to do the same for constructors. This snippet is taken directly from the preview code of the formatter editor:
public Example(LinkedList list) {
fList = list;
counter = 0;
}
public void push(Pair p) {
fList.add(p);
++counter;
}
I want the constructor to look the same as the method. I could not find a way to do that in the formatter settings.
(This is not a question about the right way to format code - these are closed as opinion based. This is a question about configuring a tool in an IDE. Please keep the discussion relevant.)
one of the sonar issue that I recently found was that
"Malicious code vulnerability - May expose internal representation by incorporating reference to mutable object"
For example ideally Eclipse should generate setter for date like following
public void setBillDate(Date billDate) {
this.billDate = (Date)billDate.clone();
}
How can I force Eclipse to generate code like this?
Window -> Preferences -> Java -> Code Style -> Code Templates
Enable project specific settings
You'll see "Setter Body", Edit:
${field} = ${param};
The code you need might be written as
try {
${field} = ${param}.getClass().cast( ${param}.clone() );
} catch( CloneNotSupportedException cnse ){
// whatever
}
I admit that I don't know whether there is a template variable for the parameter class. Investigating...
I need to test a webpage via desktop application, I'm trying to use
the selenium IDE, I had sucess to create the test cases, but I'm not
able to execute them on java.
I've been looking for something helpful, but I can't find any help at all.
Thank you
A framework that has been created for just this cause, (it's in Java) can be downloaded here or you can check the project out from github here.
This project was designed to be very simple, yet very effective. This type of framework is a "free version" of my interpretation of a framework that I use every day in production-type environments.
There is a sample test that is enclosed in the project named SampleFunctionalTest.java. Assuming you follow the ReadMe to the T, you should have no problem getting started.
Here is what a test would look like in this framework.
#Config(url = "http://ddavison.github.io/tests/getting-started-with-selenium.htm", browser = Browser.FIREFOX) // You are able to specify a "base url" for your test, from which you will test. You may leave `browser` blank.
public class SampleFunctionalTest extends AutomationTest {
/**
* You are able to fire this test right up and see it in action. Right click the test() method, and click "Run As... jUnit test".
*
* The purpose of this is to show you how you can continue testing, just by taking the semi colon out, and continuing with your test.
*/
#Test
public void test() {
// click / validateAttribute
click(props.get("click"))
.validateAttribute(props.get("click"), "class", "success") // validate that the class indeed added.
// setText / validateText
.setText(By.id("setTextField"), "woot!")
.validateText(By.id("setTextField"), "woot!") // validates that it indeed set.
// check / uncheck
.check(By.id("checkbox"))
.validateChecked(By.id("checkbox")) // validate that it checked
.check(props.get("radio.2")) // remember that props come from <class name>.properties, and are always CSS selectors. (why use anything else, honestly.)
.validateUnchecked(props.get("radio.1")) // since radio 1 was selected by default, check the second one, then validate that the first radio is no longer checked.
// select from dropdowns.
.selectOptionByText(By.xpath("//select[#id='select']"), "Second") // just as a proof of concept that you can select on anything. But don't use xpath!!
.validateText(By.id("select"), "2") // validateText() will actually return the value="" attr of a dropdown, so that's why 2 works but "Second" will not.
.selectOptionByValue(By.cssSelector("select#select"), "3")
.validateText(props.get("select"), "3")
// frames
.switchToFrame("frame") // the id="frame"
.validatePresent(By.cssSelector("div#frame_content"))
// windows
.switchToWindow("Getting Started with Selenium") // switch back to the test window.
.click(By.linkText("Open a new tab / window"))
.waitForWindow("Google") // waits for the url. Can also be the you are expecting. :) (regex enabled too)
.setText(By.name("q"), "google!")
.closeWindow(); // we've closed google, and back on the getting started with selenium page.
}
}
You should create an instance of a WebDriver and call methods on the instance of that object.
An easy example is shown here: http://www.seleniumhq.org/docs/03_webdriver.jsp#introducing-the-selenium-webdriver-api-by-example
I hope you have created the script in webdriver.
Now in the script recorded by the selenium ide you have three methods called
setup, testSomeName and tearDown.
From the very basic: to run this script all you need to do is create a main method in the same class and in that you need to call these methods in the same order as specified above.
After that you just need to run that program.
Here is an example to make it more clear:
public class p_adjcb {
public void setUp() throws Exception {
}
public void testP_adjcb() throws Exception {
}
public void tearDown() throws Exception {
}
public static void main(String[] args) {
p_adjcb obj = new p_adjcb();
try {
obj.setUp();
obj.testP_adjcb();
obj.tearDown();
} catch (Exception ex) {
}
}
}
If you get any compiler error make sure you have downloaded the selenium-standalone-server.jar file and added it to your class path.
This is a very basic start. Later on you may need to use som framework like junit.
Hope it helps.