Project progress and something I like/hate of ReactJS

Actually I have finished the backend API for a while. Instead of using Django, I chose Flask because I don’t need the model in Django. There are so much steps you need to do a simple thing in Django. With Flask, I write an api and it’s done. Of course Django is more mature and has more features but I don’t need them now.

The problem is frontend because I am not a frontend developer, to say it precisely, I don’t do much html/css/javascript stuff. Anyway, I don’t want to use AngularJS ( which have experience with ) because it’s a full blown framework with its own MVC paradigm. I just want a simple web page which show two textbox and a button. So I chose React and had to go through the tutorial.

For some reason, I kinda hate it. I like it for the component idea and I don’t have clutter up my html with jsp/php whatever, I just put everything inside a .js file. However, during the tutorial, I found something which made me nausea.

Function and ECMA6 class

First of all, it’s the choice between using a function or a ECMA6 class to describe a component. In the official documentation , there are many examples of function AND ECMA6 class appear together and both of them are Component of React. For instance:

function BoilingVerdict(props) {
  if (props.celsius >= 100) {
    return <p>The water would boil.</p>;
  }
  return <p>The water would not boil.</p>;
}
class Calculator extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {temperature: ''};
  }

  handleChange(e) {
    this.setState({temperature: e.target.value});
  }

  render() {
    const temperature = this.state.temperature;
    return (
      <fieldset>
        <legend>Enter temperature in Celsius:</legend>
        <input
          value={temperature}
          onChange={this.handleChange} />
        <BoilingVerdict
          celsius={parseFloat(temperature)} />
      </fieldset>
    );
  }
}

It make sense with the class way to make a Component. It doesn’t make much sense for me with the Functional way. In my paradigm, I believe there should be only ONE way to do the same thing. It is confusing to see a function there but it’s not a real function. Yes it does return something but it serve the purpose like a Class. I think they should change all of them to Class instead of using function for Component.

States and Props

Second, there are difference between state and props. It’s confusing in the example because they introduce state first with an working example, and later told me to put it away and replace it with props. In additon, they were used in the same way: “this.state.someThing” and “this.props.someThing” and I think it’s confusing for beginner. I assume it’s like fields of super class in Java but it has extra work to pass the state of super class to subclass. We could do it cleaner with Java:

package me.rayentwickler.main;

public class TestSuperClass {
private String generalPropertyA;

public TestSuperClass(String generalPropertyA){
this.generalPropertyA = generalPropertyA;
}
public String getGeneralPropertyA() {
return generalPropertyA;
}

public void setGeneralPropertyA(String generalPropertyA) {
this.generalPropertyA = generalPropertyA;
}

}

package me.rayentwickler.main;

public class TestSubClass extends TestSuperClass {

ย ย ย  public TestSubClass(String generalPropertyA){
super(generalPropertyA);
}
public static void main(String[] args){
TestSubClass myInstance = new TestSubClass(“ABC”);
System.out.println(myInstance.getGeneralPropertyA());
}
}

In Java, if two class have ancestor/child relationship, I don’t have to tell Java that what kind of fields does the ancestor have. But it ReactJS, it seems I have to do a lot of boilerplate code!

 

Props are Read-Only, but we could change it by setState()

React said it provide a one-way data flow to make the world safer, so props are read-only. However, because the mother component still to access all the states of its children, we need to “Lift the state up” so that every state are stored in the top most Component and the state are passed down to children like a waterfall ( The real nature waterfall, not SDLC ). However, usually we want to accept user input and change the state which is props in this case, but props are read-only! What now? Well, ReactJS provided a way to call upper level component’s function, and in the function it called setState()! Since state could be modified, and after each update, render() would be call and states are passed to children again with new values. Seriously, it sounds like a loophole in its paradigm.

Coding Horror – C code in disguise of Java

There is huge demand for software developers in the market but there are not enough candidates which fits the requirement of company. Thus, on and off there would be some developers who has coding issue, were hired. Today I would share some bizarre code I have seen in workplace.

