JavaDoc warn of possible NullPointerException - nullpointerexception

I've written a method that returns the most likely LAN Interface on Android. Since the user may not be connected to a LAN, it's possible for this method to return null. How should I warn callers about this possibility in the JavaDoc? I don't think I should use #throws since the method doesn't actually throw a NullPointerException.

I think the right way to do this would be in the return clause:
/**
* ...
* #return {#code null} if the user is not connected to a LAN, else the most
* likely LAN interface.
*/
public LanInterface getMostLikelyInterface();
It would be the responsibility of the caller to know that this means not to use the returned value before a check.
Though you could use Guavas' Optional class instead:
/**
* ...
* #return Optional.absent if the user is not connected to a Lan interface,
* else the most likely one.
*/
public Optional<LanInterface> getMostLikelyInterface();
The users then would have to use if(iface.isPresent()), which is much more readable than if(iface != null).

Related

How do I reference a secondary constructor in KDoc?

I have a Kotlin class with a secondary constructor, that is supposed to be used in a certain scenario. Now this should be properly documented from the first constructor so you can see it right away.
/**
* This is my class.
*
* #constructor This is the primary constructor meant for Scenario A.
* If you are in Scenario B, please use [reference to secondary constructor] <- what do I put in here?
*/
class MyClass(val a: String) {
constructor(b: Int) : this("$b abc")
}
I have not the slightest idea what to put in the square brackets that are meant for referencing members/functions, but I feel it should be possible.
Would be great if somebody knows more about this 🙏

Polymorphic return type depending on the state of a result

I've the following method:
attemptToGetToken(TokenRequestAttempt attempt);
I use a third party component to get the token but it may fail in some case (in the attempt is not valid or missing parameters).
There is no reason to throw an Exception for this case because it is actually expected to fail.
However, depending on the result, the end-user may acts accordingly.
It means I need to return an Object which allows the user to decide what it can/should do.
The probably most obvious answer would be to simply have such class:
class AttemptResult {
constructor(status, token, errorMessage);
getStatus();
getToken();
getErrorMessage();
isSuccessful();
}
And simply return this object properly populated (I may add specific factory method for success/fail state, but it would be just a tool).
The problem I have with this approach is that the contract is not clear.
In the case of failure, the token would be null but the developper would then have to use the isSuccessful() method to check wether or not the attempt succeed.
But nothing will prevent him to call getToken() and get a null result which may bubble an error somewhere.
So I'm wondering if it wouldn't be better to actually return two kind of object.
interface TokenAttemptResult {}
class FailedTokenAttempt implements TokenAttemptResult {
getError();
}
class SuccessfulTokenAttempt implements TokenAttemptResult {
getToken();
}
Because I implement an empty interface to define a relationship between the both result, I may now use this interface as a return type in my service:
TokenAttemptResult attemptToGetToken(TokenRequestAttempt attempt);
When an user calls the method above, he is in charge to check the return type and act accordingly, it prevents him to call method which should not be supposed to be called and may generate side effects.
What do you think about this kind of design?
Any of you has experimented with it and has any feedbacks?
Please avoid unconstructive answer involving personal preferences without actual arguments, I'm really looking for serious design theories.
Thanks!
The subclassing approach will work, however since interfaces are open, the client has no way of being sure that they have exhaustively checked all possible implementing types of the interface. The OO approach to closing the possible cases is the visitor pattern e.g.
public interface TokenResultVisitor<TResult> {
TResult Visit(FailedTokenAttempt failure);
TResult Visit(SuccessfulTokenAttempt success);
}
and then
interface TokenAttemptResult {
T Accept<T>(TokenResultVisitor visitor);
}
This is a fairly heavyweight approach if you only have two possible cases, so if your language supports first-class functions you can simply define a method which takes two handlers e.g.
interface TokenAttemptResult {
T Handle<T>(success: Result => T, failure: TokenError => T);
}

Symfony2 - Entity and Relationship Annotation

This is classic method for the entity relationship;
/**
* #ORM\OneToMany(targetEntity="Product", mappedBy="category")
*/
protected $products;
and other entity;
/**
* #ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* #ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
But, when I use this method, I can't use limit function. All results are taken. But, I should use sql limit function. So, I use a repository class. I wrote all sql code again. I used join function again. Is the relationsip annotation necessary in this situation? Do I still need to add this annotation?
Unfortunately, there is no way of doing what are you asking. You are gonna have to write a custom DQL, preferably inside a custom repository in order to fetch exactly what you want. Of course you still need the annotation itself, as is required by Doctrine to do many things under the hood and, in general, to keep a good relationship model between your entities.
The most close annotation you have to control the way in which relationships are joined when using automatic method is the OrderBy one:
/*
* #OneToMany(...)
* #OrderBy({"name" = "ASC"})
*/
protected $relation;

Aren't entity definitions for ORM error prone?

I'm using Doctrine ORM in a project that I am working on. Although the idea of providing an object interface to the db is nice, I have a question about the implementation of the entity classes.
Let's consider this example of a User entity:
<?php
/**
* #Entity #Table(name="users")
**/
class User
{
/**
* #Id #GeneratedValue #Column(type="integer")
* #var int
**/
protected $id;
/**
* #Column(type="string")
* #var string
**/
protected $name;
/**
* #OneToMany(targetEntity="Bug", mappedBy="reporter")
* #var Bug[]
**/
protected $reportedBugs = null;
/**
* #OneToMany(targetEntity="Bug", mappedBy="engineer")
* #var Bug[]
**/
protected $assignedBugs = null;
// .. (other code)
}
Now, its all fine and dandy, but I was wondering what would happen if I make a spelling mistake in one of the comments e.g. I write:
#Table(name="users)
instead of
#Table(name="users")
the IDE will not complain since its a comment, and I'll only get an error when I run the "generate entities" command (that does the magic in the background of generating code, creating tables, columns and relationships).
So my question is: Aren't entity definitions for ORM error prone? since there really is no check on the syntax if its valid, and errors are generated only at 'generate' time. Is there a way to automate / check for mistakes earlier on while development?
Thanks!
IMO, The issue that you highlighted can be compared to using wrong variables in PHP ($var1 instead of $var2). For that matter, in all dynamic languages.
But you can avoid the problem highlighted by you, if you write unit tests.

best practice for return value in WCF services

I have a WCF service sitting in the cloud.
And my application makes several calls to this WCF service.
Is it a best practise:
1] to always use return value as bool which indicates if the operation was sucessful or not.
2] returning the values you meant to return as the OUT parameters
I would:
return an atomic value (bool, string, int) if appropriate
return a complex type (a class instance) if I need to return more than one value - make sure to mark that class with [DataContract] and its properties with [DataMember]
a SOAP fault FaultException<T> when an error occurs; the <T> part allows you to define your own custom error classes, and again - don't forget to mark them with [DataContract] / [DataMember] and declare them as FaultContract on your operations
1] to always use return value as bool which indicates if the operation was sucessful or not
Yes, if the operation isn´t time consuming AND the return status is always relevant:
Waiting on a return value can affect both client and service host(server) performance/scalability. Ex. in a Request-Responsecall, Requests can keep connections open for a long preriod of time waiting for operation completion. You could implement in a way similar to "HTTP 202 Accepted" status code usage(i.e operation received arguments and has started(patially), but does wait for the completion)
No, if the operation logic only makes sense if synchronous.
No, if you are keen on refactorability/maintainability ex. when you want to return include an error message/code in the return.
2] returning the values you meant to return as the OUT parameters
Yes, this makes the service operation more wsdl compliant and easy to read.