Best Practice of Wrting Stack in Java

In the past I always used Stack class from Java API to represent a stack. However, it is not recommended in the industry because Stack is thread-safe, which will cause overhead. Instead, industry usually uses ArrayDeque to implement a stack.

Initialization Old Way

Stack<T> s = new Stack<>();

Initialization New Way

Deque<T> stack = new ArrayDeque<>();

Compare of the methods a stack can have

You should use the methods under ArrayDeque to mimick a stack

Using Stack Using ArrayDeque
push(E e) offerLast(E e)
pop() pollLast()
empty() isEmpty()
peek() peekLast()

I personally like to use xxxLast() methods to mimick push, pop, peek, but you can also use the same set of xxxFirst() to mimick these actions. But, do please be consistency.

Advertisements

Head First OOAD: Chapter 1 Well Designed Apps Rock

Chapter 1 Well Designed Apps Rock

Questions before reading this chapter

 

Goal: Know how to write good software after this chapter — Can I achieve this?

What properties shall a good software have?

  1. Satisfy customers’ need
  2. Apply OO principles and flexibility
  3. Strive for a maintainable and reusable design

 

What concepts are being repeated in this chapter?

What is a good software?

Satisfy customer

Apply OO principles (in this chapter: encapsulation and delegation — separation of concerns) Then what other principles I can think: inheritance, polymorphism

Use design pattern to write maintainable and reusable code

 

What are the Bullet Points of this chapter? Excerpt the ones I think useful for me.

Encapsulation: breaking an application up into logical parts

Delegation: giving another object the responsibility of handling a particular task.

Beginning a project by figuring out what customer wants → refining the design to make it flexible → apply design patterns to improve my design further

 

The evolution of the design of the guitar inventory app

1st stage

 

Guitar class

serialNumber: String

price: double  

builder: String

model: String

type: String

backWood: String

topWood: String

 

Methods — only price needs both setter and getter methods, others just need setter methods. Why?

 

Inventory class

guitars: List

 

addGuitar(String, double, String, String, String, String, String): void

getGuitar(String): Guitar

search(Guitar): Guitar

 

2nd stage

 

Guitar class

serialNumber: String

price: double  

builder: Builder

model: String

type: Type

backWood: Wood

topWood: Wood

 

Inventory class

guitars: List

 

addGuitar(String, double, Builder, String, Type, Wood, Wood): void

getGuitar(String): Guitar

search(Guitar): List<Guitar>

 

Reasons of transition: (1) those properties (builder, type, back and top wood) have a small finite set of fixed values; (2) try to ditch String comparisons. (3) when searching guitar, we want a matched list of guitars rather than returning one single matched guitar.

 

3rd stage:

 

Guitar

serialNumber: String

price: double

spec: GuitarSpec

 

GuitarSpec

builder: Builder

model: String

type: Type

backWood: Wood

topWood: Wood

 

Inventory class

guitars: List

 

addGuitar(String, double, GuitarSpec): void

getGuitar(String): Guitar

search(GuitarSpec): List<Guitar>

 

Reasons of transition: a client doesn’t provide every single detail of a guitar object to search for his preferred guitars, instead, he just provides a guitar spec for the search criteria.


Learned: delegation — split the current object Guitar into Guitar and GuitarSpec

When do we wanna split an object type? — 3 ways to help determine: 1. Objects should do what their names indicate; 2. Each object shall represent one single concept; 3. Unused properties indicates this object needs to give something away.

Also separating GuitarSpec out of Guitar object reveals a concept of encapsulation: protecting information in one part of your application from the other parts of your application.

 

4th stage:

GuitarSpec class added a method called matchSpec(GuitarSpec otherSpec) — which allows comparing spec of two guitars, and will be helpful to the search(GuitarSpec spec) function defined in Inventory class;

Add another property related to GuitarSpec — numOfStrings

 

Reasons of transition: indicates once separating concerns between Guitar and GuitarSpec, adding numOfStrings property only affects GuitarSpec class; matchSpec() is a API function public to Inventory or other classes to use.

 

Code: Guitar Inventory App 

I integrated the code presented in Chapter 1 and tried to apply Java 8 on it 🙂

朋友圈两位朋友回国的消息

Overview

今早起床看朋友圈以及校友群,恰巧看到了两位微信朋友回国工作的消息。一位是我研究生时代一起熬夜码过代码的程序媛队友,她发到票圈的状态是她在三藩机场临行前拿着机票自信微笑的照片,配文是感谢送机的朋友,感谢在美帝的4年帮助过她的同仁们。另一位则是我的高中学姐,生物医药科研领域的,已经回到了国内,准备找工作面试。

