-
Notifications
You must be signed in to change notification settings - Fork 137
Java attributes and methods
Java attributes and methods are essential parts of HMIS development.
Attributes store information such as:
- Patient name
- Patient code
- Bill total
- Created date
- Department
- Investigation
- Report status
- Retired status
Methods are used to:
- Read attribute values
- Change attribute values
- Validate data
- Calculate totals
- Process reports
- Search database records
- Clear filters
- Format information for display
A simple HMIS-style example is:
private String patientCode;
private double total;
private boolean retired;
public String getPatientCode() { return patientCode; }
public void setPatientCode(String patientCode) { this.patientCode = patientCode; }
public double calculateNetTotal(double discount) { return total - discount; }
In this example:
- patientCode, total, and retired are attributes.
- getPatientCode(), setPatientCode(), and calculateNetTotal() are methods.
An attribute stores data inside a Java component. Attributes are also called:
- Fields
- Member variables
- Instance variables
- Properties, especially when accessed through getters and setters
General syntax : accessModifier dataType attributeName;
private String patientName;
- private is the access modifier.
- String is the data type.
- patientName is the attribute name.
Exmples
- private Long id;
- private String patientCode;
- private Date createdAt;
- private Department department;
- private Investigation investigation;
- private boolean retired;
- private List results;
An attribute can be declared without an initial value.
private String patientName;
It can also be declared with an initial value.
private boolean retired = false;
A collection should often be initialized immediately.
private List results = new ArrayList<>();
This is safer than:
private List results;
because using an uninitialized list may cause a NullPointerException.
For example :
results.clear();
will fail when results is null.
Attributes may use primitive types or reference types.
Primitive attributes
private int patientCount;
private long recordCount;
private double total;
private boolean retired;
private char categoryCode;
- Primitive types cannot contain null.
Reference attributes
private String patientName;
private Date createdAt;
private Department department;
private Investigation investigation;
private List bills;
- Reference attributes can contain null.
Primitive
- int
- long
- double
- boolean
- char
- float
- short
- byte
Wrapper
- Integer
- Long
- Double
- Boolean
- Character
- Float
- Short
- Byte
Example:
private boolean retired;
private Boolean approved;
retired can contain:
- true
- false
approved can contain:
- true
- false
- null
Use primitive types when a value must always exist. And use wrapper types when the value may be unknown or nullable. For database query projections and DTO attributes, wrapper types are often safer.
Java automatically gives default values to attributes.
- int - 0
- long - 0L
- double - 0.0
- boolean - false
- char - Unicode zero
- Object reference - null
An instance attribute stores information specific to one Java component instance.
private String patientName;
private Department department;
private Date fromDate;
Each instance has its own values. For example, different report controllers may contain different selected dates and departments for different users. User-specific values should normally be instance attributes.
A static attribute may be shared across users and can create privacy, concurrency, and data-leak problems.
Correct:
private Patient selectedPatient;
Dangerous:
private static Patient selectedPatient;
A static attribute belongs to the Java type itself and is shared.
private static int reportCount;
A common valid static attribute is a constant.
private static final int DEFAULT_PAGE_SIZE = 50;
Another common attribute is:
private static final long serialVersionUID = 1L;
Avoid using static mutable attributes for:
- Selected patients
- Logged-in users
- Report results
- Date filters
- Department selections
- Patient medical data
- Bill details
Incorrect:
private static List selectedPatients;
Safer:
private List selectedPatients = new ArrayList<>();
A final attribute can be assigned only once.
private final int maximumResults = 100;
Constants usually use static final.
private static final int MAXIMUM_RESULTS = 100;
Naming convention for constants:
- UPPER_SNAKE_CASE
Examples:
private static final int DEFAULT_PAGE_SIZE = 50;
private static final String REPORT_TITLE = "Investigation Report";
private static final double TAX_RATE = 0.15;
A final reference cannot be assigned to a different object.
private final List codes = new ArrayList<>();
This is allowed:
codes.add("FBC");
This is not allowed:
codes = new ArrayList<>();
Attributes should normally be declared private.
- private String patientCode;
- private Date createdAt;
- private Department department;
Benefits:
- Protects internal data
- Prevents uncontrolled changes
- Supports validation through setters
- Reduces coupling
- Supports encapsulation
- Makes maintenance safer
Avoid:
public String patientCode;
Prefer:
private String patientCode;
public String getPatientCode() { return patientCode; }
public void setPatientCode(String patientCode) { this.patientCode = patientCode; }
A protected attribute can be accessed:
- Inside the same Java type
- Inside the same package
- Inside child types
protected Long id;
Protected attributes should be used carefully.
Prefer:
private EntityManager entityManager;
protected EntityManager getEntityManager() {
return entityManager;
}
rather than directly exposing the attribute.
A public attribute can be accessed from anywhere.
public String name;
Public mutable attributes are generally not recommended.
Problems include:
- No validation
- No control over changes
- Difficult debugging
- Strong coupling
- Inconsistent values
Prefer private attributes with getters and setters.
When no access modifier is written, Java uses package-private access.
String internalCode;
This attribute can be accessed only from the same package.
Package-private access may be useful for internal helper components, but attributes should still normally be private unless package access is intentionally required.
Java attributes use camelCase.
Correct:
private String patientName;
private Date createdAt;
private double netTotal;
private Department collectingCentre;
private List billItems;
Incorrect:
private String PatientName;
private Date created_at;
private double Net_Total;
private Department collectingcentre;
Rules for attribute names
Attribute names should:
- Begin with a lowercase letter
- Use camelCase
- Clearly describe the stored value
- Avoid unexplained abbreviations
- Avoid meaningless names
- Use nouns or noun phrases
- Use plural names for collections
- Use positive and clear names for Boolean values
Good:
private Date fromDate;
private Date toDate;
private Department laboratory;
private Investigation investigation;
private List<PatientInvestigation> results;
private boolean retired;
Weak:
private Date d1;
private Date d2;
private Department dep;
private Investigation inv;
private List data;
private boolean flag;
Collections should normally use plural names.
Correct:
private List<Bill> bills;
private List<Patient> patients;
private List<Investigation> investigations;
private Set<String> codes;
private Map<String, Object> parameters;
Incorrect:
private List<Bill> bill;
private List<Patient> patient;
The name should communicate that multiple values are stored.
Boolean attribute names should clearly describe a true or false state.
Good:
private boolean retired;
private boolean cancelled;
private boolean active;
private boolean approved;
private boolean printed;
private boolean editable;
Avoid unclear names:
private boolean flag;
private boolean status;
private boolean value;
private boolean check;
Boolean names should allow readable conditions.
if (bill.isCancelled()) {
}
if (report.isEditable()) {
}
Avoid double-negative names.
Confusing:
private boolean notInactive;
Better:
private boolean active;
Date attributes should clearly describe what the date represents.
Good:
private Date createdAt;
private Date lastEditedAt;
private Date retiredAt;
private Date fromDate;
private Date toDate;
private Date dateOfBirth;
private Date appointmentDate;
Avoid:
private Date date1;
private Date date2;
private Date time;
Use At for timestamps:
- createdAt
- updatedAt
- retiredAt
Use Date when only a date concept is represented:
- billDate
- appointmentDate
- dateOfBirth
@ManyToOne
private Department department;
@ManyToOne
private Institution institution;
@ManyToOne
private Investigation investigation;
@ManyToOne
private Patient patient;
Relationship attribute names should represent the related object.
Correct:
private Department department;
Avoid:
private Long departmentId;
inside a normal JPA relationship when an entity relationship is required.
A DTO may use an ID:
private Long departmentId;
private String departmentName;
because DTOs are lightweight data carriers.
A persisted attribute is stored in the database.
private String comments;
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
@ManyToOne
private Department department;
Persisted attributes may be used by:
- JPA
- Database columns
- JPQL queries
- Reports
- Services
- XHTML pages
- Existing integrations
Do not rename or remove existing persisted attributes without checking all usages.
Search for:
- Java getter and setter calls
- JPQL attribute references
- XHTML expressions
- Database migration scripts
- DTO projections
- Reports
- API integrations
A transient JPA attribute is not stored in the database.
@Transient
private String displayName;
It can be used for:
- Calculated values
- Temporary display values
- UI-only data
- Export-only data
Example:
@Transient
private String ageAsString;
Getter:
public String getAgeAsString() {
`return ageAsString;`
}
A calculated attribute may also be returned directly by a method without storing it.
public String getDisplayName() {
`return title + " " + name;`
}
JPQL generally cannot query calculated getter-only properties unless they are mapped persistent attributes.
Application contains sensitive healthcare and personal information.
Examples include:
private String patientName;
private String nationalIdentityCardNumber;
private String mobileNumber;
private String address;
private String diagnosis;
private String investigationResult;
private String prescriptionDetails;
Sensitive attributes require careful handling.
Important rules
Do not:
- Declare them as public
- Store them in static fields
- Print them unnecessarily
- Add them to error messages
- Include them in toString() without a clear need
- Log full patient details
- Expose them through unrelated getters
- Return them in DTOs that do not require them
- Store passwords as plain text
- Include secrets in source code
Bad:
@Override
public String toString() {
`return patientName`
`+ " "`
`+ nationalIdentityCardNumber`
`+ " "`
`+ diagnosis;`
}
Safer:
@Override
public String toString() {
`return patientCode;`
}
Logging should avoid unnecessary patient data.
Bad:
logger.info(
`"Patient " + patientName`
`+ " diagnosis is " + diagnosis`
);
Better:
logger.info(
`"Patient record processing completed. Record ID: "`
`+ patientId`
);
Even IDs should only be logged when operationally necessary.