Let’s start with conclusion, “He/She is a C developer instead of a Java developer. He/She is writing C code while pretending it is Java.”

The case is this: we need to generate several reports with data from database. Let’ say there are 10 reports. Here is some strange code I’ve seen, it is not the real code, I have change it and omitted some detail which is related to company’s business:

private final static String[][] titles = { {“Column A1”, “Column B1”}, {“Column A2”, “Column B2”}, {“Column A3”, “Column B3”} ,{“Column A4”, “Column B4”}, {“Column A5”, “Column B5”}, {“Column A6”, “Column B6”}, {“Column A7”, “Column B7”}, {“Column A8”, “Column B8”}, {“Column A9”, “Column B9”}, {“Column A10”, “Column B10”}};

Who use two-dimensional array for String? In this case, the column headers for each reports are not related to each other so they should not be in an array. An array is used for data which has order relationship, of the same type. This developer just use two-dimensional array for convenience. Also, there configuration stuff should be put in a configuration file so that later when we change the column header, we don’t have to compile the code again.

BufferedWriter[] bfwList = prepareBufferedWriter();

Come one, what is this? Same argument as above.

 

genReport1(bwList[0], dao);
genReport2(bwList[1], dao);







genReport10(bwList[9], dao);

This part is where the real work happens. It’s pain to see he/she passed a BufferedWriter to a method. It’s illogical and not necessary. To be honest, I won’t declare a BufferedWriter outside of the method. I would prefer this:

public void genReport( String filename );

The BufferedWriter I would create INSIDE the method with the provided filename ( with actual file path ). I don’t pass a DAO ( data access object ) around. The DAO should be a class member of the service class in which this method belongs to so that it already has access to the DAO.

In conclusion, it is not object oriented programming, it is a C procedural programming disguised in Java.

 

My sentiments over Java and Python – Part 1

Photo by Mike Kenneally on Unsplash

 

I want to write about the decision between using Java and Python. Although I have more experience with Java, I chose Python, nonetheless, it wasn’t a resounding victory of Python over Java. Let’s think about the pros and cons of them.

Here is the technology stack of major tech companies according to stackshare:

Google: Python, Java, Go, C++, Dart
Apple: Swift, Objective-C
Microsoft: C#, .NET, Visual Basic
Intel: Java
Facebook: PHP, React(Javascript)
Oracle: Java

Out of six major tech companies, three of them use Java while one uses Python. Java was owned by Oracle and the language itself has been under heavy testing by the best developers around the world. There are billions of application made with Java. There is a saying that “Java is the new COBOL”, meaning that it’s to big to fail and everyone is depending on it.

Regarding the Java language itself I don’t have much complains, although the syntax are known as verbose. I would imaging it as a big heavy hammer which could smash whatever it want, however, only the brightest developers could maneuver it good enough to do that. It’s very powerful if given enough cpu/gpu power with its concurrency capabilities.

However, I hate Java’s framework. As mentioned earlier, I am a kind of developer who use library instead of writing from scratch. And there is a problem because there are too many different way to accomplish the same thing, with mind numbing XML configuration. Later they abandoned XML and went for annotation. The annotation came like magicians and did things without telling us the logic. For example, here is a snippet of spring configuration for security:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

    @Bean
    @Override
    public UserDetailsService userDetailsService() {
        UserDetails user =
             User.withDefaultPasswordEncoder()
                .username("user")
                .password("password")
                .roles("USER")
                .build();

        return new InMemoryUserDetailsManager(user);
    }
}

Nothing could be more vague each the phrase “enable web security”. What? How? I see some code relating to authorization with weird syntax. According to the API documentation:

Add this annotation to an @Configuration class to have the Spring Security configuration defined in any WebSecurityConfigurer or more likely by extending the WebSecurityConfigurerAdapter base class and overriding individual methods:

I know every word of this sentence, but when they combined, I don’t know what it is talking about. What is WebSecurityConfigurer? And what is WebSecurityConfigurerAdapter?

