In our uni project we were asked to build a project in which we should also provide an info class in which we should insert all the info like total number of lines of code, number of methods (in the whole project).
We were asked to provide the complete number of methods, to compute with Reflection & RTTI, and obviously with no use of external libraries.
How shall I do?
Simplest approach you can use is,
Create a class to store the info you need ( number of methods,lines or whatever) - use setters/getters.
Use a static block in all your application classes, to calculate the methods, lines etc for each class & update it to info class.
I hope at a given instant it can give you the info about the loaded number of methods/code.
As #Jägermeister rightly said, the aim of this project is to try-out things yourself. So I gave some insights - which you can follow & try out yourself.
Eventually I came to a solution, thank you all.
Here's the code:
private int getNumMethods() {
java.io.File src = new java.io.File("src/APManager2016");
int result = 0;
if (src.isDirectory()) {
String[] list = src.list((java.io.File dir, String name) -> name.toLowerCase().endsWith(".java"));
try {
for (String x : list) {
Class<?> c = Class.forName("APManager2016." + x.replace(".java", ""));
result += c.getDeclaredMethods().length;
}
} catch (ClassNotFoundException ex) {
System.err.println(ex.getMessage());
result = 0;
}
}
if (result == 0)
{
result = 111;
}
return result;
}
Related
I have been trying to get into functional programming with java for a few weeks now. I have created 2 functions below "validateFileFunctionally" and "validateFileRegularly" which perform same validations. First works in a functional way using predicates(we can assume Suppliers, Consumers also in here) while the second one works in traditional java ways.
In 2018 which way should I go.
And should I try to use functional programming everywhere in my code as being done in "validateFileFunctionally" or only with Streams?
public class Main {
private final String INVALID_FILE_NAME_LENGTH = "INVALID FILE NAME LENGTH";
private final String INVALID_FILE_EXTENSION = "INVALID FILE EXTENSION";
private final String INVALID_FILE_SIZE = "INVALID FILE SIZE";
public static void main(String... args) {
File file = new File("text.pdf");
Main main = new Main();
main.validateFileFunctionally(file);
main.validateFileRegularly(file);
}
private void validateFileFunctionally(File file) {
BiPredicate<File, Integer> validateFileName = (f, maxLength) -> f.getName().length() < maxLength;
BiPredicate<File, String> validateExtension = (f, type) -> f.getName().endsWith(type);
BiPredicate<File, Integer> validateSize = (f, maxSize) -> f.length() <= maxSize;
BiConsumer<Boolean, String> throwExceptionIfInvalid = (isValid, errorMessage) -> {
if(!isValid) {
throw new InvalidFileException(errorMessage);
}
};
throwExceptionIfInvalid.accept(validateFileName.test(file, 20), INVALID_FILE_NAME_LENGTH);
throwExceptionIfInvalid.accept(validateExtension.test(file, ".pdf") || validateExtension.test(file, ".csv"), INVALID_FILE_EXTENSION);
throwExceptionIfInvalid.accept(validateSize.test(file, 20), INVALID_FILE_SIZE);
}
private void validateFileRegularly(File file) {
if (file.getName().length() > 20) {
throw new InvalidFileException("INVALID FILE NAME LENGTH");
} else if (!file.getName().endsWith(".pdf") && !file.getName().endsWith(".csv")) {
throw new InvalidFileException("INVALID FILE NAME LENGTH");
} else if (file.length() > 20) {
throw new InvalidFileException("INVALID FILE NAME LENGTH");
}
}
class InvalidFileException extends RuntimeException {
public InvalidFileException(String message) {
super(message);
}
}
}
Dah, this is a pet peeve of mine I'm afraid. Don't try to cram in functional stuff everywhere just because it's the latest new / cool thing - that just makes your code hard to read and unconventional. The Java 8 functional libraries are just another tool you have available that allow you to write cleaner, more concise code in a number of cases. You certainly shouldn't aim to use them exclusively.
Take your case as an example - the chained if statements still might not be the best way of achieving the above, but I can look at that and know near enough exactly what's going on in a few seconds.
Meanwhile, the functional example is just - rather odd. It's longer, less obvious as to what's going on, and offers no real advantage. I can't see a single case for using it as written in this example.
You should be applying Functional Programming wherever it makes sense, and stay away from bold statements like:
"I should try to use FP everywhere in my code"
"I should code only with Streams"
However, keep in mind that this example is not functional at all - validateFileFunctionally is just an enterprise-grade version of validateFileRegularly
Simply put, you took an imperative piece of code and rewrote it by wrapping it into FP infrastructure which is not what FP is about.
FP is about removing runtime uncertainty by building code from small and predictable building blocks/values, and not by putting lambda expressions wherever possible.
In your example, one could achieve this by abandoning exception handling and representing validation result as a value:
private Result validateFileRegularly(File file) {
if (file.getName().length() > 20) {
return Result.failed("INVALID FILE NAME LENGTH");
} else if (!file.getName().endsWith(".pdf") && !file.getName().endsWith(".csv")) {
return Result.failed("INVALID FILE NAME LENGTH");
} else if (file.length() > 20) {
return Result.failed("INVALID FILE NAME LENGTH");
}
return Result.ok();
}
Naturally, one could use the more sophisticated syntax for that, or a more sophisticated applicative-based validation API, but essentially that's what's all about.
Giving an example, lets say we have a code like the one below:
String phone = currentCustomer.getMainAddress().getContactInformation().getLandline()
As we know there is no elvis operator in Java and catching NPE like this:
String phone = null;
try {
phone = currentCustomer.getMainAddress().getContactInformation().getLandline()
} catch (NullPointerException npe) {}
Is not something anyone would advise. Using Java 8 Optional is one solution but the code is far from clear to read -> something along these lines:
String phone = Optional.ofNullable(currentCustomer).flatMap(Customer::getMainAddress)
.flatMap(Address::getContactInformation)
.map(ContactInfo::getLandline)
.orElse(null);
So, is there any other robust solution that does not sacrifice readability?
Edit: There were some good ideas already below, but let's assume the model is either auto generated (not convenient to alter each time) or inside a third party jar that would need to be rebuild from source to be modified.
The "heart" of the problem
This pattern currentCustomer.getMainAddress().getContactInformation().getLandline() is called TrainWreck and should be avoided. Had you done that - not only you'd have better encapsulation and less coupled code, as a "side-effect" you wouldn't have to deal with this problem you're currently facing.
How to do it?
Simple, the class of currentCustomer should expose a new method: getPhoneNumber() this way the user can call: currentCustomer.getPhoneNumber() without worrying about the implementation details (which are exposed by the train-wreck).
Does it completely solve my problem?
No. But now you can use Java 8 optional to tweak the last step. Unlike the example in the question, Optionals are used to return from a method when the returned value might be null, lets see how it can be implemented (inside class Customer):
Optional<String> getPhoneNumber() {
Optional<String> phone = Optional.empty();
try {
phone = Optional.of(mainAddress.getContactInformation().getLandline());
} catch (NullPointerException npe) {
// you might want to do something here:
// print to log, report error metric etc
}
return phone;
}
Per Nick's comment below, ideally, the method getLandline() would return an Optional<String>, this way we can skip the bad practice of swallowing up exceptions (and also raising them when we can avoid it), this would also make our code cleaner as well as more concise:
Optional<String> getPhoneNumber() {
Optional<String> phone = mainAddress.getContactInformation().getLandline();
return phone;
}
String s = null;
System.out.println(s == null);
or
String s = null;
if(s == null)System.out.println("Bad Input, please try again");
If your question was with the object being null, you should have made that clear in your question...
PhoneObject po = null;
if(po==null) System.out.println("This object is null");
If your problem is with checking whether all the parts of the line are null, then you should have also made that clear...
if(phone == null) return -1;
Customer c = phone.currentCustomer();
if(c == null)return -1;
MainAddress ma = c.getMainAddress();
if(ma == null) return -1;
ContactInfo ci = ma.getContactInformation();
if(ci == null)return -1;
LandLine ll = ci.getLandline();
if(ll == null)return -1;
else return ll.toNumber()//or whatever method
Honestly, code that's well written shouldn't have this many opportunities to return null.
At work, we have to generate a report for our client that changes its parameters several times during the week.
This report is generated from a single table on our database.
For example, imagine a table that has 100 columns and I have to generate a report with only 5 columns today, but tomorrow I have to generate with 95 of them.
With this in mind, I created a TO class with all the columns of the specified table and my query returns all columns (SELECT * FROM TABLE).
What I'm trying to create is a dynamic form to generate the report.
I first thought on create a simple frame with a list of the columns listed as check boxes and the user would select the columns that he wants (of course with a button to Select All and another to Deselect All).
As all of the columns have the same name as the attributes of the TO class, I developed the following code (I have Google this):
Class c = Test.class;
for(int i = 0; i < listOfAttributes.length; i++)
{
auxText += String.valueOf( c.getMethod( "get" + listOfAttributes[i]).invoke( this, null ) );
}
Is this the better way to do what I need to?
Thanks in advance.
Obs.: the getters of the TO class have the pattern "getAttribute_Name".
Note: This question is different from the one where the user is asking HOW to invoke some method given a certain name. I know how to do that. What I'm asking is if this is the better way to solve the problem I described.
My Java is a little more limited, but I believe that's about as good as you're going to get using reflection.
Class<?> c = Test.class;
for (String attribute : listOfAttributes) {
auxText += String.valueOf(c.getMethod("get" + attribute).invoke(this, null));
}
But since this sounds like it's from potentially untrusted data, I would advise using a HashMap in this case, with each method explicitly referenced. First of all, it explicitly states what methods can be dynamically called. Second, it's more type safe, and compile-time errors are way better than runtime errors. Third, it is likely faster, since it avoids reflection altogether. Something to the effect of this:
private static final HashMap<String, Supplier<Object>> methods = new HashMap<>();
// Initialize all the methods.
static {
methods.set("Foo", Test::getFoo);
methods.set("Bar", Test::getBar);
// etc.
}
private String invokeGetter(String name) {
if (methods.containsKey(name)) {
return String.valueOf(methods.get(name).get());
} else {
throw new NoSuchMethodException();
}
}
It might sound like a major DRY violation to do so, but the repetition at least makes sure you don't wind up with unrelated getters accidentally called.
Class c = Test.class;
for(int i = 0; i < listOfAttributes.length; i++)
{
auxText += String.valueOf( c.getMethod( "get" + listOfAttributes[i]).invoke( this, null ) );
}
You can do this somewhat more elegantly via Java Beans, the Introspector, and PropertyDescriptor, but it's a little more long-winded:
Map<String, Method> methods = new HashMap<>();
Class c = this.getClass(); // surely?
for (PropertyDescriptor pd : Introspector.getBeanInfo(c).getPropertyDescriptors())
{
map.put(pd.getName(), pd.getReadMethod();
}
//
for (int i = 0; i < listOfAttributes.length; i++)
{
Method m = methods.get(listOfAttributes[i]);
if (m == null)
continue;
auxText += String.valueOf(m.invoke(this, null));
}
I am trying to find a way to parse java code source in netbeans using the Tree API, I learned through this guide how I can access high level language elements (classes,methods,fields ..).
what I'm looking for is a way to parse if else statements (for a start) since I'm trying to apply replace type code with state strategy refactoring afterwards. it is very important for me to get the if condition. Any help would be deeply appreciated.
After diving into the Compiler Tree API doc I found how to access low level code the condition of a selected if statement in my case, here is a code snippet
#Override
public Void visitIf(IfTree node, Void p) {
try {
JTextComponent editor = EditorRegistry.lastFocusedComponent();
if (editor.getDocument() == info.getDocument()) {
InputOutput io = IOProvider.getDefault().getIO("Analysis of " + info.getFileObject().getName(),
true);
ExpressionTree exTree = node.getCondition();
if (exTree.getKind() == Tree.Kind.PARENTHESIZED) {
ParenthesizedTree parTree = (ParenthesizedTree) exTree;
BinaryTree conditionTree = (BinaryTree) parTree.getExpression();
ExpressionTree identTree = conditionTree.getLeftOperand();
if (identTree.getKind() == Tree.Kind.IDENTIFIER) {
Name name = ((IdentifierTree) identTree).getName();
io.getOut().println("Hurray, this is the name of the identifier in the left operand: " + name.toString());
}
io.getOut().close();
}
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
return null;
}
Thankfully the code naming is intuitive otherwise the documentation doesn't help much. debugging using println is very useful to know what kind of tree to deal with next.
I have a question regarding structuring of code.
I have let us say three types of packages A,B and C.
Now, classes in package A contains classes which contain the main() function. These classes
need some command line arguments to run.
In package B, there are classes which contains some public variables, which need to be configured, at different times. For example before calling function A, the variable should be set or reset, the output differs according to this variable.
In package C, uses the classes in package B to perform some tasks. They do configure their variables as said before. Not only when the object is created, but also at intermediate stage.
Package A also has classes which in turn use classes from package B and package C. In order to configure the variables in classes of B and C, class in package A containing the main() function, reads command line arguments and passes the correct values to respective class.
Now, given this scenario, I want to use Apache Commons CLI parser.
I am unable to understand how exactly I should write my code to be structured in an elegant way. What is a good design practice for such scenario.
Initially I wrote a class without Apache to parse the command line arguments.
Since I want a suggestion on design issue, I will give an excerpt of code rather than complete code.
public class ProcessArgs
{
private String optionA= "default";
private String optionB= "default";
private String optionC= "default";
public void printHelp ()
{
System.out.println ("FLAG : DESCRIPTION : DEFAULT VALUE");
System.out.println ("-A <Option A> : Enable Option A : " + optionA);
System.out.println ("-B <Option B> : Enable Option B : " + optionB);
System.out.println ("-C <Option C> : Enable Option C : " + optionC);
}
public void printConfig()
{
System.out.println ("Option A " + optionA);
System.out.println ("Option B " + optionB);
System.out.println ("Option C " + optionC);
}
public void parseArgs (String[] args)
{
for (int i=0;i<args.length;i++)
{
if (args[i].equalsIgnoreCase ("-A"))
optionA = args[++i];
else if (args[i].equalsIgnoreCase ("-B"))
optionB = args[++i];
else if (args[i].equalsIgnoreCase ("-C"))
optionC = args[++i];
else
throw new RuntimeException ("Wrong Argument : " + args[i] + " :: -h for Help.");
}
}
}
Points to note -
I already have 50+ command line options and they are all in one place.
Every class uses only a group of command line options.
I tried to write an interface, somehow but I am unsuccessful. I am not sure if this is a good way to do it or not. I need some design guidelines.
Here is the code which I wrote -
public interface ClassOptions
{
Options getClassOptions();
void setClassOptions(Options options);
}
public class Aclass implements ClassOptions
{
private String optionA="defaultA";
private String optionB="defaultB";
public Options getClassOptions()
{
Options options = new Options();
options.addOption("A", true, "Enable Option A");
options.addOption("B", true, "Enable Option B");
return options;
}
public void setClassOptions(Options options, String args[])
{
CommandLineParser parser = new BasicParser();
CommandLine cmd=null;
try
{
cmd = parser.parse( options, args);
} catch (ParseException e)
{
// TODO Auto-generated catch block
// e.printStackTrace();
System.out.println("ignored option");
}
if(cmd.hasOption("A"))
optionA = "enabled";
if(cmd.hasOption("B"))
optionB = "enabled";
}
}
I think the problems in such writing of code are -
There are different types of arguments like int, double, string, boolean. How to handle them all.
getClassOption() and setClassOption() both contain the arguments "A", "B" for example. This code is prone to errors made while writing code, which I would like to eliminate.
I think the code is getting repetitive here, which could be encapsulated somehow in another class.
Not all the arguments are required, but can be ignored.
Thank You !
I would recommend to you JCommander.
I think it's a really good Argument Parser for Java.
You define all the Argument stuff within annotations and just call JCommander to parse it.
On top of that it also (based on your annotations) can print out the corresponding help page.
You don't have to take care about anything.
I believe you will love it! :)
Take a look at it: http://jcommander.org/
There are a lot of examples and such!
Good Luck! :)
simple example for command line argument
class CMDLineArgument
{
public static void main(String args[])
{
int length=args.length();
String array[]=new String[length];
for(int i=0;i<length;i++)
{
array[i]=args[i];
}
for(int i=0;i<length;i++)
{
System.out.println(array[i]);
}