选择

序媛队友是15年毕业的,而后在美国Top的科技大公司工作。虽然我们联系的不多,但之前看过她的一条Ins状态,是在大魔都游玩,并赞赏大魔都的发展以及向往有一天可以在大魔都工作。我猜想她对上海这个城市所展现的活力、行业的发展、以及给予年轻归国人士的机会有一定的调研,权衡前景与当下在硅谷的工作,或加上她personal的其他因素考量,而做出了回国的决定。

相比于队友,学姐则是在美国13年了,国内Top 2的生物相关专业毕业,一直从事科研工作。不过,学姐本身1️⃣来美国,就没有抱要在美国申绿卡定居的想法。现在,随着特制朗朗上口普洱茶的在美执政,许多科研项目的经费被裁撤,而另一方面,🇨🇳大陆的研究经费却充裕,许多高校与科研机构广纳人才。学姐的选择倒颇有顺势而为之感。

我想,学姐也是我朋友圈中第一个用满两次H1B签证但不申请美国绿卡的第一位中国人。印度朋友就不算啦,像我前公司的经理,他们就是拿H1B来美国工作赚美刀的,根本就没有在美定居的想法,因为他们在印国自身和家庭的条件都很好呀。

还是选择

人生本来就是个不断做选择的决策过程。又没有什么人规定我一定要在哪儿工作,一定要做什么行业。不过,无论在哪里,都要好好工作,好好生活。

A Concrete Example using Singleton

Last time we talked about Singleton design pattern, today we can take a look of a concrete example using singleton, which is server side cache — cache the data a system grabs from DB and stores it on the server side.

Take university registrar system again. Let’s say in the Computer Science department, we have those user accounts set up for professors and professors have different titles, for instance, one professor may have titles like assistant professor, associate professor, and professor. Now we wanna display title information for each professor’s profile page. Because a professor’s title information change is rare or we say infrequent, this piece info can be cached on the server side, to avoid the system constantly calling getTitle() to hit DB when a professor’s profile page reloads.

Assume title is associated with user id, and we already have a lookup table in DB like

UserId TitleID
123 1
124 2
125 1
126 3

then we can use a HashMap typed variable, which should only be initialized once, to save the userId-title mapping.

===Think===
Wny the userId-title mapping table should only be initialized once?

That said, we can apply Singleton pattern over the userTitleDict variable, if it already has value, we return it; otherwise we call a method to pull data out of DB.

static class UserTitleCache {
  private static HashMap<int, List<int>> userTitleDict = new HashMap<int, List<int>>();

  public static HashMap<int, List<int>> getUserTitleDict() {
    if (userTitleDict == null || userTitleDict.size() == 0) {
      updateUsersTitlesCache();   
    } 
    return userTitieDict;
  }

  private static void updateUsersTitlesCache() {
    //write data access code to call db to update userTitleDict obj
  }
}

Surely it differs from the Solution I presented last time; here I don’t write a private constructor, because we do singleton over HashMap typed userTitleDict object, not the UserTitleCache class. But it is also right if we put private UserTitleCache() {} cuz this class itself should be unique across the system. Well this said, class UserTitleCache better be a static class.

But the code above has a defect — the cache object would never be updated if the system is continuously functioning. We wanna add a refresh interval to enforce updating the userTitleDict cache object every 60 minutes. Then

static class UserTitleCache {
  private const int Threshold = 60;
  private static DateTime _lastRefresh = DateTime.MinValue;
  private static HashMap<int, List<int>> userTitleDict = new HashMap<int, List<int>>();

  public static HashMap<int, List<int>> getUserTitleDict() {
    if (_lastRefresh.AddMinutes(Threshold) < DateTime.Now || userTitleDict == null || userTitleDict.size() == 0) {
      updateUsersTitlesCache();   
    } 
    return userTitieDict;
  }

  private static void updateUsersTitlesCache() {
    //write data access code to call db to update userTitleDict obj

    //After updating the cache object, don't forget
    _lastRefresh = DateTime.Now;   
  }
}

Sorry about the Java C# mingled code above cuz I have been writing C# for quite a while and being lazy to lookup all corresponding method names from Java API..

Write a Singleton Patten

Lint 204

