java getting concept of OOP right - java

hi guys I already searched a lot but weren't really satisfied with what I found. hope it's the right place to ask this question.
I'm doing Java now for a small amount of time (changed from C) and have problems of getting a grip of how to structure my code best for OOP.
let's give a simple example:
If I'm using some predefined strings (let's say e.g. filepaths or error messages) I'm currently creating an own class doing something like:
private static final String libPath = "\\this\\is\\a\\path\\";
private static final String notFoundMessage = "This hasn't been found";
public static String getLibPath() {
return libPath;
}
public static final String getNotFoundMessage() {
return notFoundMessage;
}
...
Would it be better to create a Map, add everything to it and get it by key?
Or am I doing it completely wrong?
Second example:
let's say I return an error string somewhere
public String getSomething() {
if (something != null) {
return something;
} else {
//handle error, return string below
}
return "I HAVE AN ERROR";
}
And anywhere else in my program I'm checking for the return value:
if (!string.equals("I HAVE AN ERROR")) {
//do something
}
else {
// handle error
}
that's obviously a bad way having to change the code twice once the error message changes. and yeah, I could define the error string the same way I'm doing it in the first example but as I'm not satisfied with that one either I'm reaching a dead end.
would be glad to hear some of your suggestions how to properly do OOP !

First example :
private static final String libPath = "\\this\\is\\a\\path\\";
private static final String notFoundMessage = "This hasn't been found";
public static String getLibPath() {
return libPath;
}
public static final String getNotFoundMessage() {
return notFoundMessage;
}
...
In this case, no need to create a Map. That is the right way to do it. Just note that the libPath would be better defined like this :
private static final Path libPath = Paths.get("this", "is", "a", "path");
(The class Path exists since Java 7, current version is Java 8)
Second example:
public String getSomething() {
if (something != null) {
return something;
} else {
//handle error, return string below
}
return "I HAVE AN ERROR";
}
No : Never return error codes in Java. Prefer using an exception.
Example :
public class ElementNotFoundException extends Exception {
...
}
public String getSomething() {
if (something == null) {
throw new ElementNotFoundException();
} else {
return something;
}
}
Then, you handle the exception like this :
try {
myObject.getSomething();
} catch(ElementNotFoundException e) {
//handle error
}

For the first example, take a look at Internationalization: http://docs.oracle.com/javase/tutorial/i18n/
You can use statics or maps, but sooner or later you will need to show the messages in several languages.
For the second example, it's better to use Exceptions as they are intended to be used when an abnormal condition (like an error) happens.
Anyway, with Exceptions take care not to use it as flow control structures: Why not use exceptions as regular flow of control?

Here are some examples for handling constants throug out your code:
1. Class
public final class MyConstants {
public static final int ERROR_CODE = -1;
}
if (getSomething() == MyConstants.ERROR_CODE) {
// ...
}
2. Interface
public interface MyConstantsHolder {
int ERROR_CODE = -1;
}
public MyClass implements MyConstantsHolder {
public void myMethod() {
if (getSomething() == ERROR_CODE) {
// ...
}
}
}

Related

How to write nested for loops in methodes (clean code)

