Drawbacks of javac -parameters flag - java-8

I want to try some frameworks features that required names of parameter in runtime, so I need to compile my app with -parameters and it will store the names of parameter in JVM byte code.
Which drawbacks except the size of jar/war exist of this parameter usage?

The addition of parameter names to the class file format is covered by JEP 118, which was delivered in Java 8. There was a little bit of discussion about why inclusion of parameter names was made optional in OpenJDK email threads here and here. Briefly, the stated reasons to make parameter names optional are concerns about class file size, compatibility surface, and exposure of sensitive information.
The issue of compatibility surface deserves some additional discussion. One of the threads linked above says that changing a parameter name is a binary compatible change. This is true, but only in the strict context of the JVM's notion of binary compatibility. That is, changing a parameter name of a method will never change whether or not that method can be linked by the JVM. But the statement doesn't hold for compatibility in general.
Historically, parameter names have been treated like local variable names. (They are, after all, local in scope.) You could change them at will and nothing outside the method will be affected. But if you enable reflective access to parameter names, suddenly you can't change a name without thinking about what other parts of the program might be using it. Worse, there's nothing that can tell you unless you have strict test cases for all uses of parameter names, or you have a really good static analyzer that can find these cases (I'm not aware of one).
The comments linked to a question about using Jackson (a JSON processing library) which has a feature that maps method parameter names to JSON property names. This may be quite convenient, but it also means that if you change a parameter name, JSON binding might break. Worse, if the program is generating JSON structures based on Java method parameter names, then changing a method parameter name might silently change a data format or wire protocol. Clearly, in such an environment, using this feature reliably means that you have to have very good tests, plus comments sprinkled around the code indicating what parameter names mustn't be changed.

The only thing is the size of the .class that will change, since the bytecode will now contain more information:
public class DeleteMe3 {
public static void main(String[] args) {
}
private static void go(String s) {
}
}
For example this will contain information about paramter names like so:
private static void go(java.lang.String);
descriptor: (Ljava/lang/String;)V
flags: ACC_PRIVATE, ACC_STATIC
Code:
stack=0, locals=1, args_size=1
0: return
LineNumberTable:
line 11: 0
MethodParameters:
Name Flags
s
This MethodParameters will simply not be present without -parameters.
There might be frameworks that don't play nice with this. Here is one Spring Data JPA Issue. I know about it because we hit it some time ago and had to upgrade (I have not been faced with any other from there on).

Related

How to check if an object conforms to the schema of an interface in typescript?

I have an interface which has certain properties defined.
For example:
interface Student {
name: string;
dob:string;
age:number;
city:string;
}
I read a JSON file which contains a record in this format and assign it to a variable.
let s1:Student = require('./student.json');
Now, I want to verify if s1 contains all the properties mentioned in interface Student. At runtime this is not validated. Is there any way I can do this?
There is an option of type guards, but that won't serve the purpose here. I do not know which fields would come from the JSON file. I also cannot add a discriminator(No data manipulation);
Without explicitly writing code to do so, this isn't possible in TypeScript. Why? Because once it's gone through the compiler, your code looks like this:
let s1 = require('./student.json');
Everything relating to types gets erased once compilation completes, leaving you with just the pure JavaScript. TypeScript will never emit code to verify that the type checks will actually hold true at runtime - this is explicitly outside of the language's design goals.
So, unfortunately, if you want this functionality you're going to have to write if (s1.name), if (s1.dob), etc.
(That said, it is worth noting that there are third-party projects which aim to add runtime type checking to TypeScript, but they're still experimental and it's doubtful they'll every become part of the actual TypeScript language.)

How to navigate to a page inside another class library in Windows Phone 7?

There are a set of common pages that I want to use in multiple projects. Hence, I want to build a class library with those pages. The problem is I am not able to pass objects using NavigationService.Navigate(new Uri("/Common;component/SomeName.xaml", UriKind.Relative)); method.
I know I can pass querystring. What I would like to know is...
Is there any limit to the number of strings you can pass in the querystring?
Is there any length limitation of the querystring?
Or better still,
Is there a better way of passing objects from an application to the pages inside a different class library?
About the question "is there a better way". In addition to the solution you've mentioned some people like to use the app's state to pass parameters between objects. For example:
PhoneApplicationService.Current.State["parameter"] = param;
var parameter = PhoneApplicationService.Current.State["parameter"];
Another option is to use a shared class. With complex objects I find it often easiest to use a static public member in a class which can be accessed from both of the projects.
Note that if you choose to use the query string navigation, some special characters in the query string may cause problems. If you can't control the content of the data which is passed between the pages, the shared class -solution is probably better for you. For example in one of our applications we're passing a web site's name in the query string. There's situations where those names can contain a '&' -character (like H&M) and if it does, the query string will break.
When navigating, if building the query strings gets cumbersome, you may check out the Caliburn.Micro and the Uribuilder class in it. It allows you to navigate with a rather nice (and fluent) syntax:
navigation.UriFor<CandidateDetailsPageViewModel>()
.WithParam(x => x.CandidateId, candidate.Id)
.Navigate();
After navigation, the TryGetValue-method can be rather useful when parsing the parameters:
String parameter;
NavigationContext.QueryString.TryGetValue("Parameter", out parameter)
More details for NavigationContext.QueryString is available from MSDN.
To answer your questions:
No there is no limit to the number of strings you can pass in a qyerystring
I believe the answer to this may be yes. I believe the standard is to have a url of < 2000 characters
For small items I usually just pass a query string to my pages. For more complex cases I have a shared static Domain class that both libraries reference. Then I can just access this variable statically really easily.

How good idea is it to use code contracts in Visual Studio 2010 Professional (ie. no static checking) for class libraries?

I create class libraries, some which are used by others around the world, and now that I'm starting to use Visual Studio 2010 I'm wondering how good idea it is for me to switch to using code contracts, instead of regular old-style if-statements.
ie. instead of this:
if (fileName == null)
throw new ArgumentNullException("fileName");
use this:
Contract.Requires(fileName != null);
The reason I'm asking is that I know that the static checker is not available to me, so I'm a bit nervous about some assumptions that I make, that the compiler cannot verify. This might lead to the class library not compiling for someone that downloads it, when they have the static checker. This, coupled with the fact that I cannot even reproduce the problem, would make it tiresome to fix, and I would gather that it doesn't speak volumes to the quality of my class library if it seemingly doesn't even compile out of the box.
So I have a few questions:
Is the static checker on by default if you have access to it? Or is there a setting I need to switch on in the class library (and since I don't have the static checker, I won't)
Are my fears unwarranted? Is the above scenario a real problem?
Any advice would be welcome.
Edit: Let me clarify what I mean.
Let's say I have the following method in a class:
public void LogToFile(string fileName, string message)
{
Contracts.Requires(fileName != null);
// log to the file here
}
and then I have this code:
public void Log(string message)
{
var targetProvider = IoC.Resolve<IFileLogTargetProvider>();
var fileName = targetProvider.GetTargetFileName();
LogToFile(fileName, message);
}
Now, here, IoC kicks in, resolves some "random" class, that provides me with a filename. Let's say that for this library, there is no possible way that I can get back a class that won't give me a non-null filename, however, due to the nature of the IoC call, the static analysis is unable to verify this, and thus might assume that a possible value could be null.
Hence, the static analysis might conclude that there is a risk of the LogToFile method being called with a null argument, and thus fail to build.
I understand that I can add assumptions to the code, saying that the compiler should take it as given that the fileName I get back from that method will never be null, but if I don't have the static analyzer (VS2010 Professional), the above code would compile for me, and thus I might leave this as a sleeping bug for someone with Ultimate to find. In other words, there would be no compile-time warning that there might be a problem here, so I might release the library as-is.
So is this a real scenario and problem?
When both your LogToFile and Log methods are part of your library, it is possible that your Log method will not compile, once you turn on the static checker. This of course will also happen when you supply code to others that compile your code using the static checker. However, as far as I know, your client's static checker will not validate the internals of the assembly you ship. It will statically check their own code against the public API of your assembly. So as long as you just ship the DLL, you'd be okay.
Of course there is a change of shipping a library that has a very annoying API for users that actually have the static checker enabled, so I think it is advisable to only ship your library with the contract definitions, if you tested the usability of the API both with and without the static checker.
Please be warned about changing the existing if (cond) throw ex calls to Contracts.Requires(cond) calls for public API calls that you have already shipped in a previous release. Note that the Requires method throws a different exception (a RequiresViolationException if I recall correctly) than what you'd normally throw (a ArgumentException). In that situation, use the Contract.Requires overload. This way your API interface stays unchanged.
First, the static checker is really (as I understand it) only available in the ultimate/academic editions - so unless everyone in your organization uses it they may not be warned if they are potentially violating an invariant.
Second, while the static analysis is impressive it cannot always find all paths that may lead to violation of the invariant. However, the good news here is that the Requires contract is retained at runtime - it is processed in an IL-transformation step - so the check exists at both compile time and runtime. In this way it is equivalent (but superior) to a regular if() check.
You can read more about the runtime rewriting that code contract compilation performs here, you can also read the detailed manual here.
EDIT: Based on what I can glean from the manual, I suspect the situation you describe is indeed possible. However, I thought that these would be warninings rather than compilation errors - and you can suppress them using System.Diagnostics.CodeAnalysis.SuppressMessage(). Consumers of your code who have the static verifier can also mark specific cases to be ignored - but that could certainly be inconvenient if there are a lot of them. I will try to find some time later today to put together a definitive test of your scenario (I don't have access to the static verifier at the moment).
There's an excellent blog here that is almost exclusively dedicated to code contracts which (if you haven't yet seen) may have some content that interests you.
No; the static analyzer will never prevent compilation from succeeding (unless it crashes!).
The static analyzer will warn you about unproven pre-/post-conditions, but doesn't stop compilation.

BDD/TDD: can dependencies be a behavior?

I've been told not to use implementation details. A dependency seems like an implementation detail. However I could phrase it also as a behavior.
Example: A LinkList depends on a storage engine to store its links (eg LinkStorageInterface). The constructor needs to be passed an instance of an implemented LinkStorageInterface to do its job.
I can't say 'shouldUseLinkStorage'. But maybe I can say 'shouldStoreLinksInStorage'.
What is correct to 'test' in this case? Should I test that it stores links in a store (behavior) or don't test this at all?
The dependency itself is not an expected behavior, but the actions called on the dependency most certainly are. You should test the stuff you (the caller) know about, and avoid testing the stuff that requires you to have intimate knowledge of the inner workings of the SUT.
Expanding your example a little, lets imagine that our LinkStorageInterface has the following definition (Pseudo-Code):
Interface LinkStorageInterface
void WriteListToPersistentMedium(LinkList list)
End Interface
Now, since you (the caller) are providing the concrete implementation for that interface it is perfectly reasonable for you to test that WriteListToPersistentMedium() gets called when you invoke the Save() method on your LinkList.
A test might look like this, again using pseudo-code:
void ShouldSaveLinkListToPersistentMedium()
define da = new MockLinkListStorage()
define list = new LinkList(da)
list.Save()
Assert.Method(da.WriteListToPersistentMedium).WasCalledWith(list)
end method
You have tested expected behavior without testing implementation specific details of either your SUT, or your mock. What you want to avoid testing (mostly) are things like:
Order in which methods were called
Making a method, or property public just so you can check it
Anything that does not directly involve the expected behavior you are testing
Again, a dependency is something that you as the consumer of the class are providing, so you expect it to be used. Otherwise there is no point in having that dependency in the first place.
LinkStorageInterface is not an implementation detail - its name suggests an interface to to an engine. In which case the name shouldUseLinkStorage has more value than shouldStoreLinksInStorage.
That's my 2 pennies worth!

C# 3.0 Autoproperties - whats the difference?

0 What's the difference between the following?
public class MyClass
{
public bool MyProperty;
}
public class MyClass
{
public bool MyProperty { get; set; }
}
Is it just semantics?
Fields and properties have many differences other than semantic.
Properties can be overridden to provide different implementations in descendants.
Properties can help alleviate versioning problems. I.e. Changing a field to a property in a library requires a recompile of anything depending on that library.
Properties can have different accessibility for the getter and setter.
"Just semantics" always seems like a contradiction in terms to me. Yes, it changes the meaning of the code. No, that's not something I'd use the word "just" about.
The first class has a public field. The second class has a public property, backed by a private field. They're not the same thing:
If you later change the implementation of the property, you maintain binary compatibility. If you change the field to a property, you lose both binary and source compatibility.
Fields aren't seen by data-binding; properties are
Field access can't be breakpointed in managed code (AFAIK)
Exposing a field exposes the implementation of your type - exposing a property just talks about the contract of your type.
See my article about the goodness of properties for slightly more detail on this.
In that case, yes it is mostly semantics. It makes a difference for reflection and so forth.
However, if you want to make a change so that when MyProperty is set you fire an event for example you can easily modify the latter to do that. The former you can't. You can also specify the latter in an interface.
As there is so little difference but several potential advantages to going down the property route, I figure that you should always go down the property route.
The first one is just a public field, the second one is a so-called automatic property. Automatic properties are changed to regular properties with a backing field by the C# compiler.
Public fields and properties are equal in C# syntax, but they are different in IL (read this on a German forum recently, can't give you the source, sorry).
Matthias
The biggest difference is that you can add access modifiers to properties, for example like this
public class MyClass
{
public bool MyProperty { get; protected set; }
}
For access to the CLR fields and properties are different too. So if you have a field and you want to change it to a property later (for example when you want to add code to the setter) the interface will change, you will need to recompile all code accessing that field. With an Autoproperty you don't have this problem.
I am assuming you are not writing code that will be called by 3rd party developers that can’t recompile their code when you change your code. (E.g. that you don’t work for Microsoft writing the .Net framework it’s self, or DevExpress writing a control toolkip). Remember that Microsoft’s .NET framework coding standard is for the people writing the framework and tries to avoid a lot of problems that are not even issues if you are not writing a framework for use of 3rd party developers.
The 2nd case the defined a propriety, the only true advantage of doing is that that data binding does not work with fields. There is however a big political advantage in using proprieties, you get a lot less invalid complaints from other developers that look at your code.
All the other advantages for proprieties (that are well explained in the other answers to your questions) are not of interest to you at present, as any programmer using your code can change the field to a propriety later if need be and just recompile your solution.
However you are not likely to get stacked for using proprieties, so you make as well always use public proprieties rather the fields.

Resources