A singleton pattern class should provide only one instance for other classes to use. In order to achieve this goal, that class should satisfy the following 3 criteria:

  1. should not be able to create more than one instance of this class
  2. should create exactly one instance of this class
  3. should provide a public method to return that exact one instance

In Java, Criteria 1 can be achieved by setting constructor private, 2 can be achieved by define a member variable of this class type and initialize it, 3 can be achieved by writing a public method. Then, what about the following solution:

class Solution {
    private Solution s = new Solution();
    private Solution() {}
    
    public Solution getInstance() {
        return s;
    }
}
/* The solution above is Incorrect!! */

The “solution” above has a problem: since other classes are not able to create an instance of that Solution class, how can we invoke getInstance() in Solution class??? So, intuitively we can try class function approach — converting getInstance() into a static method, then, the variable returned from this method should also be static. So, the correct solution is

class Solution {
    private static Solution s = new Solution();
    private Solution() {}
    
    public static Solution getInstance() {
        return s;
    }
}

That’s it!

=====Think=====

Assume I have the following Config class, without removing any lines of code, how can we turn it into a singleton class?

class Config {
    private string configString;
    public setConfigString(string configString) {
        this.configString = configString;
    }
    public getConfigString() {
        return configString;
    }
}

My solution

class Config {
    private string configString;
    
    // add the following 3 pieces of code
    private static Config config = new Config();
    private Config() {}
    public static Config getInstance() {
        return config;
    }

    public setConfigString(string configString) {
        this.configString = configString;
    }
    public getConfigString() {
        return configString;
    }
}

Then if I have a TestDriver class

class TestDriver {
    public static void main(String[] args) {
        Config config1 = Config.getInstance();
        Config config2 = Config.getInstance();
        config1.setConfigString("Benben");
        config2.setConfigString("PearSweetie");
        System.out.println(config1.getConfigString());
        System.out.println(config2.getConfigString());
    }
}

=====Think=====
What are the two println results after executing the code above?

Use ui-router resolve to provide previous state for a 2nd level page

resolves is ui-router’s way to provide values to the different controllers it manages.

Assume the following scenario:
We have a site listing student projects, and each project can be decomposed into several tasks. Now we already have projects page, tasks page, and project-details page constructed. A project Id on projects page or a task Id on task page can direct the user into corresponding project details page.

So, in this scenario, projects and tasks page would be the first level page and project details page would be the 2nd level page. We would like to record the previous state of the 2nd level page so once we wanna use a close button to send user back to the 1st level page, we need to know which 1st level page it is for the currently reached 2nd level page.

That said, we may want to construct the ui-router state for project details as follows:

angular.module('myApp')
  .config(function($stateProvider) {
    $stateProvider
      .state('projects.details', {
	    url: '^/projects/:id',
	    views: {
		'@': {
			templateUrl: 'app/Projects/ProjectDetails.html',
			controller: 'ProjectDetailsCtrl',
			controllerAs: 'projectDetailsCtrl',
			resolve: {
				previousState: function (ChannelService) {
					return ChannelService.GetCurrentState();
				}
			}
		}
	   }
    })
})

The solution above is correct but I encountered 2 pitfalls:
1. ChannelService rather than channelService
because in my current coding style for angular controller, I have

ProjectDetailsController.$inject = ['ProjectService'];
function ProjectDetailsController(projectService) {
  var vm = this;
}

I have a way to inject a service’s actual capitalized name ‘ProjectService’ on the first line and its alias lower-cased ‘projectService’ on the second line. However, since service can be directly injected into a state of ui-router config file, I should inject the service’s actual name cuz no way for me to create an alias for it at that parenthesis in app.config
2. In order to use the previousState being resolve(ed) for state ‘project.details’, we need to inject previousState into ProjectDetailsController, so the complete writing should be

ProjectDetailsController.$inject = ['ProjectService', 'ChannelService', 'previousState'];
function ProjectDetailsController(projectService, channelService, previousState) {
  var vm = this;
}

Here I’d like to elaborate a little about how I wrote the GetCurrentState() in ChannelService. Unlike using a global object Mood or Diet and expose them, I set the currentState variable in ChannelService like a private static variable in Java, which doesn’t get exposed. This is because currentState is based on need-to-use requirement, it is now only used for the resolve function for project.details state in app.config; that’s it! No need to expose it and being used for almost every angular controller. So,

var currentState = null;
var setCurrentState = function ($state) { /* $state is passed from those angular controllers in which channelService.SetCurrentState() being called */
	currentState = $state.current.name;
}
var getCurrentState = function() {
	return currentState;
}
/* function setCurrentState() and getCurrentState() are exposed */

