About Coder Croc

Indian, Java Programmer, Music lover

Preflight OPTIONS Request

Modern browsers hit preflight request to make sure if CORS (Cross Origin Resource Sharing) is being followed or not. This request brings details about the service which your client is looking forward to consume.

This detail includes allowed origins, allowed headers, allowed http methods etc. it’s browser’s responsibility to make this request if origin differs. If client is not allowed to access server resource this request will end up in HTTP Status code 401 and actual call will never be triggered by the browser. Worth to note that server has CORS mechanism configured and not client.

Note that it’s all about cross origin so if your server and client both belongs to same origin browser don’t need to make this preflight call.

To understand it more easily let’s take a simple example, you have an application which has client (Web Browser – i.e. AngularJS Application) running on localhost:1234 and server (Web Server – i.e. Java Web Application) is listening to localhost:4321 as these both belongs to different origin (even hosts are same ports differ in this case), when client tries to consume service of server it first fires OPTIONS request,

OPTIONS
localhost:4321/server/some/resource
Access-Control-Request-Method: GET
Access-Control-Request-Headers: origin, x-requested-with, Content-Type
Origin: http://localhost:1234

If CORS has been configured appropriately to allow access to localhost:1234, it will return expected response,

HTTP/1.1 200 OK
Content-Length: 0
Connection: keep-alive
Access-Control-Allow-Origin: https://localhost:1234
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: origin, x-requested-with, Content-Type, Accept

Now, browser will check response including status, Access-Control-* headers etc. to make sure that what localhost:1234 is trying to do with localhost:4321 is allowed by the later one or not. As response is 200 and our client is in allowed origin also method which is going to be used in actual call is allowed.

CORS allow server to control accessibility of it’s resources from different origins. Servers like tomcat by default allow request from cross domains but you can override this setting in your application.

Parse number String of other languages

You can not directly parse number String of language other then English in Java. To parse number String of other language say Hindi you can use following way,

NumberFormat numberFormat = NumberFormat.getInstance(new Locale("hi", "IN"));
try {
    Number number = numberFormat.parse("३५");
    System.out.println(number.intValue());
} catch (ParseException e) {
    e.printStackTrace();
}

If you use above block of code it will print 35 in console.

You can only parse the number for one of the supported locales of Java.

 

 

Does code hurts?

We all programmers have right to implement the code in our own way the only goal is we want it to run as per the requirement. At start I believed that there is nothing like good code or bad code it’s all about working and not working code. But I was wrong, there is such thing like bad smelly code which hurts, hurts you in the eye and hurts service or product for long term.

Let me simply share a very small example of taking wrong decision while writing the code and shipping it without code review which is a most dangerous step actually.

int id = Integer.parseInt(String.valueOf(Long.valueOf(pojo.geLong())));

It will take you a while to understand what above line is trying to do. You may take several minutes to figure out what can be the reason for writing such mysterious line of code.

Some of us will argue that no one can write such code but trust me such people exist on this planet earth. I am not going to blame them only it’s something that was in code since long and none of the people who checked this code tried to fix it.

This line can be fixed easily to avoid the confusion and in reasonable ways as per the code written before this particular line.

How about,

int id = pojo.geLong().intValue();

I might be wrong completely if getLong could return null. Well yes, in that case I would add null check or I’ll make sure that it does not return null for any case.

This line is not a problem who wrote it but for those who are going to understand it in future. I’ve multiple such examples which are really really disturbing and almost all the people in your team will advice you to avoid fixing this as they have fear of raising other problems in the code.

Come on! you can not hide truth for long, it may create problem in future. Good code is one of the standard you have to maintain in your product or service. The time has gone where working program was the only requirement. This is not about optimization but it’s about optimal approach of writing the code.

I’m happy that I usually take steps to fix such things and I may fail but I will get used to with dealing with buggy and smelly code which will help me to grow and I advice you to do the same as well.

Code limit 10.20.300

For any intermediate developer It is comparatively easy to write any block of code as per the requirement or business logic but the things which needs to be targeted first while writing code includes readability, testability and maintainability.

Every new developer might have done a mistake of dumping lot of code in one method or lot of irrelevant code in one class. Some automatic code analysis tools like SonarQube can warn us to reduce method lines up to 30 or reduce lambada expression lines or limit cases in switch block etc.

10-20-300 has following interpretation,

10 : Strictly no more than 10 attributes in any class.
20 : Strictly no more than 20 lines in any method.
300 : Strictly no more than 300 lines in any class.

10-20-300 rule can stop from dumping more code in any class and can ask developer to look for an alternative or it sometimes just sends a signal “time to re-factor”.

