iTranslated by AI
17 Essential Tips for Writing 'Good Code'
About This Article
I am a web application engineer at a company providing web infrastructure. My work often involves developing aggregation (BFF) layers that integrate various backend APIs—such as infrastructure and customer databases—as well as implementing frontend interfaces. I frequently choose TypeScript and C# as my languages, and use React.js and Vue.js for the frontend. In this context, I will post the tips I keep in mind daily to write "good code."
Out of Scope
- Basic concepts like indentation, fundamental naming conventions, and access modifiers are omitted.
- While the code examples are in TypeScript, the content is not specific to any single language.
- The topics are general programming concepts and are not specialized for any specific layer such as frontend or backend.
What is "Good Code"?
I define "good code" here as having:
- High maintainability
- High readability
I looked up the definitions of these terms on Wikipedia.
Maintainability
Refers to the ease with which components can be modified to correct faults, improve performance or other attributes, or adapt to a changed environment, requiring less effort and cost for additions or changes not envisioned during the initial design.
Readability
Refers to how easy it is for a human to understand the purpose and flow of the source code.
I believe maintainability encompasses readability, but I will differentiate them for this discussion.
Table of Contents
- Write Comments Starting with the Background
- Use Summary Variables
- Use Explanatory Variables
- Extract into Modules
- Use Early Returns
- Extract Cross-Cutting Concerns Using AOP
- Use Immutable Types
- Encapsulation
- Hide Legacy Code
- Cohesion and Coupling
- Avoid Inheritance Generally
- Do Not Force Commonization
- Dependency Injection (DI)
- Dependency Inversion Principle (DIP)
- Use Generics
- Reference Architectures
- Rely on Automatic Generation
Write Comments Starting with the Background
I sometimes see comments that simply translate the implementation into plain language, like this:
// Execute if master role, or if isOldTypeAccount=true and admin role
if (user.role === "master" || (user.isOldTypeAccount && user.role === "admin")) {
// Process permitted only for administrator users
}
This leaves behind uncertainties and questions: What does isOldTypeAccount mean? What is the admin role? Do I need to consider this in future modifications?
// Execute only for administrator roles
// Accounts before service renewal (isOldTypeAccount=true) used 'admin' for the administrator role
if (user.role === "master" || (user.isOldTypeAccount && user.role === "admin")) {
// Process permitted only for administrator users
}
By describing the background, it becomes clear why both "master role" and "admin role" exist and why the isOldTypeAccount flag was created.
The implementer and the reader often have different prerequisite knowledge. You should consider this when writing comments (and implementation).
Use Summary Variables
Using the code from the previous example, I will turn the part that says "Accounts before service renewal (isOldTypeAccount=true) used 'admin' for the administrator role" into a summary variable.
const isOldTypeMasterRole = user.isOldTypeAccount && user.role === "admin";
if (user.role === "master" || isOldTypeMasterRole) {
// Process permitted only for administrator users
}
By doing this as shown above, the comment is no longer necessary. It is even better if you extract it into a module.
if (isMasterRoleUser(user)) {
// Process permitted only for administrator users
}
Use Explanatory Variables
To obtain target values, one might sometimes reference deep hierarchies of a class or perform dangerous string operations. Processing such responses naively leads to poor aesthetics and reduced readability.
class UserGetService {
public get(userId: string) {
const api = new LegacyApi()
const resp = api.getUsers(userId)
return {
userId: resp.data.users[0].id,
lastName: resp.data.users[0].info.fullName.split(" ")[0],
firstName: resp.data.users[0].info.fullName.split(" ")[1],
}
}
}
In this case, defining explanatory variables can potentially improve readability.
class UserGetService {
public get(userId: string) {
const api = new LegacyApi()
const resp = api.getUsers(userId)
const user = resp.data.users[0]
const userNames = user.info.fullName.split(" ")
const lastName = userNames[0]
const firstName = userNames[1]
return { userId: user.id, lastName, firstName }
}
}
Extract into Modules
Let's take a user creation module as an example. In the bad example, the validation processing for userId and password becomes noise, decreasing readability.
function createUser(userId: string, password: string) {
// userId validation
if (userId && userId.length >= 8 && userId.length <= 32) {
// password validation
if (password && password.length >= 8 && password.length <= 64) {
const api = new UserApi(userId, password)
api.create(userId, password)
}
}
}
Taking userId as an example, it performs the following three checks:
- Does
userIdhave a value? - Is
userId8 characters or more? - Is
userId32 characters or less?
These all concern the same interest: "Is the userId in the expected state?" When concerns align, they can be extracted into a separate module.
function createUser(userId: string, password: string) {
if (isUserIdValid(userId)) {
if (isPasswordValid(password)) {
const api = new UserApi(userId, password)
api.create(userId, password)
}
}
}
function isUserIdValid(value: string) {
return value && value.length >= 8 && value.length <= 32
}
function isPasswordValid(value: string) {
return value && value.length >= 8 && value.length <= 64
}
By extracting them into modules and naming them, you can understand at a glance what concerns they are addressing. Before supplementing code with comments, consider whether that process should be extracted into a module.
Use Early Returns
The primary benefit of using early returns is the reduction of nesting. Deep nesting reduces readability.
function createUser(userId: string, password: string) {
if (isUserIdValid(userId)) {
if (isPasswordValid(password)) {
const api = new UserApi()
api.create(userId, password)
}
}
}
For logic that is not the essence of the process—such as API execution or validation before database recording—you should use early returns.
function createUser(userId: string, password: string) {
if (!isUserIdValid(userId)) { return }
if (!isPasswordValid(password)) { return }
const api = new UserApi()
api.create(userId, password)
}
Compared to the bad example, the good example reduces nesting and improves the transparency of the essential code.
Extract Cross-Cutting Concerns Using AOP
Depending on the language, the terminology changes—annotations in Java, attributes in C#, decorators in JavaScript—but I recommend using them.
For example, if processes like authentication or logging are mixed into a user creation module, they become noise relative to the class's core concerns, reducing readability. You should move such processes out and be considerate of the reader by allowing them to focus on the essential logic.
function createUser(userId: string, password: string) {
this.logger.log(Level.info, "start user create")
if (!this.auth()) { throw new UnauthenticatedError() }
if (!isUserIdValid(userId)) { return }
if (!isPasswordValid(password)) { return }
const api = new UserApi()
api.create(userId, password)
logger.log(Level.info, "end user create")
}
@auth()
@log("user create")
function createUser(userId: string, password: string) {
if (!isUserIdValid(userId)) { return }
if (!isPasswordValid(password)) { return }
const api = new UserApi()
api.create(userId, password)
}
Use Immutable Types
If exposed fields are mutable, you must constantly watch them throughout their lifecycle to ensure they haven't been changed elsewhere. Declaring them as immutable frees up your working memory—the ability to temporarily store and process information needed for work—and facilitates easier reading.
class User {
- public userId: string
+ public readonly userId: string
}
Private fields should also be made immutable whenever possible.
The information that something is "immutable" proves more effective as the amount of code grows.
class User {
public readonly userId: string
- private password: string
+ private readonly password: string
}
In languages where you can restrict class initialization via constructors, it is most desirable that the class state cannot be changed except via constructor arguments. If you have the information that "fields can only be changed by the constructor," you can safely reuse that instance even if it's buried in a vast amount of code.
class CreateUserCommand {
public readonly userId: string
private readonly password: string
+ constructor(userId: string, password: string) {
+ this.userId = userId
+ this.password = password
+ }
public execute() { ... }
}
If arguments are reference types, it is desirable to make the arguments immutable as well. This guarantees that the arguments are not modified inside the method (it is not a destructive method), which eliminates the need to check the method's internals and strengthens encapsulation.
class CreateUserCommand {
public readonly userId: string
private readonly password: string
- constructor(user: { userId: string; password: string }) {
+ constructor(user: Readonly<{ userId: string; password: string }>) {
this.userId = user.userId
this.password = user.password
}
public execute() { ... }
}
Summary of immutable types:
- Make fields
readonly. - Do not expose
settermethods (disallow external changes). - Utilize constructor constraints.
- Declare arguments as immutable types.
Encapsulation
Interpretations of encapsulation may vary. I consider encapsulation to be "the ability to use something correctly without needing to check its implementation."
"Able to use correctly without checking the implementation" means that one can understand what kind of module it is just by looking at the class definition.
class Register {
public userId: string
public password: string
public execute() {
if (!this.userId) { throw Error("Please enter a value for userId") }
if (!this.password) { throw Error("Please enter a value for password") }
// User creation process
}
}
When a class like the one above exists, extracting its class definition results in the following:
class Register {
userId: string
password: string
execute(): void
}
Looking at this alone, information is missing, and it is unclear how the class should be used. To use it, you must open the implementation and check inside the class.
First, let's change the class name. Give it a concrete name that reflects its responsibilities. Abstract names are the first step toward a GOD class.
- class Register {
+ class UserCreateCommand {
public userId: string
public password: string
public execute() {
if (!this.userId) { throw Error("Please enter a value for userId") }
if (!this.password) { throw Error("Please enter a value for password") }
// User creation process
}
}
By correcting the class name, it is now clear that it is a class for creating users.
With just this, however, the information that userId and password are required cannot be read.
Rather than just explicitly stating that userId and password are required, I will use a constructor to restrict instantiation so that it cannot be created without passing userId and password.
class UserCreateCommand {
- public userId: string
- public password: string
+ constructor(public userId: string, public password: string) { }
public execute() {
if (!this.userId) { throw Error("Please enter a value for userId") }
if (!this.password) { throw Error("Please enter a value for password") }
// User creation process
}
}
Since I've changed it to receive parameters via the constructor, it is desirable to perform validation in the constructor as well.
class UserCreateCommand {
constructor(public userId: string, public password: string) {
+ if (!this.userId) { throw Error("Please enter a value for userId") }
+ if (!this.password) { throw Error("Please enter a value for password") }
}
public execute() {
- if (!this.userId) { throw Error("Please enter a value for userId") }
- if (!this.password) { throw Error("Please enter a value for password") }
// User creation process
}
}
At this stage, I think it has become much easier to use, but finally, I will add readonly constraints to the fields. This guarantees that fields are not modified outside the constructor.
class UserCreateCommand {
- constructor(public userId: string, public password: string) {
+ constructor(public readonly userId: string, public readonly password: string) {
if (!this.userId) { throw Error("Please enter a value for userId") }
if (!this.password) { throw Error("Please enter a value for password") }
}
public execute() {
// User creation process
}
}
Finally, extracting the class definition results in the following:
class UserCreateCommand {
readonly userId: string
readonly password: string
constructor(userId: string, password: string)
execute(): void
}
It is now possible to understand how to use it just by looking at it from the outside.
Hiding Legacy Code
When dealing with legacy code or legacy APIs, you may encounter implementations like "data buckets" that have a large number of optional arguments. These control behavior based on how the arguments are passed.
In the LegacyApi below, the creation of general users and corporate users is controlled by how the User type values are packed. This API is not properly encapsulated, and you would likely end up having to ask the API maintainers how to use it.
type User = {
name: string
mail: string
address?: string // Required only for general users
corporateUser?: boolean // "true" for corporate users
corporateAddress?: string // Required only for corporate users
}
class UserCreateFacade {
public createUser() {
const api = new LegacyApi()
const user: User = {
name: "yamada taro",
mail: "yamada@xxx.com",
address: "Kamakura, Kanagawa...",
// Are the parameters sufficient...??
}
api.createUser(user)
}
public createCorporateUser() {
const api = new LegacyApi()
const user: User = {
name: "good codes Inc.",
mail: "good_codes@xxx.com",
corporateUser: true,
corporateAddress: "Shinagawa, Tokyo...",
// Is address also required...??
}
api.createUser(user)
}
}
For APIs like this, it is a good idea to define parameter generation in a Factory class so that team members don't have to ask the API maintainers how to use it twice.
type User = {
name: string
mail: string
address?: string // Required only for general users
corporateUser?: boolean // "true" for corporate users
corporateAddress?: string // Required only for corporate users
}
class UserFactory {
public static getUser(
name: string,
mail: string,
address: string
): User {
return { name, mail, address }
}
public static getCorporateUser(
name: string,
mail: string,
corporateAddress: string
): User {
return { name, mail, corporateAddress, corporateUser: true }
}
}
class UserCreateFacade {
public createUser() {
const api = new LegacyApi()
const user = UserFactory.getUser(
"yamada taro",
"yamada@xxx.com",
"Kamakura, Kanagawa..."
)
api.createUser(user)
}
public createCorporateUser() {
const api = new LegacyApi()
const user = UserFactory.getCorporateUser(
"good codes Inc.",
"good_codes@xxx.com",
"Shinagawa, Tokyo..."
)
api.createUser(user)
}
}
Cohesion and Coupling
High Cohesion
Let's take a service class that creates a user and then registers the operation history after user creation as an example.
type InputData = { userId: string; password: string }
class CreateUserService {
private readonly userApi = new UserApi()
private readonly historyApi = new HistoryApi()
public handle(inputData: Readonly<InputData>) {
this.userApi.create(inputData.userId, inputData.password)
this.historyApi.add(inputData.userId, "new user created.")
}
}
class UserApi {
create(userId: string, password: string) {}
}
class HistoryApi {
add(userId: string, message: string) {}
}
The fields used in the handle() method above are all contained within the same class, and there is a high degree of correlation between the fields and methods. A class or module where the processing and data are located close to each other in this way is said to have high cohesion.
Loose Coupling
Currently, UserCreateService is implemented with dependencies on the UserApi and HistoryApi classes. We will change each to an interface to eliminate the dependency on the concrete classes.
type InputData = { userId: string; password: string }
class CreateUserService {
constructor(
private readonly userApi: UserApi,
private readonly historyApi: HistoryApi
) {}
public handle(inputData: Readonly<InputData>) {
this.userApi.create(inputData.userId, inputData.password)
this.historyApi.add(inputData.userId, "new user created.")
}
}
// Changed from class to interface
interface UserApi {
create(userId: string, password: string): void
}
interface HistoryApi {
add(userId: string, message: string): void
}
By relying on interfaces for the implementation in this way, UserCreateService has become an independent class with no dependencies on any specific class. Such classes or modules are said to be loosely coupled.
Summary of High Cohesion and Loose Coupling
Classes that are highly cohesive and loosely coupled have many advantages, such as:
- High readability
- High maintainability (easy to modify because the scope of influence is limited)
- Less likely to have conflicts when modifying code
- Easier to create test code
To sum up, if you build a system with a highly cohesive and loosely coupled configuration, you will be able to manage it. I believe it is that important of an element in maintainability.
Avoid Using Inheritance
Unless used appropriately, inheritance easily leads to low-cohesion, tightly-coupled GOD classes. I often see programs where complexity increases by creating common logic in a base class. In most cases, if you want to share functionality, you will be more successful by extracting it into a separate class.
public class Base {
public common() {}
}
public class MyClass extends Base {
public method() {
this.common()
}
}
public class Shared {
public common() {}
}
public class MyClass {
public method() {
const shared = new Shared()
shared.common()
}
}
Do Not Over-Abstract (Do Not Force DRY)
When I was just learning to program, I thought less code was always better, and I would perform excessive DRY (Don't Repeat Yourself). Even if you forcibly extract something that has a different context, it might work at the time of release, but you will struggle when you need to make changes later. You end up having to decompose it into separate modules or add conditional logic anyway...
You think much more when modifying existing code than when writing new code.
For example, the "run" process for a human and the "run" process for an animal might be the same initially. However, there is a strong possibility that you will later need to add functionality specific only to humans. If the processes are common, you will have to perform modifications and verification while considering the "running" of both humans and animals.
It is important to allow for redundant code if the processes just happen to be the same now but are fundamentally different, rather than forcing abstraction.
Dependency Injection (DI)
There are many benefits to eliminating dependencies between classes using DI. Here, I would like to highlight the characteristics of "improved readability" and "swappability."
Improving Readability
Let's take the process of creating a user as an example. The requirements are as follows:
- Start log
- User creation
- End log
- Logging can be switched between text output and console output.
- User creation logic can be changed for testing, development, and production.
Without using DI
class CreateUserHandler {
public handle() {
const logger =
config.logger === "console" ? new ConsoleLogger() : new TextLogger();
logger.info("start create user.");
if (config.env === "test") {
const service = new CreateUserServiceTest();
service.handle();
} else if (config.env === "development") {
const service = new CreateUserServiceDev();
service.handle();
} else {
const service = new CreateUserServiceProd();
service.handle();
}
logger.info("end create user.");
}
}
mm..🤔 Other code
const config = {
env: "production",
logger: "text",
};
class CreateUserServiceTest {
public handle() {}
}
class CreateUserServiceDev {
public handle() {}
}
class CreateUserServiceProd {
public handle() {}
}
class ConsoleLogger {
public info(msg: string) {}
}
class TextLogger {
public info(msg: string) {}
}
As you can see, conditional branches unrelated to the core logic are mixed into CreateUserHandler as noise, making it difficult to follow the processing flow.
In terms of cyclomatic complexity, it is said that complexity increases with the number of conditional branches.
Using DI
class CreateUserHandler {
// Minimum implementation for now
// In libraries, injection is often done using decorators or constructors
private readonly logger = diContainer.get<ILogger>("Logger");
private readonly createUserService = diContainer.get<ICreateUserService>("CreateUserService");
public handle() {
this.logger.info("start create user.");
this.createUserService.handle();
this.logger.info("end create user.");
}
}
good😊 Other code
const config = {
env: "production",
logger: "text",
};
interface ICreateUserService {
handle();
}
interface ILogger {
info(msg: string);
}
class CreateUserServiceTest implements ICreateUserService {
public handle() {}
}
class CreateUserServiceDev implements ICreateUserService {
public handle() {}
}
class CreateUserServiceProd implements ICreateUserService {
public handle() {}
}
class ConsoleLogger implements ILogger {
public info(msg: string) {}
}
class TextLogger implements ILogger {
public info(msg: string) {}
}
class PoorDiContainer {
private readonly container: { [key: string]: unknown } = {};
public add(key: string, instance: unknown) {
this.container[key] = instance;
}
public get<T>(key: string): T {
return this.container[key] as T;
}
}
// Dependencies are set in the DI container away from the core logic
const diContainer = new PoorDiContainer();
if (config.env === "test") {
diContainer.add("CreateUserService", new CreateUserServiceTest());
} else if (config.env === "development") {
diContainer.add("CreateUserService", new CreateUserServiceDev());
} else {
diContainer.add("CreateUserService", new CreateUserServiceProd());
}
if (config.logger === "console") {
diContainer.add("Logger", new ConsoleLogger());
} else {
diContainer.add("Logger", new TextLogger());
}
By handling class selection based on config during registration to the diContainer, CreateUserHandler has become a simple implementation. While the amount of "other code" increased due to interface definitions, if encapsulation is done properly, you only need to check the interface parts, so the volume of extra code is negligible.
Swapping Implementations According to Development Phase
When running test code, you do not want to include processes with side effects. In this case, there is no need to write test-specific code in CreateUserHandler; you can switch to a test implementation simply by changing the config as shown below.
const config = {
env: "test", // Switch to implementation without side effects for testing
logger: "console", // Switch to implementation without side effects for testing
};
describe("User Creation", () => {
it("Normal termination", () => {
const createUserHandler = new CreateUserHandler();
createUserHandler.handle();
});
});
If you need to add a new Logger, the only place you need to change is where you add it to the DI container.
// Assuming settings are referenced from the DI container
const config = {
env: "production",
logger: "mongodb",
}
if (config.logger === "mongodb") { // new!!
diContainer.add("Logger", new MongoDbLogger())
} else if (config.logger === "console") {
diContainer.add("Logger", new ConsoleLogger())
} else {
diContainer.add("Logger", new TextLogger())
}
Using DI in this way reduces coupling between classes, creates independent modules, and makes it easy to switch implementations suitable for each development phase.
In actual operations, it is recommended to use libraries known as DI containers to manage dependencies. They come with features that make DI more comfortable to use, such as caching instances and generating instances using the Factory pattern.
Dependency Inversion Principle (DIP)
This is one of the SOLID principles, known in Japanese as "Izonsei Gyakuten no Gensoku." A famous design pattern that uses DIP is the Repository pattern.
By making high-level modules depend on interfaces and swapping out low-level modules via DI, you can decouple persistence logic from business logic, effectively abstracting data-related operations. By reversing dependencies in this way, you ensure that critical domain implementation does not need to be changed due to the requirements of low-level modules. This approach of placing the domain at the center of the system and pushing volatile layers to the periphery is also adopted in Onion Architecture and Clean Architecture.

Using Generics
Generics might seem straightforward once you get used to them, but for beginners, they are a new concept that can be difficult to grasp at first.
Even if you can use them intuitively, there is a different level of difficulty in creating modules using generics and incorporating them into your design. Therefore, I consider this a "gateway to success" for beginners in statically typed languages.
Generics are very convenient as they can be used to avoid boxing, suppress runtime errors caused by casting, and enhance the expressiveness of interfaces in various languages. Also, since the type to be handled can be specified by the caller, you can create modules that are convenient for the caller while maintaining consistency in processing.
List without type specification
class AnyList {
private readonly source: any[] = []
public add(value: any) {
this.source.push(value)
}
public get(index: number): any {
return this.source[index]
}
}
const anyList = new AnyList()
anyList.add("xxx")
const value = anyList.get(0) // At this point, it is an 'any' type
if (typeof value === "string") {
// Here, it is treated as a string type
}
Taking TypeScript as an example, it is treated as an any type until the type is narrowed down using type guards. Therefore, you must specify the type before using it. Also, if you accidentally cast it to the wrong type, a runtime error will occur, so you must always be careful.
List using Generics
class GenericsList<T> {
private readonly source: T[] = []
public add(value: T) {
this.source.push(value)
}
public get(index: number): T {
return this.source[index]
}
}
const genericsList = new GenericsList<string>()
genericsList.add("xxx")
const value: string = genericsList.get(0) // It is a string type at this point
By using generics and specifying the type definition from the caller, I was able to create a class that can handle any type, whether it is a string, number, or object.
Referring to Architectures
Architecture is a great invention by our predecessors. It is definitely worth referring to.
Here, I will touch upon the following. Please see other dedicated articles for details.
- Clean Architecture, Onion Architecture
- CQS and CQRS
Clean Architecture, Onion Architecture
I recognize the most important idea shared by these two is to "direct dependencies toward the center of the circle."

This is achieved by using patterns like the Repository pattern to invert dependencies. Allowing the direction of dependency only from the outside to the inside, and placing business logic at the center. By adhering to this, you prevent the leakage of business logic into other layers and keep the domain part independent.
When the most important business logic is independent, other layers become replaceable (pluggable) parts, resulting in a program that is easy to test and highly maintainable.
This article is very helpful:
CQS and CQRS
These stem from the idea that since the concerns differ between data retrieval (Query) and data modification (Command), it is generally better to separate Query and Command rather than sticking to simple CRUD.
Separating CQS within a program is called CQS, while separating them by server or resource is called CQRS.

In implementations separated by server, event sourcing is often used together. Event sourcing treats use cases as events and accumulates them in a database. Use cases corresponding to "Delete" are also inserted into the database as deletion events. (Think of it like git).
The accumulated events are called an event journal and become the data source inserted only by Commands.
Conversely, for Queries, you create a database that acts as a read model with convenient data extracted from the event journal. A convenient data structure has high retrieval performance and is rich in expressiveness. Read models maintain the latest state by monitoring transaction logs or by detecting changes in the data source through hooks provided by the database (*1).
*1 This refers to DynamoDB Streams or Oracle's CHANGE NOTIFICATION.
Relying on Automatic Generation
When humans create things, their own philosophies enter the code. Sometimes this reduces readability or causes confusion. For example, API wrappers or Entities corresponding to DB schemas are easier to use for the consumers if they are created mechanically.
DB schema scaffolding has a long history, but for APIs as well, by following specifications like OpenAPI, GraphQL, or gRPC, you can automatically generate a sequence of code for API requests.
I often use code generation with OpenAPI, so I will note an example of that. In my work, I often use .NET for backend APIs and React.js or Vue.js for the frontend. In this case, I use openapi-generator to automatically generate an SDK that wraps the processing of requests to each endpoint from the OpenAPI definition YAML file created in the backend.
Even if the endpoint definition changes, I just regenerate it, so it keeps maintenance costs down. Furthermore, I am able to implement type-safe code through the OpenAPI definition file, even though the languages (C# and TypeScript) differ.
Also, in my company's system, there are layers even further below the backend APIs mentioned above, and they are also connected via APIs. Since those APIs also publish OpenAPI definition files, the consuming side generates an SDK from those definition files.

In the article below, I have documented how to achieve type safety by automatically generating an SDK for backend .NET and frontend TypeScript via an OpenAPI definition file, so please take a look if you are interested.
Conclusion
These are the 17 tips I am conscious of in my daily work for writing "good code."
In my environment, these points apply very well. However, how about in your environment?
Nowadays, many textbooks on OOP and design are published. However, trying to merge the contents of those books into your own work environment often doesn't go well. That is because the systems the authors create as samples, and your system, have entirely different requirements and environments.
In the end, I believe that to write good code, you must build many "drawers" (knowledge/tools), repeat trial and error to see how to incorporate them into your environment without conflict, and continue to accumulate study and experience. I am also continuing to input, thinking I want to write better code next time.
I will update this article when I can verbalize more good tips.
This ended up being a long post and somewhat poetic at the end. Haha. Thank you to everyone who read it for sparing your valuable time. 🙌
CHANGELOG
- 2022-12-18
- Inverted the conditional branch in "# Writing comments from the background" (determined from comments received that it was hard to understand as an early return).
- Refactored field name "id" to "userId".
- Refactored method name "validateXxx" to "isXxxValid".
- Fixed syntax errors in class.
Discussion
早期リターンの改善後のコードが以下になってますが、if文の判定に
!が足りていないように思います。ほんとですね!
教えてくれてありがとうございます。取り急ぎ修正しました。
今思うと「validateXX」は曖昧な名前でしたね。(しっかり自分で引っかかってしまいました😅)
DeepReadonlyを定義して、ReadonlyにDeepReadonlyしたり、
eslintとprettierで自動フォーマットするとよさそう🙆♂
DeepReadonly初めて聞きました!(ありがとうございます!!)
調べてみたら下記のリポジトリが便利そうなので、今度眺めてみようと思います👀
ですね!実際にTypeScriptで運用するときはどちらも組み込むようにしています🙆♂️
突然ですみません、第一目のコードなんですが、ここ間違っているじゃないでしょうか?
ここ
||ではなく、&&なのでは?日本語は下手なので、誤解したらすみません。
ここ、、サンプルコードが良くなかったですね。
早期リターンを例にせず、以下のようにしたほうが伝わりやすかったです。
早期リターンにする場合だと以下だけで条件クリアしているので
isOldTypeAccountの判定は不要ですものね。ご指摘ありがとうございます!
時間あるときに修正したいと思います🙆♂️