Skip to content

Commit 2430990

Browse files
authored
Merge pull request #6 from MartinFiorde/refactor/clean-personal-practice
Refactor/clean personal practice
2 parents b768f15 + e7b21a3 commit 2430990

File tree

22 files changed

+30
-767
lines changed

22 files changed

+30
-767
lines changed

docs/Apuntes java functional.docx

-644 KB
Binary file not shown.

docs/Functional SE.pdf

-1.12 MB
Binary file not shown.
-312 KB
Binary file not shown.

jobs-search-reporter/src/main/java/com/platzi/jobsearch/CommanderFunctions.java

Lines changed: 8 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,20 +8,6 @@
88
import java.util.function.Supplier;
99

1010
public interface CommanderFunctions {
11-
/**
12-
* JCommander permite generar opciones de terminal de cualquier clase, por eso el primer parametro es
13-
* de tipo Object.
14-
*
15-
* @param object Clase de la cual se generaran los argumentos de JCommander
16-
* @return una instancia de JCommander. Idealmente con CLIArguments como objeto pasado.
17-
*/
18-
static JCommander buildCommander(Object object) {
19-
return JCommander
20-
.newBuilder()
21-
.addObject(object)
22-
.build();
23-
}
24-
2511
/**
2612
* Con esta funcion, facilitamos crear una configuracion inicial de JCommander, pidiendo el nombre del
2713
* programa y un Supplier de tipo T para los argumentos. Asi podemos usar alguna funcion que nos devuelva
@@ -33,7 +19,11 @@ static JCommander buildCommander(Object object) {
3319
* @return una instancia de {@link JCommander} ya configurada con el nombre y los argumentos.
3420
*/
3521
static <T> JCommander buildCommanderWithName(String name, Supplier<T> argumentsSupplier) {
36-
JCommander jCommander = buildCommander(argumentsSupplier.get());
22+
// JCommander permite generar opciones de terminal de cualquier clase, por eso se le agrega un object con el metodo addObject(...)
23+
// argumentsSupplier.get() es la clase de la cual se generaran los argumentos de JCommander
24+
// Queda definida una instancia de JCommander. Idealmente con CLIArguments como objeto pasado.
25+
JCommander jCommander = JCommander.newBuilder().addObject(argumentsSupplier.get()).build();
26+
3727
jCommander.setProgramName(name);
3828
return jCommander;
3929
}
@@ -45,18 +35,14 @@ static <T> JCommander buildCommanderWithName(String name, Supplier<T> argumentsS
4535
static Optional<List<Object>> parseArguments(
4636
JCommander jCommander,
4737
String[] arguments,
48-
OnCommandError onCommandError
49-
) {
50-
List<Object> result;
38+
OnCommandError onCommandError) { // en caso que las validaciones de CLIKeywordValidaror o CLIHelpValidator fallen, se generará un ParameterException
5139
try {
5240
jCommander.parse(arguments);
53-
5441
return Optional.of(jCommander.getObjects());
55-
} catch (ParameterException exception) {
42+
} catch (ParameterException exception) { // atrapará el parameter exception y devuelve un optional vacio
5643
onCommandError.onError(jCommander);
44+
return Optional.empty();
5745
}
58-
59-
return Optional.empty();
6046
}
6147

6248
@FunctionalInterface

jobs-search-reporter/src/main/java/com/platzi/jobsearch/JobSearch.java

Lines changed: 7 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,31 +21,22 @@ public static void main(String[] args) {
2121
JCommander jCommander = buildCommanderWithName("job-search", CLIArguments::newInstance);
2222

2323
//Obtenemos las opciones que se le dieron a JCommander
24-
Stream<CLIArguments> streamOfCLI =
25-
//Nos retorna un Optional<List<Object>>
26-
parseArguments(jCommander, args, JCommander::usage)
27-
//En caso de un Optional.empty()
28-
.orElse(Collections.emptyList())
24+
Stream<CLIArguments> streamOfCLI = parseArguments(jCommander, args, JCommander::usage) //Nos retorna un Optional<List<Object>>
25+
.orElse(Collections.emptyList()) //En caso de un Optional.empty()
2926
.stream()
3027
.map(CLIArguments.class::cast); // map(obj -> (CLIArguments) obj) give same result
3128

3229
//Tomamos nuestro Stream y obtenemos las opciones que se dieron en el CLI
3330
Optional<CLIArguments> cliOptional = streamOfCLI
34-
//Solo nos interesan los casos donde no sea la solicitud de ayuda
35-
.filter(cli -> !cli.isHelp())
36-
//Y que contengan un keyword, en otros caso no tenemos que buscar
37-
.filter(cli -> cli.getKeyword() != null)
31+
.filter(cli -> !cli.isHelp()) //Solo nos interesan los casos donde no sea la solicitud de ayuda
32+
.filter(cli -> cli.getKeyword() != null) //Y que contengan un keyword, en otros caso no tenemos que buscar
3833
.findFirst();
3934

4035
//Si el Optional tiene un dato, lo convertimos a Map<String,Object>
4136
cliOptional.map(CLIFunctions::toMap)
42-
//Convertimos el Map en un request
43-
.map(JobSearch::executeRequest)
44-
//Aun seguimos operando sobre un Optional… en caso de que no hubiera datos
45-
//Generamos un stream vacio
46-
.orElse(Stream.empty())
47-
//Imprimos los datos por pantalla.
48-
.forEach(System.out::println);
37+
.map(JobSearch::executeRequest) //Convertimos el Map en un request
38+
.orElse(Stream.empty()) //Aun seguimos operando sobre un Optional… en caso de que no hubiera datos generamos un stream vacio
39+
.forEach(System.out::println); //Imprimos los datos por pantalla.
4940
}
5041

5142
private static Stream<JobPosition> executeRequest(Map<String, Object> options) {

jobs-search-reporter/src/main/java/com/platzi/jobsearch/cli/CLIArguments.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ public final class CLIArguments {
4444
private boolean isMarkdown = false;
4545

4646
@Parameter(
47-
names = "--help",
47+
names = {"--help", "-h"},
4848
help = true,
4949
validateWith = CLIHelpValidator.class,
5050
description = "Muestra esta ayuda")

jobs-search-reporter/src/main/java/com/platzi/jobsearch/cli/CLIKeywordValidator.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
public class CLIKeywordValidator implements IParameterValidator {
1212
@Override
1313
public void validate(String name, String value) throws ParameterException {
14-
if (!value.matches("^[a-zA-Z]+[0-9]*$")) {
14+
if (!value.matches("^[a-zA-Z]+\\d*$")) {
1515
System.err.println("Keyword: " + value + " no es un Keyword valido, keywords deben ser alfanumericas.\n");
1616
throw new ParameterException("Only alphanumerics are supported");
1717
}
Lines changed: 0 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,4 @@
11
package com.platzi.functional_student_practice._03_inmutable;
22

3-
import java.util.List;
4-
53
public class C8InmutObjWithMutAttributes {
6-
7-
public static void main(String[] args) {
8-
9-
System.out.println("////////////////////////////////////////////////////////////////////////////////////");
10-
System.out.println("\nCLASS 8\n");
11-
12-
// 1. We make an inmutable object (without setters)
13-
Direccion dir = new Direccion("New York");
14-
15-
// 2. We make a mutable object (with setters)
16-
Persona p1 = new Persona(dir);
17-
18-
// 3. We make an inmutable list
19-
List<Persona> lista1 = List.of(p1);
20-
21-
// 4. Try to change mutable element from inmutable list is allowed
22-
System.out.println("Antes de modificar: " + lista1);
23-
p1.getDireccion().setCiudad("Los Angeles");
24-
System.out.println("Después de modificar: " + lista1);
25-
26-
}
27-
28-
private static class Direccion {
29-
String ciudad;
30-
31-
Direccion(String ciudad) {
32-
this.ciudad = ciudad;
33-
}
34-
35-
String getCiudad() {
36-
return ciudad;
37-
}
38-
39-
void setCiudad(String ciudad) {
40-
this.ciudad = ciudad;
41-
}
42-
43-
@Override
44-
public String toString() {
45-
return ciudad;
46-
}
47-
}
48-
49-
private static class Persona {
50-
private final Direccion direccion;
51-
52-
Persona(Direccion direccion) {
53-
this.direccion = direccion;
54-
}
55-
56-
public Direccion getDireccion() {
57-
return direccion;
58-
}
59-
60-
@Override
61-
public String toString() {
62-
return "Persona{direccion=" + direccion + "}";
63-
}
64-
}
65-
664
}
Lines changed: 0 additions & 70 deletions
Original file line numberDiff line numberDiff line change
@@ -1,74 +1,4 @@
11
package com.platzi.functional_student_practice._04_functional;
22

3-
import java.util.function.IntPredicate;
4-
import java.util.function.IntUnaryOperator;
5-
import java.util.function.Predicate;
6-
73
public class C11y12MathFunctions {
8-
public static void main(String[] args) {
9-
10-
System.out.println("////////////////////////////////////////////////////////////////////////////////////");
11-
System.out.println("\nCLASS 11\n");
12-
13-
// 1. function as type
14-
// Function<Integer, Integer> square1 = new Function<Integer, Integer>() {
15-
// @Override
16-
// public Integer apply(Integer x) {
17-
// return x * x;
18-
// }
19-
// };
20-
// System.out.println(square1.apply(5)+"\n");
21-
22-
// 2. function 1 writen in a more performant way
23-
IntUnaryOperator square2 = x -> x * x;
24-
System.out.println(square2.applyAsInt(6)+"\n");
25-
26-
// 3. function 3 declared in the class, outside the main method
27-
System.out.println(square3(7));
28-
System.out.println(square3(8)+"\n");
29-
30-
31-
System.out.println("////////////////////////////////////////////////////////////////////////////////////");
32-
System.out.println("\nCLASS 12\n");
33-
34-
// 1. Function as type using lambda to declare operation in one line
35-
// Function<Integer, Boolean> isOdd1 = x -> x % 2 == 1;
36-
// System.out.println(isOdd1.apply(7));
37-
// System.out.println(isOdd1.apply(8)+"\n");
38-
39-
// 2. function 1 writen in a more performant way
40-
IntPredicate isOdd2 = x -> x % 2 == 1;
41-
System.out.println(isOdd2.test(7));
42-
System.out.println(isOdd2.test(8)+"\n");
43-
44-
// 3. function Predicate by teacher
45-
// Predicate<Integer> isEven1 = x -> x % 2 == 0;
46-
// System.out.println(isEven1.test(7));
47-
// System.out.println(isEven1.test(8)+"\n");
48-
49-
// 4. function 3 performant
50-
IntPredicate isEven2 = x -> x % 2 == 0;
51-
System.out.println(isEven2.test(7));
52-
System.out.println(isEven2.test(8)+"\n");
53-
54-
// 5. Student example
55-
Predicate<Student> isApproved = student -> student.getQualification()>= 7;
56-
System.out.println(isApproved.test(new Student(6)));
57-
System.out.println(isApproved.test(new Student(7)));
58-
}
59-
60-
private static int square3(int x) {
61-
return x * x;
62-
}
63-
64-
private static class Student {
65-
private final double qualification;
66-
public Student(double qualification) {
67-
this.qualification = qualification;
68-
}
69-
public double getQualification() {
70-
return qualification;
71-
}
72-
}
73-
744
}
Lines changed: 0 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -1,57 +1,4 @@
11
package com.platzi.functional_student_practice._04_functional;
22

3-
import java.util.ArrayList;
4-
import java.util.List;
5-
import java.util.function.Consumer;
6-
import java.util.function.Supplier;
7-
83
public class C13CLIUtils {
9-
10-
public static void main(String[] args) {
11-
12-
System.out.println("////////////////////////////////////////////////////////////////////////////////////\n");
13-
System.out.println("CLASS 13\n");
14-
15-
// 1. Created CLI class, consumer and supplier
16-
List<CLIArguments> list = new ArrayList<>();
17-
for (int i = 0; i < 5; i++) {
18-
list.add(generateCLI());
19-
list.get(i).setHelp(i % 2 == 0);
20-
}
21-
22-
for (int i = 0; i < list.size(); i++) {
23-
showHelp(list.get(i), i);
24-
}
25-
26-
}
27-
28-
29-
private static void showHelp(CLIArguments cliArguments, int i) {
30-
Consumer<CLIArguments> consumerHelper = cliArguments1 -> {
31-
if (cliArguments1.isHelp()) {
32-
System.out.println(i +": Manual required");
33-
}
34-
};
35-
consumerHelper.accept(cliArguments);
36-
}
37-
38-
39-
private static CLIArguments generateCLI() {
40-
Supplier<CLIArguments> generator = CLIArguments::new; //same as () -> new CLIArguments()
41-
return generator.get();
42-
}
43-
44-
45-
private static class CLIArguments {
46-
private boolean isHelp;
47-
48-
public boolean isHelp() {
49-
return isHelp;
50-
}
51-
52-
public void setHelp(boolean help) {
53-
isHelp = help;
54-
}
55-
}
56-
574
}

0 commit comments

Comments
 (0)