Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Impact of having methods inside if Condition  RSS feed

 
Vineeth Menon
Ranch Hand
Posts: 79
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've got a method which returns a String based on the first character of the method input. E.G.

If I pass the above method in an if condition, E.G.


Now I know this piece of code would work, but is it a correct way of coding in Java? Are there any performance losses/gains? Just because it works, it does not mean it's right. I want to know if it is the correct way to code. Any help on this would be appreciated.

PS: I've asked this question in Code and Stack overflow and got heavily downvoted http://codereview.stackexchange.com/questions/127845/impact-of-having-methods-inside-if-condition . If someone can help me it would be great.
 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why use Strings for the data? How many different trip categories do you have? Can you create an enumerated type with those trip categories in? You can pass the type around. You can also attach those enum elements to each trip object. You can add information about the trips to the enum elements; remember enum elements are full‑blown objects and can have methods and fields. You would usually make an enum element immutable and they are implicitly singletons.

Did you know you can use enum elements and Strings after case in a switch statement? You can also use the charAt(0) in a switch statement.
 
Zachary Griggs
Ranch Hand
Posts: 83
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is perfectly acceptable code. As long as you don't need to do that again later on in the method, then you could refactor it into a local boolean variable so that you only have one method call.

(That is, putting a method in the condition is acceptable - not mentioning anything about this specific method and whether it should be improved.)
 
Vineeth Menon
Ranch Hand
Posts: 79
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@Campbell: Have not looked into Enum's much. Going to look into the link you have provided.
@Zachary: Thank you for your comments.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!