And for each page that can reach to project details, we call channelService.SetCurrentState($state) when that page loads.

===== Update 1 =====
The solution above “Update 1” is tedious cuz it requires each page that can possibly link to project-details page to load channelService.SetCurrentState($state) first, which means those pages should have injected channelService and $state prior to this load.
Since our requirement is that obtain the previous state for project-details page only, so to clean the code, we 1st remove all channelService.SetCurrentState($state) from those controllers, 2nd for channelService.js

/* inject $state to this channelService at the beginning */
/* we don't need var currentState = null; or setCurrentState function */
var getCurrentState = function() {
	return $state.current.name;
}
/* function getCurrentState() is exposed */

Then, since the only change we made to channelService is adding a getCurrentState(), and based on the property of service injection in app.config, I found that I could just don’t do apply any change to channelService.js (reverse this file back to what it was), and for the resolve part of the state ‘projects.details’

resolve {
  previousState: function ($state) {
    return $state.current.name;
  }
}

This greatly reduced the code base. However, this brings in an issue to our business requirement, which I will explain in “Update 2”

===Update 2===
Think about that if I get to page http://localhost:8080/#/projects/112 then page http://localhost:8080/#/projects/113, on projects-113 page I close it so I goto page 112 again. Then what is the previous state for page 112, isn’t it page 113, so the code above would end up between 112 and 113 forever!!!

So we want ok for those 2nd level page, no matter what, when user close it, goto the 1st level page, which is either projects page or students page.

That said, in channel service, we can have