To be honest, such things can not be followed too strictly or can not be considered as a rule of thumb. This does not make you write maintainable or readble code but as you limit your code at first place, it will start making difference gradually.

This digits should trigger that you are moving in a way to increase the possibility of creating problem in either maintainability or readability. Because no developer praise the code which is hard to modify and difficult to interpret. This digits are totally based on my experience and does not have any concrete research base. The effectiveness of digits can vary up to some point as per the scenarios or use cases.

Volatile with example

Volatile is ignored or most of the times unknown concept among developers as we never(or hardly) use this keyword while building the programs.

I will try to express it in a simple term with an understandable (at least according to me) example. Before that volatile means (in Java context) liable to change rapidly.

Before volatile, we should understand why we need volatile. You know, each thread has it’s own stack (for optimization) where it can store variable used in it.

Now when variables are used among multiple threads it may be possible that one thread change the value and second would still use the old value which it has in it’s stack. Confusing!? if yes, then consider it like, each thread has it’s own memory to manipulate those variable and for the optimization sake it should not refer to the changes made by other threads.

So, what volatile keyword does ? It enforces “Java Memory Management Mechanism” to ensure that every thread can get a consistent value. Does that makes sense ? Indeed, I guess. But wait! volatile is not similar to synchronization and you can figure out that now.

Please refer to the following example.

class Counter extends Thread {
	
	private volatile long number = 0;
	
	@Override
	public void run() {
		while(number >= 0) {
			number++;
		}
		
		System.out.println("Counter is terminated! Number must be volatile.");
	}

	void terminate() {
		number = -999999999;
	}
}

class Tester extends Thread {

	@Override
	public void run() {
		Counter counter = new Counter();
		counter.start(); 

		try {
			System.out.println("Terminating the counter in 3 Seconds...");
			Thread.sleep(3000);
			counter.terminate();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

public class VolatileDemo extends Thread{

	public static void main(String[] args) {
		Tester tester = new Tester();
		tester.start();
	}
}

We will get following output with volatile

Terminating the counter in 3 Seconds...
Counter is terminated! Number must be volatile.

and following without volatile, (without volatile the program will keep on executing, so better to terminate it forcefully after observing the result for sometime.)

Terminating the counter in 3 Seconds...

To the best of my knowledge, use of volatile is too rare in day to day development. But it’s one of the hot topics in interviews due to it’s behavior.

Do you choose to throw NPE ?

Well, NPE the NullPointerException is quite famous among Java programmers. It has a bad impression although, no one want to see this in console but everyone for sure see this more than once while programming.

The agenda of this blog is whether we should throw NPE explicitly or not. Throwing exception is always better than swallowing it with try-catch and even more empty catch block is the worst thing you could have in your program.

Throwing NPE explicitly is valid, however, if you are getting something null in method parameter than we have another suitable exception which can be much more suitable and that is IllegalArgumentException.

According to the documentation, NPE is about depicting the use of null reference in program which is detected at runtime by JVM. If you could detect whether something is null in your program and want to throw NPE you are not raising it because of illegal use of null reference and actually throwing it before that.

So, we should always throw IllegalArgumentException instead of NPE if possible. I believe you will always go with this exception instead of NPE, but kindly note that throwing NPE is not a bad practice at all. Ultimate goal is to make your system report immediately if anything goes wrong instead of just continuing the execution.

Here better not to create a custom exception for such cases. Because if we already have inbuilt exception than why to create our own, so, don’t reinvent the wheel.

Declare less variables

Almost every java programmer had heard this statement “accomplish this task with less number of variables.” I sometimes think, why do we do this. I am not saying create more number of variables than needed. I am saying what does it make a difference if I complete task with two variables instead of one. Specifically, talking about interviews, almost 80% interviewer check how optimized code interviewee can write. I think that is really important in interview.

But this should not become our bad habit in professional software development. I think we should not sacrifice clarity of code for micro optimizations. Nowadays, we are living in time where we have strong servers and enough memory to handle such extra stuff. Only goal is to write maintainable code and that can be achieved by following three steps.

  1. Correctness
  2. Clarity
  3. Code optimization

Sometimes, developer becomes much more eager to write as optimized code as possible. So, code becomes difficult to maintain and sometimes quite confusing for other developers.

Why developers fail to choose readability is difficult to say. Usually, they directly jump to write code without much thinking about readability and maintainability. Nowadays, developers who write readable code are respected everywhere than those who can do much more complex and difficult task but with messy code. It can be possible to cover this in peer to peer code review. However, more then 50% of the probable bugs or convention related issues can be easily solved by tools like SonarQube, FindBugs etc.

Optimization is important but not the first goal of any real world applications. If you can write easily understandable code, optimization would be less tricky. This is what Donald Knuth said,

Premature optimization is the root of all evil.