TECH

June 12, 2024

Exploring the role of "Cushion Words" in Japanese Language

Have you ever heard of the Japanese word "cushion words"? Today, I would like to introduce some of the politest Japanese words, "cushion words".

1. What is "cushion words"? 

“Cushion words” are also called business pillow words, and by adding them as an introduction to a conversation, they have the effect of softening the impression that the words convey to the other person than if they were said directly. It is just like a “cushion” to soften the impact of words.

You can also express your feelings of “sorry” (申し訳ない) or “I may be a nuisance to the other person, but…” (もしかしたら相手としては迷惑かもしれないけれど…) in a way that shows compassion for the other person.

2.Scenes and effects where "cushion words" should be used

It is mainly used in situations where you want to make a “request”, “refusal”, or “opinion/refutation”. By using a variety of words and using them appropriately, you should be able to express your words in a way that touches the other person’s heart. It also has the effect of making it easier to convey to the other person that “You are an important person who I want to take care of”.

You can use “cushion words” when talking to customers, seniors, superiors, etc.

When making an offer or asking something, when offering something that you don’t know if the other person needs, or when you want to ask something, cushion words such as “If you don’t mind” (もしよろしければ), or “If it’s not a problem” (差し支えなければ) are used. This phrase is useful when you want to extract information from the other party during a business negotiation or meeting, or when making a proposal.

The cushion words are used not only in face-to-face communication, but also in emails and documents where it is difficult to convey nuances and feelings. This will avoid giving the impression that you are bossy or one-sided, and it will show that you are considerate.  Cushion words are essential for building trusting relations.

Here are some cases to use cushion words.

a. When asking something.

「お尋ねしてよろしいでしょうか」 (May I ask?)

「失礼ですが」 (Excuse me)

「差し支えなければ」 (If it’s not a problem)

「お教えいただきたいのですが」 (I would like to ask you to tell me.)

Ex:失礼ですが、お名前をフルネームでお聞かせいただけますでしょうか。

b. When requesting something.

「恐縮ですが」 (I’m sorry)

「ご面倒をお掛けしますが」 (I apologize for the inconvenience.)

「ご迷惑とは存じますが」 (I understand this is nuisance.)

「こちらの都合で恐れ入りますが」 (We apologize for the inconvenience.)

Ex:ご面倒をお掛けしますが、お引き受けいただけないでしょうか。

c. When you want cooperation.

「恐れ入りますが」 (Excuse me)

「お手数をおかけしますが」 (I apologize for the inconvenience)

