Sam's Chest of Drawers

Thinking about Programming and Lifestyle


  • Home

  • Categories

  • Archives

  • Tags

Safer Property Accessor

Posted on 12-24-2017 | In Programming

What is the problem

Suppose we have models like this:
img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Student {
private Teacher teacher;
public Teacher getTeacher() { return teacher; }
public void setTeacher(Teacher teacher) { this.teacher = teacher; }
}

class Teacher {
private Email email;
public Email getEmail() { return email; }
public void setEmail(Email email) { this.email = email; }
}

class Email {
private String address;
public String getAddress() { return address; }
public void setAddress(String address) { this.address = address; }
}

(Not domain model actually, just poor data container. I’ll come back to this topic later.)

Now given a student instance, I need to do some change to the teacher’s email. How can I do? Firstly I need a way to retrieve the mail address.

Read more »

C# For Java Programmer (Language Basic)

Posted on 12-17-2017 | In Programming

It’s based on C# 7.0, which is the latest version with VS 2017. I list the feature unfamiliar to Java programmer.

Read more »

Functional Programming in Java

Posted on 12-16-2017 | In Programming

Based on Functional Programming in Java, a book similar to the red bible of Scala and explains reasons why Scala introduced features like monad Option, List, Stream, Try and comprehension.

Question Answer
01.groupBy(value -> key) Stream::collect(Collectors::groupingBy(value -> key)) See also partitioningBy
02.type alias in Java Use interface (see code)
03.final variable for closure Final requirement applies to local variable only (see code)
04.If closure has reference to non-local variable which is not final, how to make function free of side effects Turn implicit variables to explicit arguments of the function (see code)
05.There are Function and BiFunction. How about TriFunction Using curring is another way to avoid TriFunction (see code
06.Partially bind the first/second parameter Deduct from types to create curried function (see code)
07.The size of a thread 1064 KB for 64-bit JVM (size of stack)
08.Give meaningful name for built-in functional interface Define new functional interfaces (with same function signature as built-in functional interfaces) and use the new interfaces in class/method definition. Then use anonymous lambda in the application.
09.Pattern matching in Java Define a Case class extended from Tuple<Supplier<Boolean>, Supplier<Result<T>>>. See com.samwang.common.EmailValidation (alg-java in my git)
10.Handle effects in a loop One way is to fold effects into one and execute them afterwards (in a batch mode or delay the execution until necessarily).
11.Why classes shouldn’t have several properties of the same type (in modeling) No compiling error when using an incorrect property. Solution is to use value types like Money, Weight, Age (rather than double, int).
12.Make recursion function stack-safe 1) Turn to tail-recursion 2) Use heap-based TailCall, which has two sub-classes: Return and Suspend. See com.samwang.common.TailCall (alg-java in my git)
13.Turn to tail-recursion Define a helper function with an accumulator.
14.Another way to look at Fibonacci series 0,1,1,2,3,5,8,13 A series of pairs (tuples): (0,1),(1,1),(1,2),(2,3),(3,5),(5,8),(8,13) And the generation method is x -> new Tuple<>(x._2, x._1 + x._2)
15.Function memorization Wrap function in com.samwang.common.Memoizer (alg-java in my git). For functions with more than one parameter, one way is to use Tuple2, Tuple3 (and use these tuples as the key in Memorizer). Another (better) way is to memorize the curried function (see code). In case there are huge different results to be kept in cache, use soft or weak references (and WeakHashMap) in Memorizer.
16.java.util.Objects Helper functions for comparison, equal, hash-code, null-check, etc.
17.Functional list in Java Define abstract class List with two sub-classes Nil and Cons. See com.samwang.common.List (alg-java in my git).
18.What’s good for StringBuilder::append to return this In case StringBuilder is used as an accumulator, it saves one line of code to explicitly return the builder (see code).
19.Implement foldRight with foldLeft for the purpose of stack safety list.reverse().foldLeft(identity, x -> y -> f.apply(y).apply(x));
20.Given concat(head, tail), what’s good to implement List::flatMap with foldRight instead of foldLeft foldLeft: (((1,2),3),4); foldRight: (1,(2,(3,4))). So foldRight works well with concat(f.apply(element), list_for_accumulation)
21.Implement variance (with mean) (see code)
22.Optional::orElseGet vs orElse The former supports laziness which is critical for function evaluation; the latter is suitable for literal (because literal has been evaluated already by compiler).
23.Exception handling with Result See com.samwang.common.Result (alg-java in my git), which is more powerful than Option in that it has 3 subtypes to represent 3 cases:Success, Failure and Empty.
24.Give meaningful (error) message for Result.Empty or Result.Failure abstract Result mapFailure(String message)
25.Find the last one using foldLeft (see code)
26.Loop without loop Accumulator + recurrence
27.Return an item at an index with foldLeft fold with a Tuple as identity in the format of (failure + index). See Result::getAt_ (alg-java in my git).
28.Reason to use joinfork thread pool to do list parallelization. Hard to predict computation time so having to divide the list into a large number of sublists.
29.Algorithm to show the ugliness of imperative style Find the first ten primes (see code)
30.Remove item from Binary Search Tree (BST) After removing the item, the left and right node need to be merged. See Tree::remove and Tree::removeMerge (alg-java in my git)
31.General merge for BST See Tree::merge (alg-java in my git)
32.Day-Stout-Warren algorithm for balanced tree 1, Rotate left until both branches are nearly equal. 2, Apply rotation to the right branch. 3, Apply right rotation to the left branch. 4, Stop when the height = log2(size)
Read more »