I had some experience with using Spring 3 and I only used it for Dependency Injection, Inversion of Control, etc. I really appreciate Spring for eliminating the boilerplate code for JDBC. But then again here came Spring Boot, and everyone is advised to use Spring Boot instead of normal Spring. Here we go:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {

            System.out.println("Let's inspect the beans provided by Spring Boot:");

            String[] beanNames = ctx.getBeanDefinitionNames();
            Arrays.sort(beanNames);
            for (String beanName : beanNames) {
                System.out.println(beanName);
            }

        };
    }

}

It didn’t look like what I was used to. Does it mean I have to abandon all of my work? According to the folks on internet, it seems Spring was too complicated so they created a framework FOR a framework!

Here I end all of my rants over Java, and if I have to, I would use J2EE over Spring, but I would like to avoid it all together.

 

It gets too long and I would continue the Python part next time.

 

Japanese Tokenizer – Design

 

I have drafted a sequence diagram for the application. Although I have hesitated between Java and Python, I have settled with Python. Because of the RESTful API for frontend, I have to consider authentication and I hate spring’s security module. I don’t like spring’s magic to begin with ( e.g: @AutoWired, @EnableWebdSecurity ), I prefer to have everything wired up by hand. It has becomes much more complicated over the tutorial on spring security. For example:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/", "/home").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }

I don’t like chained method calls and I do not appreciate that the guide didn’t explain how does this part works. What is and(), what is the logic behind these lines? What if I don’t want to use a form login? I have an API so I don’t need a form login. The code does not look like the kind of Java I know.

So I chose Python, although I have more experience with Java. ( I have coded with Python, but not with django, I expected it’s trivial because of the small application )

I have been a backend developer for various project and seldom code frontend stuff. But if I have to make an web application, I would have to take care of frontend + backend. Please excuse me if I make horrible mistake in web design.

Frontend: A static page with javascript ( ReactJS )

Backend: Python Django

Security for the RESTful API: Http Basic authentication over HTTPS

I only have time to code it in Saturday and Sunday because I couldn’t focus after a full day work. For development, I prefer to do it on a VPS like digitalOcean because I don’t want to mess with my pc, however, it is too expensive to spin a droplet just for a day’s coding and paying for the whole month. I am looking in to Amazon AWS but I couldn’t get the ssh working. I use to code on digitalOcean and it’s much easier to connect with ssh. Actually this blog is hosted on a VPS of digitalOcean.

Let’s continue next time.

Project I have in mind – (2) Weather forecast accuracy tool

Photo by Craig Whitehead on Unsplash

I have another project in my mind, I want to obtain everyday weather forecast data from Hong Kong Observatory. My original idea was to provide a chart with what kind of clothe to wear in different temperature down to exact degree, but I have given it up because I don’t remember what do I wear in different temperature. I might have to conduct a survey for that. I might come back for it later.

My current objectives is to gather everyday weather forecast data, and cross check them later when the day passed, in order to know whether HKO is accurate.

This is an example of the forecast:

Date/Month 7/8 (Tuesday)
Wind: East force 2 to 3.
Weather: Very hot with sunny periods, a few showers and
isolated thunderstorms.
Temp Range: 28 - 33 C
R.H. Range: 65 - 95 Per Cent

I could easily classify them into member of a java class, scrape the data, and save into database.

 

I have obtained a piece of permission from HKO:

Dear Mr. Lam,

Thank you for your your submitting the electronic form of request for authorization to re-disseminate the information from Hong Kong Observatory website on 29 July 2018.

The Hong Kong Observatory hereby grant to “LAM WAI MAN” free authorization to reproduce or re-disseminate weather information of HKO website detailed in the Annex as listed below.

1. Such information is for NON-COMMERCIAL use (i.e. not for selling or exchange for benefit, gain, profit or reward in this context).

2. Acknowledgement is given to the Hong Kong Observatory as the source of information.

3. Such information must be reproduced accurately.

For the other conditions of the authorization,ย  please visit the link below:

http://www.hko.gov.hk/appweb/applink.htm

Note:

All web contents (including the format of HTML files, images, hyperlinks, Javascript codes and etc) of the HKO websites (including its mobile version, text-only version , RSS and etc.) are subject to change without prior notice to the authorized persons or organizations.

Notices to authorized persons shall be posted in the following webpage:

http://www.weather.gov.hk/appweb/noticeboard.htm .

Regards,

TH Chow
Hong Kong Observatory

Now I have the permission from HKO to scrape their website, I could work on it. But I prefer to do it after the Japanese Tokenizer. I would come up with a design first though.

Project I have in mind – (1) A Japanese text tokenizer online

Photo by Charles Deluvio ๐Ÿ‡ต๐Ÿ‡ญ๐Ÿ‡จ๐Ÿ‡ฆ on Unsplash

 

I had attended Japanese classes recently and found a piece of opensource software called MeCab ( http://taku910.github.io/mecab/ ) which was developed by Kyoto University. It is an offline software so one would have to install it on computer. I want to put it online so that it is accessible by other people without installing the software.

Here is an example of using MeCab to tokenize Japanese text:

% mecab
ใ™ใ‚‚ใ‚‚ใ‚‚ใ‚‚ใ‚‚ใ‚‚ใ‚‚ใ‚‚ใฎใ†ใก
ใ™ใ‚‚ใ‚‚  ๅ่ฉž,ไธ€่ˆฌ,*,*,*,*,ใ™ใ‚‚ใ‚‚,ใ‚นใƒขใƒข,ใ‚นใƒขใƒข
ใ‚‚      ๅŠฉ่ฉž,ไฟ‚ๅŠฉ่ฉž,*,*,*,*,ใ‚‚,ใƒข,ใƒข
ใ‚‚ใ‚‚    ๅ่ฉž,ไธ€่ˆฌ,*,*,*,*,ใ‚‚ใ‚‚,ใƒขใƒข,ใƒขใƒข
ใ‚‚      ๅŠฉ่ฉž,ไฟ‚ๅŠฉ่ฉž,*,*,*,*,ใ‚‚,ใƒข,ใƒข
ใ‚‚ใ‚‚    ๅ่ฉž,ไธ€่ˆฌ,*,*,*,*,ใ‚‚ใ‚‚,ใƒขใƒข,ใƒขใƒข
ใฎ      ๅŠฉ่ฉž,้€ฃไฝ“ๅŒ–,*,*,*,*,ใฎ,ใƒŽ,ใƒŽ
ใ†ใก    ๅ่ฉž,้ž่‡ช็ซ‹,ๅ‰ฏ่ฉžๅฏ่ƒฝ,*,*,*,ใ†ใก,ใ‚ฆใƒ,ใ‚ฆใƒ
EOS

Because Japanese text does not have a space between each word, you couldn’t judge which one is a word. For example, this sentence was composed of 8 characters of ใ‚‚ ( mo ), it is so complex for average learner and even google translate couldn’t understand it:

Actually ใ™ใ‚‚ใ‚‚ใ‚‚ใ‚‚ใ‚‚ใ‚‚ใ‚‚ใ‚‚ใฎใ†ใก ( sumomomomomomomomonouchi ) translate to “Both plum and peach are a kind of prunus ). From wikipedia: “Prunus is a genus of trees and shrubs, which includes the plums, cherries, peaches, nectarines, apricots, and almonds. ” The actual sentence structure is this – “ใ™ใ‚‚ใ‚‚ใ€€ใ‚‚ใ€€ใ‚‚ใ‚‚ใ€€ใ‚‚ใ€€ใ‚‚ใ‚‚ใ€€ใฎใ€€ใ†ใก” ( Plum and peach and ( is ) peach of type ).

What I want to do now is to provide this Japanese tokenizer online, in a similar UI like google translate, in which there are two textbox, you put in words in left-hand side and get the result from the right-hand side.