var prevPageState = null;
var pageStateNames = ['projects', 'students'];
var setCurrentState = function() {
	if (pageStateNames.indexOf($state.current.name) > -1)
		prevPageState = $state.current.name;
}
var toPrevPageState = function () {
	if (!!prevPageState) {
		$state.go(prevPageState);
		return;
	}
	$state.go('projects'); // assume user wasn't on either projects page or students page, we default it to be projects page

and in Routes.js

resolve: {
	prevState: function (ChannelService) {
		return ChannelService.SetCurrentState();
	}
}

===Update 3===
Update 2 is much better, but writing an array of 1st level page names in channelService.js is still tedious, what if I have 100 1st level pages…
A cool way to handle it would be add a parameter in those states of 2nd level pages. like params: {is2nd: true}, and then the setCurrentState function in channelService.js can be written as

var prevPageState = null;
//NO more page name array
var setCurrentState = function() {
	if (!$state.params.is2nd) //meaning current state is a 1st level page state
		prevPageState = $state.current.name;
}

===Think===
OK, the tweak of this problem is done. For now just one issue: since we have

resolve: {
	prevState: function (ChannelService) {
		return ChannelService.SetCurrentState();
	}
}

in the appRoutes.js file which defines all ui-router states, we cannot inject a service at the beginning of .config() part, and directly setting ChannelService as a parameter in the function of resolve leads us loosing the poser of injecting service using ['ChannelService', fuction (channelService){ }] format. Loosing the array format injection has no harm in code execution but would get into trouble if using javascript uglify.

Cleverly use newVal and oldVal in $scope.$watch

Angular 1 provides a $watch function for the root scope $scope, with its basic syntax as $watch(watchExpression, listener, [objectEquality]); Though the example from Angular 1’s official site already provides some code snippet like

scope.$watch(
  // This function returns the value being watched. It is called for each turn of the $digest loop
  function() { return food; },
  // This is the change listener, called when the value returned from the above function changes
  function(newValue, oldValue) {
    if ( newValue !== oldValue ) {
      // Only increment the counter if the value changed
      scope.foodCounter = scope.foodCounter + 1;
    }
  }
);

I didn’t use oldValue much. For most past time, I found using

scope.$watch(function(){
   return food;
}, function(newValue) {
    if (!!newValue) {
      //do something
    }
  }
);

was sufficient, until I met the following request.

Goal: /* we want vm.StudentName be filled with data from DB first,
then once the name being selected in the selective dropdown is changed, we want another variable vm.Editables.Student.IsStuLeader default to be false */

Analysis: vm.StudentName is by default not null cuz it is filled with StudentName data provided from DB; this indicates the value being watched has a non-null old value. When writing the $scope.$watch, I should pick the version with both newVal and oldVal version.

My 1st tweak was

$scope.$watch(function () {
	return vm.StudentName;
}, function (newVal, oldVal) {
	if (newVal != oldVal)
		vm.Editables.Student.IsStuLeader = false;
});

My first tweak could be correct if vm.StudentName was a primitive string in this problem, however, it was an object with both Name and IsStuLeader properties. That said, when I closed the UI for selecting a student name, I ended up with something like

newVal = Object {Name: "Xian Lin", IsStuLeader: true}, oldVal = Object {Name: "Xian Lin", IsStuLeader: true}

Though the contents of newVal and oldVal were the same, these two were two distinct objects with their own memory location. This triggered an old principle: do comparisons using primitive types.

In this example, I actually just need to compare that if the Name properties were equal in content for both newVal and oldVal, so the 2nd tweak became

$scope.$watch(function () {
	return vm.StudentName;
}, function (newVal, oldVal) {
	if (!!newVal && !!oldVal && newVal.Name != oldVal.Name) //observe the Name change of the selected vm.StudentName object
		vm.Editables.Student.IsStuLeader = false;
});

which resolved the issue.

Key Point
1.oldVal being watched is by default not null (ie. provided from DB), try the newVal and oldVal format of $scope.$watch
2.No matter for what language, comparisons should be done by comparing primitive types

Side Note:
JavaScript has both primitive and object Strings, surely compare using primitive string.

SQL Server 小技巧

1.Escape Character
Escape in SQL Server is brackets []
ie. Escape all usernames with “_NY” suffix, then

Username not like '%[_]NY' --where % is the wildcard
	--indicating whatever in front of the underscore sign

2.Variablize @top

select top 1 studentId, studentName from Student

If we don’t alwasy select top one row of Student table, we can variablize it, by declaring something like

declare @top int = case when @IsSelectingTopOne = 1 then 1 else 100 end

first. And then

select top @top studentId, studentName from Student

3.Convert a pass in variable input from null into empty string

SET @Input = LTRIM(RTRIM(ISNULL(@Input, '')))

4.Transform a string column into a bit column

SET case when s.StudentLeaderId IS NULL then 0 else 1 end as IsStuLeader
FROM Student s

5.Cast bool into int

MAX(CAST(task.IsFinished as int)) as IsFinished

6.Use Is NULL instead of ‘= NULL’ in SQL Server

‘Is Null’ at least returns something while ‘= NULL’ returns nothing. Ok, a joke, actually, ‘Is Null’ is the right syntax to compare a string/int value  with NULL in SQL Server.

7.After If condition, if you wanna reset a bunch of variables, please include these variables within BEGIN END block

错误(Incorrect Way):

IF @CanEditStudent = 0
SET @FirstName = NULL
SET @LastName = NULL
-- this would always set @LastName to be NULL, cuz IF only governs the next line.

正确(Correct Way):

IF @CanEditStudent = 0
BEGIN
 SET @FirstName = NULL 
 SET @LastName = NULL
END

[翻译] Bedi Egilmez: Who do the Turks think is their best and most reliable neighbor?

Source

问题:哪个国家是土耳其人最值得信任的邻居?

从政治角度讲,土耳其与它的邻国甚至区域强权如以色列还有俄罗斯皆有不少问题。历史上的问题,比如伊斯坦布尔屠杀塞浦路斯争议亚达那屠杀则更为严重得多。但我的回答不谈政治。

我有不少来自周边邻国,比如格鲁吉亚、伊朗、希腊、保加利亚、塞浦路斯还有阿塞拜疆的朋友。塞浦路斯和土耳其并无实际定型的国界,但我还是把它算在内了,毕竟它离我爸爸的老家只有150公里远。我在海外(土耳其国以外)同大部分来自这几个国家的人居住;可以说,我的主要伙伴都来自塞浦路斯、希腊还有阿塞拜疆。

我感到自己同希腊文化更贴近,因为许多事物都是那么得相似。我的塞浦路斯朋友给我分享过他奶奶做的萨尔玛(Sarma),一种由葡萄、卷心菜、唐莴苣叶包起来的碎肉饼,我的希腊朋友还邀请过我到他家做客,并让我品尝了Bifteki肉饼

我嘛,也曾带他们到土耳其餐厅喝拉克酒,

吃Meze大餐

好吧,说了这么多都在讲吃的。但请你相信我,我们还有许多共通的理念,不仅仅是食物 🙂

编按:希土两族的问题由来已久,但这位哥们的回答会给人一点温馨的感觉。另外,这也印证了超级演说家第三季选手许吉如演讲《人之常情》5:15–6:46的内容。