Android Studio / IntelliJ Anonymous Class Formatting - intellij-idea

I was wondering if it is possible to change the auto-formatting in Android Studio in such a way that braces for anonymous classes are placed on the same line while still putting braces for regular classes, methods and blocks on a new line.
Currently, IntelliJ is giving me this result:
class TestClass
{
public void test()
{
FooBar foo = new FooBar(new Runnable() // I want the brace here...
{ // ...not here.
#Override
public void run()
{
//
}
});
}
}
However, I would like the code to be formatted like this:
class TestClass
{
public void test()
{
FooBar foo = new FooBar(new Runnable() { // <- Same Line
#Override
public void run()
{
//
}
});
}
}
Everything is fine, except the one detail that I cannot get the brace to be formatted like in the second example. Is this not possible or did I just overlook the setting?

I've wanted this for a long time now as well, but unfortunately it is not possible in Intellij.
The closest you can come is setting Wrapping and Braces/Braces Placement/In class declaration to "Next line if wrapped" or "End of line" (what I use). This of course modifies the way the brace is wrapped for not only anonymous inner classes (the desired result), but also for top level and inner classes; however, methods/if/else/for/while/do-while/try/catch/finally/switch etc are unaffected.
I really wish IntelliJ would add a Wrapping and Braces/Braces Placement/In anonymous class declaration option like Eclipse has.

Related

Does Intellij have an auto replace feature like Toad?

Does Intellij have an auto replace feature like Toad?
keyboard : ss + spacebar ==> select * from
IntelliJ has live templates.
For example enter the following code and place the cursor inside the curly braces:
public class MyClass {
// put cursor under this line
}
Now type psvm and hit TAB, the following will appear
public class MyClass {
// put cursor under this line
public static void main(String[] args) {
}
}
There are many live templates. The one in this example means "public static void main" (psvm) - you can research them all yourself. Note that many depend on context.
IntelliJ documentation: Live Templates

Apex Test Class

newbie here...thanks for your patience. I'm interested in writing a test class for the following controller, but not sure where to begin:
public class savecontroller
{
private final Emp__c emps;
public savecontroller(ApexPages.StandardController controller)
{
this.emps= (Emp__c)controller.getRecord();
}
public void autosave()
{
upsert emps;
}
}
Thank you
Your code is a little bit strange... From this part:
public savecontroller(ApexPages.StandardController controller)
it looks like your controller is not really a "controller", but more like an extension of a standard controller for Emp__c object. I know, it doesn't affect anythingin your post (except maybe semantics), BUT (!) it does have an affect on how you write your test class. Since this is an extension, test class would look something like this:
#isTest
public class saveconttroller_test {
public static Emp__c test_emp; // declaration
static {
test_emp = new Emp__c();
insert test_emp; //since you have upsert you can leave this out
}
static testMethod void testsavecotroller() {
Test.startTest();
//in the next two lines we contruct standard controller and the extension
ApexPages.StandardController sc = new ApexPages.StandardController(test_emp);
savecontroller ext = new savecontroller(sc);
ext.autosave();
Test.stopTest();
}
}
Now, let me point out a few things... first, as I'm sure you know, test should cover as much code as possible. SF requires 75%, but the closer you get to 100% the better. But (!), you should always include something to assert if your method is doing what it is suppose to be doing. For example in your case, i would change method autosave() like this:
public PageReference autosave()
{
try {
upsert emps;
return new ApexPages.StandardController(test_emp).view();
} catch(Exception e) {
return null;
}
}
By doing so, you can include System.assertEquals(ref1, ref2); in your test class, wher ref1 is reference you would expect (if the upsertion was successful this would be test_emp page reference) and ref2 would be the reference you actually get from the test.
Second thing is using static method in the test. Whatever you write in this method will always execute on Test.startTest(); call.
Hope this helps you! :)
Cheers, G.

How to disable static initializer?