It would involve two components, a frontend UI powered by a web server, with Semantic UI or JQueryUI, and a backend RESTful API written by Java or Python. I still haven’t decide to code it in Java or Python yet.

Let’s continue later.

What I do in my company

Cyberport, where I started working

I have been working for the same company for quite a long time( 5 + 1.5 year with a short duration out of the company ). I have to do whatever the SSAs ( Senior System Analyst ) want me to do. When I just started out, he want me to code some COBOL, which they had a lot in the mainframe. I had only learnt C and Java in university, so something like COBOL was really annoying ( just that ).

 

Here is a sample I took from the web ( University of Lemerick : http://www.csis.ul.ie/cobol/examples/default.htm#SimplePrograms ) :

$ SET SOURCEFORMAT"FREE"
IDENTIFICATION DIVISION.
PROGRAM-ID.  SeqReadNo88.
AUTHOR.  Michael Coughlan.
* An example showing how to read a sequential file without
* using condition names.
* See SeqRead.CBL for the definitive example.


ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
    SELECT StudentFile ASSIGN TO "STUDENTS.DAT"
		ORGANIZATION IS LINE SEQUENTIAL.

DATA DIVISION.
FILE SECTION.
FD StudentFile.
01 StudentDetails.
   02  StudentId       PIC 9(7).
   02  StudentName.
       03 Surname      PIC X(8).
       03 Initials     PIC XX.
   02  DateOfBirth.
       03 YOBirth      PIC 9(4).
       03 MOBirth      PIC 9(2).
       03 DOBirth      PIC 9(2).
   02  CourseCode      PIC X(4).
   02  Gender          PIC X.

PROCEDURE DIVISION.
Begin.
   OPEN INPUT StudentFile
   READ StudentFile
      AT END MOVE HIGH-VALUES TO StudentDetails
   END-READ
   PERFORM UNTIL StudentDetails = HIGH-VALUES
      DISPLAY StudentId SPACE StudentName SPACE CourseCode SPACE YOBirth
      READ StudentFile
         AT END MOVE HIGH-VALUES TO StudentDetails
      END-READ
   END-PERFORM
   CLOSE StudentFile
   STOP RUN.

We had a lot of flat file which were fixed length, delimited by each fields’ length. Now I primarily code Java, but I remember COBOL has verbose syntax and wasn’t as powerful as modern day programming language. I even had to implement my own function to reverse a string!

I have coded C in their roaming system and it wasn’t standard C, but a ASN.1 C from OSS Nokalvaย  ( http://www.oss.com/asn1/products/asn1-c/asn1-c.html ). I did an version upgrade for their TAP3 file ( a file standard for roaming partners to exchange customer usage data ) exchange program, which was required by GSMA ( https://www.gsma.com/ ). I had chewed the whole TAP3 specification upgrade difference and changed the programs accordingly.

Now I code java for different system in this company. Recently I am working on plugging an auto-pay system into a brand new system provided by our partner for the digital transformation project of our company. ( They want to replace the old mainframe system written with COBOL )

Let’s continue later.

Why I started this blog

Photo by Clรฉment H on Unsplash

I have been a software developer in Hong Kong for almost 8 years. Software developers are sought-after right now but I did not intend to jump for a higher salary. I am the ordinary developer who fix stuff quietly over the years. I have seen juniors who came in after me, leave sooner then me.

I haven’t maintained a solid profile on the internet, I didn’t have the need and do not have the time after work. I could not put programs I worked in company online just to show off, but I am tired as ____ after work. I want a work life balance and my current job somehow gives me this.

A dear friend asked me if I want to come over to Berlin, where I once lived and like. His/Her friend pointed out my profile is vague, I hate it and I really want to come over so I started working. I would show some computer stuff. It’s going to be simple but could shows I have minimal qualification for a developer. I am going to orchestra the whole thing including infrastructure, development and deployment.

I would update this site slowly, with random post. I would document my journey to make this work of proof.

P.S. Information for English speaker, The domain of this blog, rayentwickler is composed of Ray ( my name ) and Entwickler, which is a German word for Developer.