Spring 5

Posted on 12-10-2017 | In Programming

TODO:

What’s the use of java.lang.annotation.Target,Retention? In other words, give a practical view of Java Annotation.

In which case, @Autowired needs to used together with @Qualifier

Read more »

Java Basic

Posted on 11-10-2017 | In Programming
Question Answer
01.Classloader Three classloaders: Bootstrap(rt.jar), extension and application(classpath).
02.OOPS principles Abstraction with encapsulation, (type system supports) inheritance and thus polymorphism.
03.Object oriented VS object based ES5 as object based language, provides abstraction and encapsulation, but no native support of inheritance and polymorphism
04.What happen if multiple interfaces have the same default method and a class implements these interfaces Compile error.
05.Aggregation VS composition Objects get destroyed along with the composite object, while aggregated objects exist.
06.super() and this() They (not both of them) must be the first statement for a constructor.
07.Execute a program with main method No way to do it since Java 7.
08.Override for static(class) method No way as inheritance doesn’t apply to class.
09.Overloading VS overriding Overloading happens at compile time, while overriding at runtime.
10.Covariant return type It’s allowed to return a sub-type in method of sub-class. (see code)
11.Marker interface VS annotation Interface provides static check during compiling, while annotation has to be checked at runtime. (see code)
12.Pass-by-value or pass-by-reference Java is always pass-by-value. (see code)
13.”foo” VS new String(“foo”) The former is in string constant pool, while the latter is a normal string object. (see this)
14.Comparator VS comparable The former is a util interface comparing two objects, while the latter compares another object with itself, which means it is implemented by compared types while comparator is used by sorting functions.
15.Why Object::hashCode() is native Performance concern because it looks for an integer representation of an object reference on the heap.
16.What’s the benefit of Collections::copy() over collection constructor or addAll It doesn’t involve reallocation but instead trigger out-of-index error if happened.
17.Return value for high-order function For functional interface, return a lambda (instead of an anonymous class).
18.java.time package since Java 8 LocalDate, Year, MonthDay, DayOfWeek. Also refer to TemporalAccessor for use suggestion (see code)
19.@SafeVarargs For methods with variable number of arguments, JVM uses array under the hood. When the type of arguments is type parameter, JVM uses Object[] which could lead ClassCastException. That’s the reason JVM gives warning during compiling. The annotation is used to by-pass the warning.
20.Catch uncaught exception for a Thread Thread::setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh)
21.Get notification on memory usage see MemoryPoolMXBean’s javadoc
22.Java is a strict language Method arguments are passed by value (evaluated first, that’s the reason Scala introduced by-name parameters). In a few places however, Java is lazy: &&, ?:, if…else, foo, while, Java 8 streams.
23.Advantages to use anonymous lambda (or method references) 1, No need to declare type explicitly. 2, Named lambdas are compiled to objects.
24.Add constraints to resource accessing or preventing thread from quitting too early Semaphore
25.How to prevent assertion from being disabled Check with a static initializer and quit with RuntimeException (see code)

