Another quick addition to my Java Tips series. This instance deals again with adding some safety while reducing a bit of code clutter.
Advice
Use Commons ObjectUtils.toString() instead of directly calling toString() on an object if it may be null. This also allows for a alternate result if the object is null.
Code-Example
Before
final String projectId = (request.getParameter("projectid") != null) ? request.getParameter("projectid").toString() : "";
final String roleId = (request.getParameter("roleid") != null) ? request.getParameter("roleid")
.toString() : "DEFAULT";
After
final String projectId = ObjectUtils.toString(request.getParameter("projectid"));
final String roleId = ObjectUtils.toString(request.getParameter("roleid"), "DEFAULT");
Benefit
Readability gain. Safety gain, as ObjectUtils methods are null-safe. The reduced code footprint eases recognition of the intention, which is even more significant if there should be a default text if the object instance is indeed null.
Remarks
None.