ต่อข้อความ format ข้อความ หรือ output ค่าของตัวแปร ออกมาด้วย string interpolation ในภาษา TypeScript (JavaScript), Java, Groovy และ C#
ปกติเพื่อนๆ ต่อข้อความ string กันยังไงครับ ยังมีใครใช้วิธี ต่อข้อความด้วย + operation อยู่ไหม วันนี้ผมจะขอแนะนำตัวอย่างง่ายๆ ในการต่อข้อความ string ด้วยวิธีการที่เรียกว่า string operation ที่ช่วยให้ code เราอ่านง่ายขึ้น ในตัวอย่างนี้มี code ตัวอย่างในภาษา
- TypeScript ที่ใช่แบบเดียวกับ JavaScript
- Java
- Groovy
- C#
ในตัวอย่างมี code ในทำนองเดียวกัน คือมี class Product ที่เก็บข้อมูลสินค้า และเขียนในรูปแบบของ unit test เพื่อ output ข้อความว่า product Basic Programming costs 499.99 is added on 2018-Feb-05
ด้วย string interpolation เรามาเริ่มกันเลยดีกว่าครับ
string interpolation ใน TypeScript/JavaScript
Product.ts
export default class Product {
private _name: string;
private _createDate: Date;
private _price: number;
get name(): string {
return this._name;
}
set name(value: string) {
this._name = value;
}
get createDate(): Date {
return this._createDate;
}
set createDate(value: Date) {
this._createDate = value;
}
get price(): number {
return this._price;
}
set price(value:number){
this._price = value;
}
}
ProductSpec.ts
import * as moment from 'moment';
import Product from '../../string-interpolation/Product';
describe('string interpolation return correct formatted string', function () {
it('return correct full name', () => {
//given
let product = new Product();
product.name = 'Basic Programming';
product.price = 499.99;
product.createDate = new Date(2018, 1, 5); //month value in JavaScript starts from 0
//when
//format date with moment js
var formattedString =
`product ${product.name} costs ${product.price} is added on ${moment(product.createDate).format("YYYY-MMM-DD")}`;
//then
expect(formattedString).toBe('product Basic Programming costs 499.99 is added on 2018-Feb-05');
});
});
string interpolation ใน Java และ Groovy
Product.java
package com.codesanook.examples.stringinterpolation;
import java.math.BigDecimal;
import java.util.Date;
public class Product {
private String name;
private Date createDate;
private BigDecimal price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
ProductTests.java
package com.codesanook.examples.stringinterpolation.tests
import spock.lang.Specification
import com.codesanook.examples.stringinterpolation.Product
import java.text.SimpleDateFormat
class ProductTests extends Specification {
def "string interpolation Java style should return correct formatted string"() {
given:
Product product = new Product();
product.setName("Basic Programming");
product.setPrice(499.99);
Date date = new GregorianCalendar(2018, 1, 5).getTime(); //month value in Java starts from 0
product.setCreateDate(date);
when:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MMM-dd", Locale.ENGLISH);
String formattedDate = simpleDateFormat.format(product.getCreateDate());
String formattedString = String.format("product %s costs %.2f is added on %s",
product.getName(),
product.getPrice(),
formattedDate);
then:
formattedString == "product Basic Programming costs 499.99 is added on 2018-Feb-05";
}
def "string interpolation Groovy style should return correct formatted string"() {
given:
def date = new GregorianCalendar(2018, 1, 5).getTime()
//initialize property from constructor
def product = new Product(name : "Basic Programming", price : 499.99, createDate : date)
when:
def simpleDateFormat = new SimpleDateFormat("yyyy-MMM-dd", Locale.ENGLISH)
def formattedDate = simpleDateFormat.format(product.getCreateDate())
def formattedString = "product ${product.name} costs ${String.format('%.2f',product.price)} is added on $formattedDate"
then:
formattedString == "product Basic Programming costs 499.99 is added on 2018-Feb-05"
}
}
string interpolation ใน C#
Product.cs
using System;
namespace CodeSanook.Examples.CSharp.StringInterpolation
{
public class Product
{
public string Name { get; set; }
public DateTime CreatedDate { get; set; }
public decimal Price { get; set; }
}
}
ProductTests.cs
using CodeSanook.Examples.CSharp.StringInterpolation;
using System;
using Xunit;
namespace CodeSanook.Examples.CSharp.Tests.StringInterpolation
{
public class ProductTests
{
[Fact]
public void GetFullNameWithReflection_ValidPropertyValues_ReturnCorrectFullName()
{
//arrange
var product = new Product()
{
Name = "Basic Programming",
Price = 499.99M,
CreatedDate = new DateTime(2018, 3, 5)//in .NET month value starts from 1
};
//act
var formattedString =
$"product {product.Name} costs {product.Price:0.00} is added on {product.CreatedDate:yyyy-MMM-dd}";
//assert
Assert.Equal("product Basic Programming costs 499.99 is added on 2018-Mar-05", formattedString);
}
}
}
download source code จาก github ได้เลยครับ
Be the first comment