Continue at P250

(To be continued)

Read more »

Learning TeX

Posted on 10-17-2017 | In Lifestyle

Q&A

Question Answer
01.Preamble The part before \begin{document}. It’s for \title, \author and \newcommand that is visible for the whole document.
02.Define commands(macro) \newcommand{command-name}[parameter-count][optional-parameters]{definition} in preamble
03.Show title and table-of-contents Make sure both of them are after \begin{document}
04.Article outline elements \chapter \section \subsection
05.Numbered list \begin{enumerate} \item ... \end{...}
06.Non-numbered list \begin{itemize} \item ... \end{...}
07.Description list \begin{description} \item ... \end{...}
08.Table \begin{tabular} head1 & head2\\ \hline row1-col1 & row1-col2\\ \end{...} Don’t forget \ at the end of each row (including head)
09.Reference \label{key} \ref{key} \pageref{key}
10.Bibliography \begin{thebibliography}{widest label} \bibitem[labelA]{keyA} Author A, Title A, Year A \end{...} Don’t forget the second argument in begin section. \cite{keyA,keyB} to cite the reference(s).
11.Inline formula \( ... \)
12.Separate formula \[ ... \]
13.Numbered formula \begin{equation} ... \end{...}
14.Multi-line formula \begin{align} formula1 &= A formula2 &= B \end{...} amsmath provides a align mode to use & to align multi-line formula.
15.Subscript in formula a_{subscript} \lim_{n=1,2, \ldots} a_n
16.Underline and overline in formula \overline{} \underline{}_{} \overbrace \underbrace

See PDF and TEX

Beyond Try Catch

Posted on 10-15-2017 | In Programming

See the PDF version
Check source code

Promise and Future

Posted on 09-17-2017 | In Programming

What is Future

Future is a place to hold a value (that may not be available yet). Future has two parts: asynchronized computation (a block provided by application) and the computation result.

Future’s computation

In language such as Scala, a block of computation is actually by-name parameter like this:

1
2
3
4
val fetchPatientDetails = Future{
val session = getSession(credential)
session.getPatientInfo(id)
} // it's Future<PatientInfo>

Read more »

Scala and Functional Programming

Posted on 09-05-2017 | In Programming

Map

Keywords Comment & Reference
Concurrent programming in Scala Q&A
Programming Scala Q&A
Scala tip Q&A
Algebraic Data Types Comment, blog 1,2,3
sbt Comment
reader monad reader monad
resource resource
an introduction blog blog
Read more »

Feature Branch Workflow

Posted on 07-15-2017 | In Tool

I recommend to use Feature Branch Workflow(FBW) as a daily guideline of source code check-in. Read more why FBW is a good workflow

It starts from a new branch (either for a new feature or bug-fixing):

1
2
3
4
5
git checkout -b <feature-branch>

// then make change locally
git add .
git commit -a
Read more »
123…5
Yuping Wang

Yuping Wang

85608565

43 posts
5 categories
30 tags
Github Twitter
© 2016 - 2020 Yuping Wang
Powered by Hexo
Theme - NexT.Muse