Clean code means for me: only one task for each methode and no nested loops.
When I got the following code, I asked myself, how can I avoid nested for loops and encapsulate them in methods.
private String getUser(){
for (FieldConfigScheme context : getConfigurationSchemes()) {
for (Option option : getOptions(context)) {
for (Group group : getGroups()) {
if (option.getValue().equalsIgnoreCase(group.getName())) {
return group.getUser();
}
}
}
}
return "default";
}
My first solution was the following. The problem here is, the for loops are running until the end and do not break (return) when the value is found and set.
private String user = "default";
private String getUser(){
for (FieldConfigScheme context : getConfigurationSchemes()) {
processOptions(context);
}
return this.user;
}
private void processOptions(FieldConfigScheme context){
for (Option option : getOptions(context)) {
processGroups(option);
}
}
private void processGroups(Option option){
for (Group group : getGroups()) {
setUser(option, group);
}
}
private void setUser(Option option, Group group){
if (option.getValue().equalsIgnoreCase(group.getName())) {
this.user = group.getUser();
}
}
so I wrote this code, which should be the same like the first:
private String user = "default";
private boolean isUserSet = false;
private String getUser(){
for (FieldConfigScheme context : getConfigurationSchemes()) {
if(!isUserSet) processOptions(context);
else return this.user;
}
return this.user;
}
private void processOptions(FieldConfigScheme context){
for (Option option : getOptions(context)) {
if(!isUserSet) processGroups(option);
else return;
}
}
private void processGroups(Option option){
for (Group group : getGroups()) {
if(!isUserSet) setUser(option, group);
else return;
}
}
private void setUser(Option option, Group group){
if (option.getValue().equalsIgnoreCase(group.getName())) {
this.user = group.getUser();
isUserSet = true;
}
}
But then I asked myself, is this really better code? Is this more clean code? Yes, every method is only doing one thing. And yes, the code is better to read in my opinion. But from originally 12 lines compact code I now got 30 lines of code and one member variable more in the code. So is the first originally code better because it's more compact even with nested for loops?
What do you think? Which one is better? Or how can I write the code better?
Thanks in advance for your answers!
Instead of returning void, why not boolean?
private String getUser(){
for (FieldConfigScheme context : getConfigurationSchemes()) {
if (processOptions(context)) {
break;
}
}
return this.user;
}
private boolean processOptions(FieldConfigScheme context){
for (Option option : getOptions(context)) {
if (processGroups(option)) {
return true;
}
}
return false;
}
private boolean processGroups(Option option){
for (Group group : getGroups()) {
if (option.getValue().equalsIgnoreCase(group.getName())) {
this.user = group.getUser();
return true;
}
}
return false;
}
T.B.H. I prefer the nested loops method. It looks clean, there is nothing more going on in the loop than to simply find something in a hierarchy and this is perfectly fine.
The use of extra function in this case is just bad. Imagine having to debug this code now, rather than focusing on one method which is doing this, you will have to look at all the extra ones you made.
Also this method doesn't seem to take any parameters which suggests that it actually only needs to do this check once and the rest of the time it should just return the same value. That just a guess, but if that was the case, then it makes your efforts to make it cleaner all the more unnecessary.

Array Of Methods That Return A String

I'm creating a kind of data testing program, and one specific part is giving me a huge amount of trouble. In my main method class there is one section where I need to send over a String of data as a parameter in a method to my methods class (let's call it ValidatorClass) and the idea being that the method will then return any validation errors or if there are none simply an empty String.
This would be fine except that I use "for loops" when going through my data to validate as doing it without is just too clunky. I tried to research about arrays of methods and found plenty of useful things that work with void methods but found nothing on any methods that return variables.
In a nutshell I'm asking: Is it possible to create an array of methods (or implement an array of objects to simulate an array of methods) that return a variable?
Here is some example code, but in the actual program the method's return would actually be used further on:
public class Validation{
public static void main(String args){
ValidatorClass valTest = new ValidatorClass();
String[] dataList = {"Andrew", "Jameson", "Male"}
for(int i = 0; i < dataList.length; i++){
String errors = valTest.testInput(dataList[i], i).validationList[i];
System.out.println(errors);
}
}
}
And in ValidatorClass:
public class ValidatorClass{
public String testInput(String data, int index){
//Tests the data by calling method "index" which corresponds to data type.
//ie. validateName would be index : 1, validateSurname index : 2 etc
String errors = validationMethodList[index](data); //Somehow add data as a parameter to it
return errors;
}
public String validateName(String name){
String errors = "";
if(name.length < 1){
errors += "Name Not Entered";
}
return errors;
}
public String validateSurname(String surname){
String errors = "";
if(surname.length < 1){
errors += "Surame Not Entered";
}
return errors;
}
public String validateGender(String gender){
String errors = "";
if(!gender.equalsIgnoreCase("male") || !gender.equalsIngoreCase("female")){
errors += "Invalid Gender";
}
return errors;
}
}
I imagine that you have something like...
static String validate1(Validatible v) { /* do something */ }
static String validate2(Validatible v) { /* do something else */ }
static String validate3(Validatible v) { /* do something still else */ }
And that you want to execute, in some method...
Validatible v = getValidatible();
System.out.println(validate1(v));
System.out.println(validate2(v));
System.out.println(validate3(v));
Then perhaps you could write an interface:
public interface Validator {
String validate(Validatible v);
}
...and keep them in an array or a list...
private static final List<Validator> validators = Arrays.asList(
new Validator() {
#Override
public String validate() {
/* do something */
}
},
new Validator() {
#Override
public String validate() {
/* do something else */
}
},
new Validator() {
#Override
public String validate() {
/* do something still else */
}
}
);
// Can be written more compactly if in Java 8.
Thereafter, you can call the methods in a for-loop:
Validatible v = getValidatible();
for(Validator validator : validators) {
System.out.println(validator.validate(v));
}
Possible improvements would include using a StringBuilder to build a single String (or using the Stream API and using Collectors.joining) if this fits your purpose better.

