Clean Code: Classes

Vignesh Sathiyamurthy
2 min readSep 30, 2022
  • Class name should be noun, meaninful and in the title case with the first letter of each separate word capitalised.
class FileEntity {
}
class FileRepository {
}
class FileUploadService {
}
class FileResource {
}
  • A class is a conceptual representation of entity in your application and contains only functions whatever entity needs to do.
class UserService {    public UserEntity fetchUserByEmail(String Email) {
}
public List<UserEntity> fetchAllUsers() {
}
public List<UserEntity> fetchSubscribedUsers() {
}

public UserEntity updateUser(String id, UpdateUserRequest request) {
}

public UserEntity updateUserSubscription(String id, UpdateSubscriptionRequest request) {
}
public void deleteUserById(String id) {
}
public boolean isValidUser(String id) {
}
public boolean isSubscibedUser(String id) {
}
public void logoutUser(String id) {
}
}
  • Define functions are tightly focused and do them well.
  • It’s okay to have functions doing same thing but taking different parameters.
class UserService {    public UserEntity fetchUsers() {
}
public List<UserEntity> fetchUsers(boolean isSubscribed) {
}
public List<UserEntity> fetchUsers(FilterUserRequest request){
}
}
  • Class should small and contains average of fewer than 30 functions and 600 lines of code [each function has 20 lines of code].
  • Keep the utility methods and variables are private except some for testing.
  • To write clean functions inside class, please check my previous post https://vignesh-satya.medium.com/clean-code-functions-f3cb17b691e2

I kept this story short on purpose, because I don’t want to explain it all in a story. I’ll see you in another story.

--

--