「ご面倒をおかけします」 (I'm sorry for the inconvenience)

「お忙しいところ恐れ入りますが」 (I apologize for the inconvenience, but I'm busy)

Ex:恐れ入りますが、〇日までにメールでお返事をいただいてもよろしいでしょうか。

d. When to refuse.

「あいにく」(Unfortunately)

「残念なのですが」(Unfortunately)

「お気持ちはとてもよくわかるのですが」 (I know exactly how you feel.)

「せっかくのお申し出をいただき、大変ありがたいのですが」 (I would like to thank you very much for your request.)

「ご期待に添えず、大変申し訳ないのですが」 (I am very sorry that I did not meet your expectations.)

「私どもの力不足で、大変恐縮なのですが」 (I am very sorry that I'm lacking in ability.) 

Ex: ご希望のデザインには添えず、申し訳ございません。再度、見直しを行います。

e. When giving an opinion or counterargument.

「僭越ながら」 (Please allow me (to say something))

「おっしゃることは重々承知をしておりますが」 (I am fully aware of what you are saying.)

「余計なこととは存じますが」 (I know it's unnecessary, but...)

「私の考え過ぎかもしれませんが」 (Maybe I'm thinking too much)

Ex: おっしゃることは重々承知をしておりますが、今回はA案をご提案させていただけないでしょうか。

f. When a request cannot be met.

「せっかくお声をかけていただいたのですが」 (Thank you for taking time to contact me but)

「ぜひご期待にお応えしたかったのですが」 (I really wanted to meet your expectations but)

「身に余るお話、光栄なのですが」 (It's an honor to hear your story)

「申し上げにくいのですが」 (It's hard to tell)

Ex: 身に余るお話、光栄なのですが、今回は辞退させていただいてもよろしいでしょうか?

g. When you want something to be improved.

「細かいことを言ってしまい恐縮ですが」 (I apologize for mentioning such details)

「こちらの都合ばかりで申し訳ございませんが」 (I apologize for the inconvenience)

「説明が足りず失礼いたしました」 (I apologize for not explaining enough)

Ex: 説明が足りず失礼いたしました。決定の理由を2つ以上あげていただけると助かります。

h. When offering assistance.

「もしよろしければ」 (If you do not mind)

「私でよければ」 (If you're okay with me)

「差し支えなければ」 (If it's not a problem)

「お力になれるのであれば」 (If I can help)

Ex: もしよろしければ〇〇までご提案させていただきます。

3. Examples of NG usage of cushion words that are easy to mistake.

  • 「申し訳ございません」 (I’m sorry)

「申し訳ございません」 (I’m sorry) is a cushion word used when you can’t meet someone’s request or when you apologize. Therefore, if you use it casually when it is not needed, it will end up sounding too light in the situation where you originally wanted to use it.

NG example:

「申し訳ございませんが、お名前をお聞かせいただけますか」

「申し訳ございませんが、こちらにご記入いただいてもよろしいでしょうか」

OK example:

「申し訳ございませんが、セール品につきましては返品をご遠慮いただいております」

  • 「差し支えなければ」 (If you don’t mind)

「差し支えなければ」 (If you don’t mind) includes the meaning of “Please decline the request if it is inconvenient.” Therefore, it can only be used in situations where there is no inconvenience caused even if the other party refuses. For example, it cannot be used when you are responding to a telephone call and need to know the person’s name to be connected to the agent, so be careful.

NG example:

「差し支えなければ、 お名前を伺ってもよろしいでしょうか」

→「差し支えなければ」を「恐れ入りますが」に変更しましょう。

OK example:

「差し支えなければ資料をご自宅にお送りしましょうか」

4. Precautions when using cushion words

Cushion words are soft expressions that give a polite impression, but if used too often, they can give a dull impression and make it difficult to get the main point across.

Cushion words can be used in a variety of situations, such as emails, chats, telephone calls, and face-to-face meetings, but especially in phone calls and face-to-face situations where sentences cannot be confirmed in text, it is likely that your intentions will be difficult to convey, so avoid using cushion words frequently.

5. How to respond to 「差し支えなけれ」 (If you don’t mind)

So far, we have looked at the expressions 「差し支えなけれ」 (If you don’t mind) used when requesting someone to do something, but there may be times when the other makes a request “If you don’t mind” to us. When accepting a request, a response such as 「承知しました」 (I understand) or 「かしこまりました」 (I understand) is appropriate.

Also, as mentioned above, 「差し支えなけれ」 (If you don’t mind) is an expression that leaves the decision on whether or not to accept the request to you, so of course you can decline it.

When you say “No”, be sure to show that you are sorry.

For example, if you can respond with something like 「大変申し訳ないですが、〇〇があるため、行うことが難しい状況です。お役に立てず恐縮でございます」 (I’m very sorry, but due to 〇〇, I’m unable to help you, I’m sorry that I can’t help you.)

This will leave a good impression.

6. Use cushion words appropriately to facilitate communication.

Cushion words are used in a variety of business situations to show consideration for others and facilitate communication.

It’s good idea to understand multiple phrases and appropriate situations, as they will be useful in situations where you need to convey something that is difficult to convey, such as when declining a request from someone or making a counterargument.

Make sure to use cushion words appropriately depending on the situation and maintain smooth communication and good relationships.

Reference Image and Document Source:

  • https://www.pexels.com/
  • https://go.chatwork.com/
  • https://allabout.co.jp/
View More
TECH

April 28, 2024

How to implement automatic activation feature for Windows applications.

    While using a computer for work, you'll certainly have to work with licensed applications. One of the important feature of licensed applications is activating the license with a key, but I believe that if you're a first-time user of the application, grasping the activation process can be difficult to ensure the correct execution of the activation process, software developers need to provide detailed and simplified instructions. With a principle of prioritizing user experience and application security, developers often develop the "Auto-Activation" feature, where a single mouse click on the application link automatically activates it and makes it ready to use.

    In this article, I will guide you on how to implement the "Auto-Activation" feature via email for a Windows application. There are certainly many other ways to implement this feature, but I will try to provide the simplest instructions possible so that you can understand how this feature works and apply it to your project.

1. Development environment

For implementing the auto-activation feature via email for a Windows application, I will develop an environment with two main components:

    • ActivationServer:
      • Function: Manage data, send emails, redirect activation links
      • Email service: Gmail
      • Web Framework: ASP.NET
    • Application:
      • Function: Perform activation
      • Application Framework: Windows Form C#

2. Functional design

    Regarding the specific operation of the feature, I will describe it according to the diagram below. Through the Windows operating system allowing you to call commands to open applications via "application protocol" (reference "Registering an Application to a URI Scheme"), we will create an application protocol for our application. Then, we can pass the activation key to the application to activate it as a URI parameter.

Auto activation email sending

Picture 1. Auto activation email sending sequence diagram

Auto activation processing

Picture 2. Auto activation processing sequence diagram

3. Functional development

On the server side, I will implement the routes as follows:

    • GET Home/index: Display the email sending form.
    • POST Home/SendMail: Generate the activation key and send the email.
    • GET Home/AutoRedirect: Perform redirection to the application protocol.

HomeController.cs

using System;
using System.Net;
using System.Net.Mail;
using System.Web.Mvc;
using Utility;

namespace ActivationServer.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View("Index", new ViewDataDictionary { { "message", string.Empty } });
        }

        [HttpPost]
        public ActionResult SendMail(FormCollection form)
        {
            try
            {
                string emailAddress = form["email"];
                string host = "http://myserver.com";
                string mailAddress = "myemail@gmail.com";
                string mailPassword = "mypassword";
                string mailHost = "smtp.gmail.com";
                int maiPort = 587;
                string mailSubject = "Auto activation email";
                string mailBody = "<h2>Auto Activation Email</h2><a href="{{ActivationLink}}">Click here to active!</a>";
                mailBody = mailBody.Replace("{{ActivationLink}}",
                           $"{host}/Home/AutoRedirect?protocol=appdemo&param=myactivationkey}");

                using (SmtpClient client = new SmtpClient())
                {
                    client.Host = mailHost;
                    client.Port = maiPort;
                    client.EnableSsl = true;
                    client.Credentials = new NetworkCredential(mailAddress, mailPassword);

                    using (MailMessage message = new MailMessage())
                    {
                        message.From = new MailAddress(mailAddress);
                        message.To.Add(new MailAddress($"{emailAddress}"));
                        message.Subject = mailSubject;
                        message.Body = mailBody;
                        message.IsBodyHtml = true;

                        client.Send(message);
                    };
                };
                return View("Index", new ViewDataDictionary { { "message", "Activation mail has been sent!" } });
            }
            catch (Exception ex)
            {
                return View("Error", new ViewDataDictionary { { "message", ex.Message } });
            }
        }

        public ActionResult AutoRedirect(string protocol, string param)
        {
            return Redirect($"{protocol}://?key={param}");
        }
    }
}

In the example, I'm using email sending with an HTML code to embed a link in the email using an <a> tag.

    I'll further explain why we don't directly insert the application protocol into the activation link. The reason is that an application protocol inherently lacks the format of an HTML protocol, making it prone to being stripped out by email servers during the email sending process. Therefore, instead of directly inserting the application protocol, we'll use a route like "Home/AutoRedirect" to redirect to the application protocol.

Index.cshtml

@{
    ViewBag.Title = "Home Page";
}

<main>
    <section class="row" aria-labelledby="aspnetTitle">
        <h1 id="title">Auto Activation Demo</h1>
    </section>

    <div class="row">
        <section class="col-md-4" aria-labelledby="">
            <form method="post" action="@Url.Action("SendMail")">
                <div class="mb-3">
                    <label for="txtEmail" class="form-label">Email address</label>
                    <input type="email" class="form-control" name="email" id="txtEmail" required>
                </div>
                <button type="submit" class="btn btn-primary">Submit</button>
            </form>
        </section>

        <section class="row mt-3">
            <p id="message">@Model["message"]</p>
        </section>
    </div>
</main>

On the application side, I will implement 2 forms as follows:

    • Active: Activation screen

Active screen

Picture 3.  Active Screen

    • Main: Main screen of the application

Main screen

Picture 4 .  Main Screen

    I'll add modifications so that the application can be launched via CLI with a "key" parameter. This is aimed at inserting the activation key into the activation screen upon startup.

Programs.cs

using System.Web;
using Utility;
using AppSetting = ApplicationDemo.Properties.Settings;

namespace ApplicationDemo
{
    internal static class Program
    {
        private static Mutex? mutex = null;

        ///
        ///  The main entry point for the application.
        /// 
        [STAThread]
        static void Main()
        {
            const string appName = "ApplicationDemo";
            bool createdNew;

            mutex = new Mutex(true, appName, out createdNew);

            if (!createdNew)
            {
                MessageBox.Show("Application already running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            ApplicationConfiguration.Initialize();

            Form startForm = new Main();
            if (string.IsNullOrWhiteSpace(AppSetting.Default.Key) || !CommonCode.IsValidKey(AppSetting.Default.Key))
            {
                string[] args = Environment.GetCommandLineArgs();
                string key = string.Empty;
                if (args.Length > 1)
                {
                    Uri uri = new Uri(args[1]);
                    key = $"{HttpUtility.ParseQueryString(uri.Query).Get("key")}";
                }
                startForm = new Active(key);
            }

            Application.Run(startForm);
        }
    }
}

Active.cs

using Utility;
using AppSetting = ApplicationDemo.Properties.Settings;

namespace ApplicationDemo
{
    public partial class Active : Form
    {
        public Active(string key)
        {
            InitializeComponent();

            txtActivationKey.Text = key;
        }

        private void btnActive_Click(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtActivationKey.Text))
                {
                    throw new Exception("Please enter activation key!");
                }

                if (CommonCode.IsValidKey(txtActivationKey.Text))
                {
                    MessageBox.Show("Activation Successful", "Information", MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                    AppSetting.Default.Key = txtActivationKey.Text;
                    AppSetting.Default.Save();
                    Main main = new();
                    main.Show();
                    Hide();
                }
                else
                {
                    MessageBox.Show("The activation key is invalid!", "Error", MessageBoxButtons.OK,
                                     MessageBoxIcon.Warning);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void Active_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void Active_Shown(object sender, EventArgs e)
        {

            if (!string.IsNullOrWhiteSpace(txtActivationKey.Text))
            {
                btnActive.PerformClick();
            }
        }
    }
}

Main.cs

using AppSetting = ApplicationDemo.Properties.Settings;

namespace ApplicationDemo
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void btnDeactive_Click(object sender, EventArgs e)
        {
            AppSetting.Default.Key = string.Empty;
            AppSetting.Default.Save();

            Active active = new Active(string.Empty);
            active.Show();
            Hide();
        }

        private void Main_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }
    }
}

    To make the application operational with an application protocol, we'll register it through the registry as follows, with the "ExecFilePath" is the location where the application is installed.

AppDemo.reg

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\appdemo]
"URL Protocol"=""
@="URL:appdemo"

[HKEY_CLASSES_ROOT\appdemo\shell]

[HKEY_CLASSES_ROOT\appdemo\shell\open]

[HKEY_CLASSES_ROOT\appdemo\shell\open\command]
@="ExecFilePath"   \"%1\""

To perform registry registration during application setup, you'll need to use a third-party software to package the application.

4. Operational demo:

5. Advantages and disadvantages:

    • Advantages:
      • User Experience: Streamlined activation process enhances user experience, reducing user frustration and increasing satisfaction.
      • Automation: Automating the activation process saves time and effort for both users and administrators.
      • Security: By encrypting the activation key and embedding it in a link, security is enhanced compared to manual entry or transmission via insecure channels.
      • Ease of Use: One-click activation simplifies the process for users, especially for those who may not be technically savvy.
    • Disadvantages:
      • Complexity of Implementation: Setting up the infrastructure for automated activation, including server-side processing and email integration, can be complex and require additional development effort.
      • Compatibility Issues: Because the information of the application protocol needs to be registered with the exact path to the application to be opened, it will not work if the user moves the application to a different directory.

Cover image from freepik.com

Reference:

  1. Sending emails using Gmail in C#
  2. Sign in with app passwords
  3. Registering an Application to a URI Scheme
View More
TECH

April 25, 2024

Dependency Injection Overview: Using Dependency Injection in ASP.NET Core

In the world of software development, Dependency Injection (DI) stands as a fundamental concept, often hailed as a cornerstone of good design and modular architecture. But, for many developers, especially those newer to the field, the term can evoke confusion or difficult to understand. I hope that the blog will help you understand DI better.

1. Understanding Dependency Injection

At its core, Dependency Injection is a design pattern used to manage dependencies between different components or modules within a software system. It can be understood simply as follows:
  • Modules do not communicate directly with each other, but through an interface. The low-level module will implement the interface, the high-level module will call the low-level module through the interface.
  • For example: To communicate with customer service, we have the ICustomerService interface, the low-level modules are CustomerService. The high-level module CustomerController will only use the ICustomerService interface.
  • Initialization of low-level modules will be performed by DI Container. For example: In the CustomerController, we will not initialize ICustomerService service = new CustomerService (), this will be done by DI Container. The CustomerController will not know anything about the class CustomerService
  • Which Module is attached to which interface will be configured in the class Program.cs

2. The Three Types of Dependency Injection

Dependency Injection can be implemented in three main ways: Constructor Injection, Setter Injection, and Interface Injection.
  • Constructor Injection: In this approach, dependencies are provided through a class's constructor. This ensures that all required dependencies are available when an object is instantiated, promoting immutability and simplifying testing.
  • Setter Injection: Also known as property injection, Setter Injection involves providing dependencies through setter methods. While not as preferred as Constructor Injection due to the potential for objects to be in an invalid state, Setter Injection can be useful for optional dependencies.
  • Interface Injection: This approach is less common and involves providing dependencies through an interface that the client class implements. However, this method can introduce tight coupling between the client class and the injector, making it less flexible compared to Constructor Injection.
Among the three types of Inject, Constructor Injection method is very popular because of its flexibility, ease of building DI libraries...

3. Advantages and disadvantages of Dependency Injection

Advantage

  • Reduce adhesion between modules
  • Code is easy to maintain, easy to replace modules
  • Very easy to test and write Unit Test

Disadvantages

  • The concept of DI is quite difficult to understand new developers will have difficulty learning it
  • Objects are completely initialized from the beginning, which can reduce performance Increases code complexity

4. Using DI in .NET CORE

Use Dependency Injection through these steps:
  1. Use an interface or base class to abstract implementation dependencies.
  2. Register the dependency in the service container. ASP.NET Core allows us to register our application services with the IoC container, in the Program.cs class use IServiceCollection to register application services
  3. Include the service in the constructor of the class in which it is used. The framework will create an instance of the dependency and remove it when it is no longer needed.
Example: The ICustomerService interface defines the SendMessage method
public interface ICustomerService {
    void SendMessage(string message);
}
We have the CustomerAService implement ICustomerService1
public class CustomerAService : ICustomerService {
    public void SendMessage(string message)
    {
        Console.WriteLine($"CustomerAService.SendMessage Message: {message}");
    }
}
The AddScoped method registers the service with scoped lifetime, the lifetime of a singleton request
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<ICustomerAService, CustomerAService>();
 
var app = builder.Build();
There are 3 lifecycle levels: addTransient, addScoped, addSingleton.
  • Transient: Instance is initialized each time a service is created
  • Scoped: Instance is initialized per scope. (Scope here is each request sent to the application). In the same scope, the service will be reused.
  • Singleton: The service instance is created uniquely at application launch and is used everywhere
ICustomerService is required and used to call the SendMesasge method
public class CustomerController : PageModel {
    private readonly ICustomerService _customerService;
    public Index2Model(ICustomerService customerService) {
        _customerService = customerService;
    }
    public void OnSendMesasge() {
        _customerService.SendMessage("Send message");
    }
}
By using the DI pattern, the controller will: Not use CustomerAService, only use the ICustomerService interface. That makes it easy to change the Controller's implementation without modifying the Controller.

View More
TECH

April 9, 2024

Top Angular interview questions (part 1)

Interviews allow the interviewer to collect relevant information from the interviewee. This information can include details about qualifications, experiences, skills, and suitability for the position.

In a technical interview for a position related to Angular framework, the candidates need to prepare for the understanding of the framework, it will help them perform well during the interview.

This post will introduce the top 5 common questions about Angular framework.

View More
TECH

April 3, 2024

The Power of Memos

Memo-taking habits recommended for all people.
People who are good at work, such as people who have the ability to take action, people who are good at speaking and writing, people who have planning skills, and people who have good judgment and decision-making skills, have the ability to take notes. They frequently write down in notebooks or diaries things they see or hear, ideas that come into their minds, lessons learned insights and so on. They often review their notes and use them in their work.
The human brain is not a universal device that remembers all events and information. On the contrary, it forgets most things. When you are busy at work, you may break out in a cold sweat and say, "I can't remember what you said to me just now".
A good way to avoid the risk of forgetting is to take memos. A memo is like an external hard disk for the brain. Therefore, you don't have to remember what you have written down.

Here are memo-taking situations and their respective purposes.

1. Meetings and conferences

There are many situations where memos are taken in the company, such as meetings and conferences, where there are many items to be noted, such as what was said and what was decided on the spot.
The memos taken in these situations are sometimes written down in the form of minutes, so the memos taken on the spot are positioned as a record for the purpose of writing them down. People's conversations in meetings unfold faster than the speed at which notes are taken, so speed and technique are required to successfully jot down only the main points.

2. Business negotiations and meetings with clients

Business negotiations and meetings with suppliers and customers are activities outside the company, so handling memos is more important than within the company. If you are inside the company, you can ask the same question again if you bow down, but if you are outside the company, it can become a trust issue for the company if it continues over and over again. Therefore, taking notes is essential, but another effect is that it is also a business technique to show that you are listening carefully to what the other person is saying and that you are taking notes to ensure that there are no mistakes.

3. Training and seminars

Memos are also very useful in training courses, seminars and other opportunities for self-improvement. In this case, the main purpose is to efficiently take home the information necessary for self-improvement, so the notes should be easy to understand when you read them back later and reproducible, so that you can easily remember them.

4. Writing down inspiring ideas

Writing down information that comes in from the outside is not the only role of a memo. It is also very important to take notes on ideas that occur to you in your mind. Ideas come to you suddenly and disappear quickly, but by writing them down, you can remember them later. It also allows you to brush them up further and develop them into a draft plan.

Conclusions

No one has a bad impression when they see the person they are talking to taking copious notes. At the same time, it gives a good impression that they are listening attentively so as not to miss anything you say, and at the same time, it gives you a sense of security that your message will be understood if they are taking this many notes.

Since the obvious act of taking memos out of necessity can make such a good impression on the other person, you should make great use of memos as a consistent communication technique.
When you see someone taking memos seriously, the person you are talking to will naturally become more serious. If that is how you get information of high value, then thank goodness for memos.

※Image source and Reference website:

  • [https://www.pexels.com]
  • [https://navi.dropbox.jp/memo]
  • [https://next.rikunabi.com/journal/20170425_m1/]
View More
TECH

April 2, 2024

Online word lookup skills

As a Japanese interpreter in the IT industry, you will certainly encounter many new words and new knowledge during your interpreting process.

In such situations, we need to learn about new knowledge from that new word, and there are many ways to get answers, including: asking knowledgeable people, searching online, searching in books, etc.

Here, I would like to share about “How to search wording on internet”.

View More
TECH

April 1, 2024

Some tips when writing emails in Japanese to Customers

When we work with Japanese customers, we need to become familiar with exchanging information that is related to work via email. Business emails have different expressions compared to spoken communication. Based on my learning and experiences, I would like to introduce some basic tips for writing work-related emails in Japanese.

View More
TECH

April 1, 2024

The Bluetooth Qualification Process: Overview for Individuals and Businesses

In the world of wireless communication, Bluetooth technology has become an integral part of our daily lives. From smartphones to smart home devices, Bluetooth enables seamless connectivity and data transfer. However, before a device can bear the official Bluetooth logo, it must go through a rigorous qualification process. In this blog post, we will delve into the steps involved in the Bluetooth qualification process for individuals and businesses, while also highlighting the potential risks of non-compliance. Please note that this article serves as a personal perspective and a reference guide.

View More
TECH

April 1, 2024

Understanding Stunnel: A Basic Overview

In today's digital landscape, safeguarding sensitive data on networks is paramount. Stunnel serves as a widely-used tool for achieving this goal.

View More
TECH

April 1, 2024

Introducing PHPStan: Improving PHP Code Quality

While developing PHP applications, IDEs like PhpStorm or Visual Studio Code can help you quickly detect and fix errors. However, there are error cases that the IDE cannot detect, such as:

  • Type errors: IDEs cannot check the data types of variables when they are passed between functions or methods.
  • Call to undefined method errors: IDEs cannot check the calling of methods of an object if they are not defined.
  • Accessing non-existing elements of an array or object: IDEs cannot check accessing non-existing elements of an array or object.
  • ...

PHPStan is a static analysis tool for PHP code that helps detect errors in source code that regular IDEs cannot detect. Unlike dynamic analysis tools that identify issues during runtime, PHPStan performs its analysis by examining the codebase without actually running the application. This approach allows developers to catch errors and potential problems before deploying the code.

Key Features of PHPStan:

  1. Static Analysis: PHPStan analyzes your code without running it, identifying a wide range of potential issues such as type mismatches, undefined variables, and unreachable code.
  2. Type Inference: By analyzing the code flow, PHPStan can infer types of variables, enabling early detection of type-related errors and improving the overall reliability of your code.
  3. Error Detection: It flags common mistakes and potential bugs in your code, helping you catch errors early in the development process.
  4. Customizable Rules: PHPStan allows you to define your own rules and levels of strictness, tailoring the analysis to your specific project requirements.
  5. Integration: It seamlessly integrates with popular PHP development tools and continuous integration pipelines, making it easy to incorporate into your existing workflow.

Benefits of Using PHPStan:

  1. Early Issue Detection: PHPStan finds problems in your code before it runs, helping to catch and prevent bugs early.
  2. Better Code Quality: PHPStan points out areas where your code can be improved, which helps make your code easier to maintain and understand.
  3. Increased Developer Efficiency: Developers get immediate feedback in their coding environment, which speeds up development and reduces time spent debugging.
  4. Type Safety: PHPStan checks types in your code, making it safer and less likely to have runtime errors caused by type mismatches.
  5. Customizable Rules: You can customize PHPStan to fit your project’s requirements by creating your own rules and extensions, ensuring it follows your coding standards.

How to use PHPStan:

To start using PHPStan, follow these simple steps:

  1. Organize project structure:

    Below is an example of a simple directory structure for a project using PHPStan:

    project_root/

    ├── src/ # Directory containing the PHP source code of the application
    │ ├── index.php

    ├── vendor/ # Directory containing libraries and Composer dependencies
    │ └── ...

    ├── phpstan.neon # PHPStan configuration file
    └── composer.json # Composer configuration file

  2. Install PHPStan using Composer

    composer require --dev phpstan/phpstan

  3. Create PHPStan Configuration:

    Add config to phpstan.neon configuration file. This file can define rules, paths to analyze, and other configuration options.

    Example phpstan.neon configuration:

    parameters:
      level: 7
      phpVersion: 80000
      paths:
        - src

    + level: This sets the strictness level of PHPStan to 7, indicating a high level of analysis.
    + phpVersion: Configuration option specifies the PHP version that PHPStan should use for analysis. In this case, 80000 corresponds to PHP version 8.0.0.
    + paths: Specifies the directories to analyze.

  4. Run PHPStan:

    We will add some error code examples to the index.php file for PHPStan to check.

    index.php

    1   <?php
    2   // Using an undeclared variable
    3   echo $undefinedVariable;
    4   
    5   // Calling a non-existent function
    6   nonExistentFunction();
    7   
    8   // Calling a non-existent method within a class
    9   class AnotherClass {
    10       public function method() {
    11           $this->undefinedMethod();
    12       }
    13   }
    14
    15  $anotherObj = new AnotherClass();
    16  $anotherObj->method();
    17
    18  // Performing an operation on a non-numeric variable
    19  $nonNumeric = 'abc';
    20  $result = $nonNumeric * 2;
    21
    22  // Using a global variable
    23  function testGlobal() {
    24      global $undefinedGlobal;
    25      echo $undefinedGlobal;
    26  }
    27
    28  testGlobal();
    29
    30  // Using a function with an inappropriate number of parameters
    31  function sum($a, $b) {
    32      return $a + $b;
    33  }
    34
    35  $result = sum(5);
    36
    37  // Accessing a non-existent element in an array
    38  $array = ['a', 'b', 'c'];
    39  echo $array[3];
    40  ?>


    After that, Run PHPStan from the command line in your project directory:

    vendor/bin/phpstan analyse

  5. Review the Output:

    PHPStan will analyze your code and provide feedback on any issues found. Review the output to identify and fix potential problems in your code.

    Note: Using configuration file /var/www/html/phpstan.neon.
     1/1 [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓] 100%
     ------ ---------------------------------------------------------------------
      Line   index.php
     ------ ---------------------------------------------------------------------
      3      Variable $undefinedVariable might not be defined.
      6      Function nonExistentFunction not found.
             ? Learn more at https://phpstan.org/user-guide/discovering-symbols
      10     Method AnotherClass::method() has no return type specified.
      11     Call to an undefined method AnotherClass::undefinedMethod().
      20     Binary operation "*" between 'abc' and 2 results in an error.
      23     Function testGlobal() has no return type specified.
      31     Function sum() has no return type specified.
      31     Function sum() has parameter $a with no type specified.
      31     Function sum() has parameter $b with no type specified.
      35     Function sum invoked with 1 parameter, 2 required.
      39     Offset 3 does not exist on array{'a', 'b', 'c'}.
     ------ ---------------------------------------------------------------------
     [ERROR] Found 11 errors

Conclusion:

PHPStan is a valuable tool for any PHP developer looking to write cleaner, more reliable code. By catching errors early and providing detailed feedback, it empowers developers to build high-quality PHP applications with confidence and efficiency.

References:

View More
1 7 8 9 10 11 16