Assuming my system under test looks like this:
public class SysUnderTest {
public int foo() {
Trouble trouble1 = new Trouble();
Trouble trouble2 = new Trouble();
return trouble1.water(1) + trouble2.water(2);
}
}
The test will looks something like
public class DummyTest {
#Tested SysUnderTest sut;
#Mocked Trouble trouble;
#Test
public void testTrouble() {
new Expectations() {{
trouble.water(anyInt); returns(10, 20);
}};
assertThat("mocked result", sut.foo(), is(30));
new FullVerificationsInOrder() {{
Trouble t1 = new Trouble();
Trouble t2 = new Trouble();
t1.water(1);
t2.water(2);
}};
}
}
However, Trouble is actually a 3rd-party lib class that I have no control, which it does static initialization which will fail in testing env.
public class Trouble {
static {
troubleInitialize();
};
public int water(int i) {
return 0;
}
private static void troubleInitialize() {
throw new RuntimeException("Trouble");
}
}
I know I can use MockUp<Trouble> to get rid of the static initializer but I have no idea how to make use of it in case as I want to (in my realistic case) be able to distinguish the two new instances (created in SysUnderTest) and verify their invocations. I have tried different ways but all failed with some reasons
Adding a new MockUp<Trouble>(){#Mock void $clinit(){} }; in #Before/#BeforeClass, and keep #Mocked Trouble trouble;. It seems not working because the mockup action happens after the DummyTest class is loaded, which will load (unmodified) Trouble class which will throw exception during static initialization
Adding the new Mockup in a TestSuite and call the DummyTest in suite, similar problem as 1.
Simply put the behavior of returning 20, 30 in the fake class, and remove usage of Expectations/Verifications but I have no way to verify which instance is called with what parameter.
Is there a better way to solve my problem? Actually I would want to keep using Expectaitons/Verifications, all I want is some way to disable the static initializer during unit test.
Use stubOutClassInitialization to change the mocked class's static init to an empty method when using Mocked.
#Mocked(stubOutClassInitialization=true) Trouble trouble;

How to prevent dead code being optimized by JVM?

public class A
{
public String getText()
{
Marker.start();
...
...
Marker.end();
}
}
public class Marker
{
public static void start()
{
long now = System.currentTimeMillis;
}
public static void end()
{
long now = System.currentTimeMillis;
}
}
I want to use JPDA (Java Platform Debugger Architecture) to detect the occurrence of Marker.start() and Marker.end() from external application. However I think the code may be optimized / eliminated away by JVM. How to prevent dead code being optimized by JVM?
You could for example create a fake int variable somewhere in the class Marker and increment/decrement its value in the start() and end() methods. I don't think any optimizer could remove an instance field from a class even if the value is not used anywhere. After all, someone could always inject new agent code into the JVM and ask for the value. This means calls to start() and stop() shouldn't get optimized out, either.

Composition, I don't quite get this?

Referring to the below link:
http://www.javaworld.com/javaworld/jw-11-1998/jw-11-techniques.html?page=2
The composition approach to code reuse provides stronger encapsulation
than inheritance, because a change to a back-end class needn't break
any code that relies only on the front-end class. For example,
changing the return type of Fruit's peel() method from the previous
example doesn't force a change in Apple's interface and therefore
needn't break Example2's code.
Surely if you change the return type of peel() (see code below) this means getPeelCount() wouldn't be able to return an int any more? Wouldn't you have to change the interface, or get a compiler error otherwise?
class Fruit {
// Return int number of pieces of peel that
// resulted from the peeling activity.
public int peel() {
System.out.println("Peeling is appealing.");
return 1;
}
}
class Apple {
private Fruit fruit = new Fruit();
public int peel() {
return fruit.peel();
}
}
class Example2 {
public static void main(String[] args) {
Apple apple = new Apple();
int pieces = apple.peel();
}
}
With a composition, changing the class Fruit doesn't necessary require you to change Apple, for example, let's change peel to return a double instead :
class Fruit {
// Return String number of pieces of peel that
// resulted from the peeling activity.
public double peel() {
System.out.println("Peeling is appealing.");
return 1.0;
}
}
Now, the class Apple will warn about a lost of precision, but your Example2 class will be just fine, because a composition is more "loose" and a change in a composed element does not break the composing class API. In our case example, just change Apple like so :
class Apple {
private Fruit fruit = new Fruit();
public int peel() {
return (int) fruit.peel();
}
}
Whereas if Apple inherited from Fruit (class Apple extends Fruit), you would not only get an error about an incompatible return type method, but you'd also get a compilation error in Example2.
** Edit **
Lets start this over and give a "real world" example of composition vs inheritance. Note that a composition is not limited to this example and there are more use case where you can use the pattern.
Example 1 : inheritance
An application draw shapes into a canvas. The application does not need to know which shapes it has to draw and the implementation lies in the concrete class inheriting the abstract class or interface. However, the application knows what and how many different concrete shapes it can create, thus adding or removing concrete shapes requires some refactoring in the application.
interface Shape {
public void draw(Graphics g);
}
class Box implement Shape {
...
public void draw(Graphics g) { ... }
}
class Ellipse implements Shape {
...
public void draw(Graphics g) { ... }
}
class ShapeCanvas extends JPanel {
private List<Shape> shapes;
...
protected void paintComponent(Graphics g) {
for (Shape s : shapes) { s.draw(g); }
}
}
Example 2 : Composition
An application is using a native library to process some data. The actual library implementation may or may not be known, and may or may not change in the future. A public interface is thus created and the actual implementation is determined at run-time. For example :
interface DataProcessorAdapter {
...
public Result process(Data data);
}
class DataProcessor {
private DataProcessorAdapter adapter;
public DataProcessor() {
try {
adapter = DataProcessorManager.createAdapter();
} catch (Exception e) {
throw new RuntimeException("Could not load processor adapter");
}
}
public Object process(Object data) {
return adapter.process(data);
}
}
static class DataProcessorManager {
static public DataProcessorAdapter createAdapter() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
String adapterClassName = /* load class name from resource bundle */;
Class<?> adapterClass = Class.forName(adapterClassName);
DataProcessorAdapter adapter = (DataProcessorAdapter) adapterClass.newInstance();
//...
return adapter;
}
}
So, as you can see, the composition may offer some advantage over inheritance in the sense that it allows more flexibility in the code. It allows the application to have a solid API while the underlaying implementation may still change during it's life cycle. Composition can significantly reduce the cost of maintenance if properly used.
For example, when implementing test cases with JUnit for Exemple 2, you may want to use a dummy processor and would setup the DataProcessorManager to return such adapter, while using a "real" adapter (perhaps OS dependent) in production without changing the application source code. Using inheritance, you would most likely hack something up, or perhaps write a lot more initialization test code.
As you can see, compisition and inheritance differ in many aspects and are not preferred over another; each depend on the problem at hand. You could even mix inheritance and composition, for example :
static interface IShape {
public void draw(Graphics g);
}
static class Shape implements IShape {
private IShape shape;
public Shape(Class<? extends IShape> shape) throws InstantiationException, IllegalAccessException {
this.shape = (IShape) shape.newInstance();
}
public void draw(Graphics g) {
System.out.print("Drawing shape : ");
shape.draw(g);
}
}
static class Box implements IShape {
#Override
public void draw(Graphics g) {
System.out.println("Box");
}
}
static class Ellipse implements IShape {
#Override
public void draw(Graphics g) {
System.out.println("Ellipse");
}
}
static public void main(String...args) throws InstantiationException, IllegalAccessException {
IShape box = new Shape(Box.class);
IShape ellipse = new Shape(Ellipse.class);
box.draw(null);
ellipse.draw(null);
}
Granted, this last example is not clean (meaning, avoid it), but it shows how composition can be used.
Bottom line is that both examples, DataProcessor and Shape are "solid" classes, and their API should not change. However, the adapter classes may change and if they do, these changes should only affect their composing container, thus limit the maintenance to only these classes and not the entire application, as opposed to Example 1 where any change require more changes throughout the application. It all depends how flexible your application needs to be.
If you would change Fruit.peel()'s return type, you would have to modify Apple.peel() as well. But you don't have to change Apple's interface.
Remember: The interface are only the method names and their signatures, NOT the implementation.
Say you'd change Fruit.peel() to return a boolean instead of a int. Then, you could still let Apple.peel() return an int. So: The interface of Apple stays the same but Fruit's changed.
If you would have use inheritance, that would not be possible: Since Fruit.peel() now returns a boolean, Apple.peel() has to return an boolean, too. So: All code that uses Apple.peel() has to be changed, too. In the composition example, ONLY Apple.peel()'s code has to be changed.
The key word in the sentence is "interface".
You'll almost always need to change the Apple class in some way to accomodate the new return type of Fruit.peel, but you don't need to change its public interface if you use composition rather than inheritance.
If Apple is a Fruit (ie, inheritance) then any change to the public interface of Fruit necessitates a change to the public interface of Apple too. If Apple has a Fruit (ie, composition) then you get to decide how to accomodate any changes to the Fruit class; you're not forced to change your public interface if you don't want to.
Return type of Fruit.peel() is being changed from int to Peel. This doesn't meant that the return type of Apple.peel() is being forced to change to Peel as well. In case of inheritance, it is forced and any client using Apple has to be changed. In case of composition, Apple.peel() still returns an integer, by calling the Peel.getPeelCount() getter and hence the client need not be changed and hence Apple's interface is not changed ( or being forced to be changed)
Well, in the composition case, Apple.peel()'s implementation needs to be updated, but its method signature can stay the same. And that means the client code (which uses Apple) does not have to be modified, retested, and redeployed.
This is in contrast to inheritance, where a change in Fruit.peel()'s method signature would require changes all way into the client code.