Improve code with several booleans conditions java

I got a big problem to deal with, my code is too long and full characters. I removed a lot, using methods and using some proper design patterns... But it is still too "crowded".
I get a string from the user, a question like:
"How are you Josh?"
"Who is Josh's mother?"
I need to analyze that question so see it's content and to System.out.print() the answer.
so a long serie of "if/else if" starts e.g
if (question.startsWith("How") && question.endsWith("Josh?"))
{
//do a lot of things here.
System.out.print(actualHealth);
}
else if (question.startsWith("Who") && question.endsWith("mother?"))
{
//do a lot of things here.
System.out.print(getParents().getMother());
}
*
*
* //Lot of "else if" here to recognize the question meaning.
*
*
else
{
System.out.print("question not recognized");
}
I called this class AnswersFactory as referred to the Design Pattern "Factory Pattern" because the question, is "asked" in another class. But I suppose it's a wrong way to consider it a design pattern.
How to simplify all those conditions even if they seem impossible to simplify, or at least make the code seem more organized? Is there a good design pattern to follow?
My code works great but is not beautiful to see. I hope you understand that frustration!
Thank you.
Not sure why you want to check the question based on the keyword, it has some drawbacks like mentioned by HCBPshenanigans
But to change it to be more flexible, I would do something like this:
An interface for all question handlers
public interface IQuestionHandler
{
bool CanHandle(string question);
void Handle(string question);
}
Concrete class for each scenario. Each class will tell whether it can handle the question or not, and contain logic to handle the question:
public class HealthQuestionHandler : IQuestionHandler
{
public bool CanHandle(string question)
{
return question.StartsWith("How") && question.EndsWith("Josh?");
}
public void Handle(string question)
{
//Replace by actual processing
string healthStatus = "I'm fine";
Console.WriteLine(healthStatus);
}
}
public class MotherQuestionHandler : IQuestionHandler
{
public bool CanHandle(string question)
{
return question.StartsWith("Who") && question.EndsWith("mother?");
}
public void Handle(string question)
{
//Replace by actual processing
string mother = "...";
Console.WriteLine(mother);
}
}
And finally a question handler processor to manage all the handlers. It will register all available handlers in constructor. When called to process, it goes through all of available handlers, ask one by one which one can handle the question
public class QuestionHandlerProcessor
{
private List<IQuestionHandler> _handlers;
public QuestionHandlerProcessor()
{
//Register available handlers
_handlers = new List<IQuestionHandler>
{
new HealthQuestionHandler(),
new MotherQuestionHandler()
};
}
public void Process(string question)
{
foreach(var handler in _handlers)
{
if(handler.CanHandle(question))
{
handler.Handle(question);
return;
}
}
Console.WriteLine("Question not recognized");
}
}
Usage:
QuestionHandlerProcessor processor = new QuestionHandlerProcessor();
processor.Process("How are you Josh?");
processor.Process("Who is Josh's mother?");
Although my answer is in C#, but should not be difficult to convert to Java.
you can use Chain Of Responsibility pattern. you will need catching the exception
UnhandledQuestionException
.
public abstract class QuestionHandler {
protected QuestionHandler successor;
public void setSuccessor(QuestionHandler successor) {
this.successor = successor;
}
public abstract void handle(String question);
}
and implementors should be so
public class HealthQuestionHandler extends QuestionHandler {
private bool canHandle(String question) {
return question.startsWith("How") && question.endsWith("Josh");
}
public void handle(String question) {
if( canHandle(question) ) {
String healthStatus = "I am fine";
System.out.println(healthStatus);
} else {
super.successor.handle(question);
}
}
}
public class MotherQuestionHandler extends QuestionHandler {
private bool canHandle(String question) {
return question.startsWith("Who") && question.endsWith("Mother");
}
public void handle(String question) {
if( canHandle(question) ) {
String mother = "..."; //name
System.out.println(mother);
} else {
super.successor.handle(question);
}
}
}
the final handler, when question cannot be handled:
public class UnhandledQuestionHandler extends QuestionHandler {
public void handle(String question) {
throw new UnhandledQuestionException("question not recognized");
}
}
you should create
UnhandledQuestionException
first, that extends Exception class.
you should create QuestionHandlerFactory too.
public class QuestionHandlerFactory {
public static QuestionHandler create() {
//if you can have several variants of this handler combinations, this method shouldn't be static
QuestionHandler healthQuestionHandler = new HealthQuestionHandler();
QuestionHandler motherQuestionHandler = new MotherQuestionHandler();
QuestionHandler unhandledQuestionHandler = new UnhandledQuestionHandler()'
motherQuestionHandler.setSuccessor(unhandledQuestionHandler);
healthQuestionHandler.setSuccessor(motherQuestionHandler);
return healthQuestionHandler;
}
}
and in the user of this class will be:
QuestionHandler handler = QuestionHandlerFactory.create();
try {
handler.handle(question);
} catch( UnhandledQuestionException ex ) {
System.out.println(ex.getMessage());
}
create an enum for your Constants such "WHO","HOW", .... and WHERE" then try to use switch after that
you can create enum in the same class
You can use Factory pattern and a strategy pattern. Since Qestion is being asked in a different class (let's call it QueryResolver ) it should look like this :
class QueryProcessor
{
private IQueryResolver _ resolver;
//We will be injecting our dependencies in the constructor (Dependency Inversion)
public QueryProcessor(IQueryResolver resolver )
{
_resolver = resolver;
}
public string ProcessQuery()
{
_resolver.ResolveQuery();
}
Now your QueryResolver Implements the IQueryResolver interface
public interface IQueryResover
{
string ResolveQuery();
}
And you will have multiple implementation of IQueryResolver each responsible for a particular kind of Query e.g.:
//This particular implementation know how to resolve question including the "Who" key word.
class WhoQueryResolver : IQueryResolver
{
private string _question;
public WhoQueryResolver(string question)
{
_question = question;
}
public string ResolveQuery()
{
//do a lot of things here.
System.out.print(getParents().getMother());
}
Similarly,
class HowQueryResolver : IQueryResolver
{
private string _question;
public HowQueryResolver(string question)
{
_question = question;
}
public string ResolveQuery()
{
//do a lot of things here.
System.out.print(GetActualHealth());
}
than finally a factory which return concrete implementation of IQueryResolver
public class QueryResolverFactory
{
public static IQueryResolver GetQueryResolver()
{
if (question.startsWith("How") && question.endsWith("Josh?"))
{
return new HowQueryResolver(question);
}
else if (question.startsWith("Who") && question.endsWith("mother?"))
{
return new WhoQueryResolver(question);
}
}
}

How to call a method whose name is the value of a string variable in java?

This is the code of the method that I want to simplify. The method name I call of SerializedExpFamMixture class is exactly the value of "model", my question is how to assign the value of "model" directly as the name of the method instead of using "if" to determine which method I should call. Since by using "if", I need to list all the possible values of "model" and judge which method I should use.
Thank you very much for help. I am new to java.
public static SerializedExpFamMixture RateMtxModel(String model)
{
SerializedExpFamMixture result=new SerializedExpFamMixture();
if(model=="kimura1980()")
result=SerializedExpFamMixture.kimura1980();
if(model=="accordance()")
result=SerializedExpFamMixture.accordance();
if(model=="pair()")
result=SerializedExpFamMixture.pair();
return result;
}
One way you can approach this is to use Reflection:
Method method = myClass.getClass().getMethod("doSomething", null);
method.invoke(myClass, null);
Since you are new to Java, it's time for some general pointers:
In Java, we usually name our methods with camelCase, so the first letter is lower case.
Also, in Java we usually leave the opening curly-bracket on the same line as the code (no newline).
Always use final on your variables. At least your parameters. That way you won't overwrite it, and thus won't have to try to figure out which value it actually has at runtime.
Use curly-brackets! Please!
The result variable is not actually needed.
Use the equals-method to compare Strings.
If you only want one result, use else-if
Fixing these things, your method looks like this:
public static SerializedExpFamMixture rateMtxModel(String model) {
if (model.equals("kimura1980()")) {
return SerializedExpFamMixture.kimura1980();
} else if (model.equals("accordance()")) {
return SerializedExpFamMixture.accordance();
} else if(model.equals("pair()")) {
return SerializedExpFamMixture.pair();
}
return new SerializedExpFamMixture();
}
Next, let's look at what you are actually trying to do here. You want to pass some Strings around, and use them as a basis for creating objects. And now, with the advice given here, you will do this using reflection. This does not sound like a very good idea to me. Say you were to go through with this, and this happened:
rateMtxModel("kinura1980");
Small typo, hard to spot, will give unexpected results. If you were actually calling a method the compiler would let you know that you messed up, now you will get no warning (btw did you see both errors in that method call?). The same if someone were to delete the accordance()-method, the compiler would not alert them that this will break the program.
If it was up to be I would just use the static factory-methods in SerializedExpFamMixture directly, but if you have to do it like this (if the task at hand is using a String input to create an object) I would do something like this:
public enum Something {
KIMURA1980("kimura1980()"),
ACCORDANCE("accordance()"),
PAIR("pair()");
private final String stringValue;
private Something(final String stringValue) {
this.stringValue = stringValue;
}
public static Something fromString(final String string) {
for (final Something something : values()) {
if (something.stringValue.equals(string)) {
return something;
}
}
return null;
}
}
public static SerializedExpFamMixture rateMtxModel(final String model) {
if (model == null) {
throw new IllegalArgumentException("model is null!");
}
final Something something = Something.fromString(model);
if (something == null) {
return new SerializedExpFamMixture();
}
switch(something) {
case KIMURA1980:
return SerializedExpFamMixture.kimura1980();
case ACCORDANCE:
return SerializedExpFamMixture.accordance();
case PAIR:
return SerializedExpFamMixture.pair();
default:
return new SerializedExpFamMixture();
}
}
This way, the one place where you will use the Strings is in the enum, the rest of the code will use the enum constants and thus have the safety of the compiler to rely on.
One could also leave the linking between operation and String to the enum, like this:
interface Operation<T> {
public T run();
}
public enum Something {
KIMURA1980("kimura1980()", new Operation<SerializedExpFamMixture>() {
public SerializedExpFamMixture run() {
return SerializedExpFamMixture.kimura1980();
}
}) ,
ACCORDANCE("accordance()", new Operation<SerializedExpFamMixture>() {
public SerializedExpFamMixture run() {
return SerializedExpFamMixture.accordance();
}
}),
PAIR("pair()", new Operation<SerializedExpFamMixture>() {
public SerializedExpFamMixture run() {
return SerializedExpFamMixture.pair();
}
}),
DEFAULT(null, new Operation<SerializedExpFamMixture>() {
public SerializedExpFamMixture run() {
return new SerializedExpFamMixture();
}
});
private final String stringValue;
private final Operation<SerializedExpFamMixture> operation;
private Something(final String stringValue, final Operation<SerializedExpFamMixture> operation) {
this.stringValue = stringValue;
this.operation = operation;
}
public static Something fromString(final String string) {
if (string != null) {
for (final Something something : values()) {
if (string.equals(something.stringValue)) {
return something;
}
}
}
return DEFAULT;
}
public SerializedExpFamMixture getCorrespondingSerializedExpFamMixture() {
return operation.run();
}
}
With this setup in the enum (I think the Operation-part can be trimmed out with Java8), the method will be as simple as:
public static SerializedExpFamMixture rateMtxModel(String model) {
return Something.fromString(model).getCorrespondingSerializedExpFamMixture();
}
Use reflection, but you need to consider a few things:
Bug alert! Comparing Strings using == doesn't work as expected in java - use .equals() instead. However, the solution below bypasses that problem
For the general case, which includes methods not visible to the invoker, you need to consider accessibility, both in finding the method and invoking it
You don't need the result variable, and even if using your code, don't need to initialize it
Try this:
String methodName = model.replace("(", "").replace(")", "");
try {
// getMethod() returns only public methods, getDeclaredMethod() returns any visibility
Method method = SerializedExpFamMixture.class.getDeclaredMethod(methodName);
// if the method is not guaranteed to be visible (eg public) you need this:
method.setAccessible(true);
return (SerializedExpFamMixture) method.invoke(null); // how to invoke on the class object
} catch (Exception forBrevity) {
return new SerializedExpFamMixture();
}

How to return String in anonymous class for a method returning void

I'm bit confused. I have the following:
public static String showInputDialog() {
Form frm = new Form();
final Command cmd = new Command("Ok");
final TextField txt = new TextField("Enter the text", null, 1024, 0);
frm.addCommand(cmd);
frm.append(txt);
frm.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c == cmd) {
return txt.getString(); // Error !!
} else {
return null; // Error !!
}
}
});
}
As you can see, I want to return the input dialog string, while the anonymous class method should return void. How can I resolve this problem?
This does not work as you expected.
I see there are already some solutions, but I feel a bit more discussion about what is actually going on might be helpful.
When you call the frm.setCommandListener(new CommandListener() { ... }) the code presents the user with a dialog where she can type in some text and submit, but the code does not stop and wait until the user finishes.
Instead the code continues to execute - without yielding the result. Only after the user finished typing and submits, you get called back to process the result - which might happen much later, or not at all.
I guess you have some code calling this method like:
public void someMethod(int foo, String bar) {
[...]
String result = MyInputForm.showInputDialog();
// do something with the result
System.out.println("hey, got a result "+ result);
[...]
}
Instead you need to reorganize this. First write a helper class handling the result:
public static class MyCallBack {
public MyCallBack(... /* here pass in what you need to process the result*/) {
... remember necessary stuff in instance variables
}
public void processResult(String result) {
// do something with the result
System.out.println("hey, got a result "+ result);
[...]
}
}
then the calling side does just:
public void someMethod(int foo, String bar) {
[...]
MyInputForm.showInputDialog( new MyCallBack(... here pass in stuff ...) );
[...]
}
and the actual code has to be changed to:
public static String showInputDialog(final MyCallBack callback) {
Form frm = new Form();
final Command cmd = new Command("Ok");
final TextField txt = new TextField("Enter the text", null, 1024, 0);
frm.addCommand(cmd);
frm.append(txt);
frm.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c == cmd) {
return callback.processResult(txt.getString());
} else {
return; // or just omit the else part
}
}
});
}
Two issues:
this way of programming feels pretty backwards, but it is really the way it works.
what feels not right is that I need to define a second helper class aside of the CommandListener. That is really not good style. I hope it can be improved, but as I do not see the complete code (which would be too much information anyway), I have to leave it to you to improve the code and get rid of the clutter. While I feel you want to have a modular, reusable input dialog helper, this might not be the best approach; better define the Form,TextField and Command directly where you need the result and get that running. Make it reusable in a second step after you get it running.
You don't need to return it if you instead do something with the String or store it somewhere, for example:
static String result;
public String commandAction(Command c, Displayable d) {
if (c == cmd) {
result = txt.getString();
} else {
result = null;
}
}
Although you'll have threading issues to deal with.
Given that CommandListener is fixed, 2 possible options are
Use a class member variable in the outer class & assign to that variable instead
private static String myText;
...
public static String showInputDialog() {
...
frm.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c == cmd) {
myText = txt.getString();
} else {
myText = null;
}
}
});
}
or Create a concrete implementation of your CommandListener and set the return value as a property of the new implementation
I would have a look at making the method/variable in this snippet non-static...
You cant return the string because you dont know when the listener will be called.
You can do something with it once you have the string though.
public static void showInputDialog() {
StringHandler sh = new StringHandler();
frm.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (c == cmd) {
sh.handle(txt.getString());
} else {
sh.handle(null);
}
}
});}
public class StringHandler {
public void handle(String s){
// Do something with that string.
}
}

Categories