Coding Cheatsheets
|Programming Best Practices
Coding and problem-solving skills are essential for delivering high-quality software applications. Some good practices:
- Modular and Efficient Code — Reuse code by writing common functions. Helps with code optimization.
- Null checks — Guard clause for validation: check null and return. Proper variable names, null & length checks, set default values wherever possible.
- Memory handling — Needs to be done in C programming code.
- Initialize/Reset variables — Especially in nested while loops.
- Write Code Comments — Makes it easy to read and understand logic. Helps maintain defect-free code.
- Make code configurable — For attributes whose values might change.
- Refer cache — In order to reduce database calls for better performance.
- Code reviews by peers — Helps us learn from each other and improve skills.
- Analyse log files — To troubleshoot issues.
- Happy Coding — Write great code and use great languages.
Other tips:
- Embrace simplicity and avoid unnecessary complexity
- Use built-in features and libraries
- Be mindful of performance
- Prioritize human readability; write comments for understanding
- Use meaningful variable names
VSCodeis an excellent code editor. GitHub Copilot can be enabled for AI-assisted coding.
Important Functions in C Programming
| Function Name | Details |
|---|---|
strcmp(str1, str2) | Compares two strings and returns zero if they are identical. |
strstr(haystack, needle) | Find first occurrence of substring needle in haystack. |
sprintf(dest, format, ...) | Formats and stores output in a character string buffer. |
sscanf(str, format, ...) | Reads formatted input from a string into provided variables. |
strcpy(dest, src) | Copies a string from one location to another. |
strlen(str) | Calculates the length of a given string (excluding the null character). |
localtime(timep) | Converts time_t variable to a structure of type tm. |
mktime(tm_info) | Converts structure of type tm to a time_t variable. |
strptime(time_str, format, tm_info) | Converts time stored in string variable to struct tm according to the given format. |
strftime(time_str, size, format, tm_info) | Converts struct tm to string for printing to log. |
atoi_64(str) | Converts string to numeric value. |
malloc(size) | Dynamically allocates memory on the heap. |
free(strp) | Deallocates memory previously allocated by malloc(). Prevents memory leaks. |
Code snippets for strcmp(), sprintf():
if(str1 && str2 && strcmp(str1, str2) == 0)
{
sprintf(printbuff, "str1 and str2 are same: %s and %s\n", str1, str2);
}
strstr() & sscanf():
if(str1 && str2 && strstr(str1, str2) != NULL) {
sprintf(printfbuff, "str2 is present in str1\n");
sscanf(str1, "%2d", strmmdd); //read first 2 chars from str1 into integer strmmdd
}
The struct tm represents date and time information — used for manipulating and formatting time-related data:
time_t epoch_time = <time-unixtimestamp> struct tm new_tm = localtime(&epoch_time); //store unix timestamp into struct tm //Adjust new_tm new_tm->tm_mon = <month>; new_tm->tm_year = <year>; new_tm->tm_mday = <dayofmonth>; new_tm->tm_hour = 0; new_tm->tm_min = 0; new_tm->tm_sec = 0; new_tm->tm_isdst = -1; time_t new_unixtime = mktime(&new_tm); //convert struct tm back to epoch
Java Annotations
Annotations help avoid writing boilerplate code and improve coding efficiency. Common Java Annotations:
| Annotation | Details |
|---|---|
@Autowired | Facilitates dependency injection — automatically injects Spring beans without explicit instantiation. |
@Override | Overrides the default implementation. |
@LogExecutionTime | Logs time taken in execution of function. |
@Component | Designates a Java class as a Spring-managed component. |
@Slf4j | Logging annotation for Spring Boot applications. |
@Repository | Indicates a class is a Data Access Object (DAO) or repository for database interaction. |
@Entity | Treats a Java class as a persistent entity, making database operations easier. |
@Getter / @Setter | Creates getter and setter functions automatically without explicit definitions. |
@ToString | Current state of the object is returned as a String when toString() is called. |
@Id | Spring Data JPA — marks a field as the primary key of an entity. |
Note: Lombok is a Java library that generates known patterns of code, allowing us to reduce boilerplate.
Essential Unix Commands
Search string/pattern using grep commands:
| grep Command | Details |
|---|---|
grep -n "string" <file> | Search string with line numbers displayed. |
grep -i "string" <file> | Case-insensitive search. |
grep -r "string" | Recursive search in folders/sub-folders. |
grep -E -w "Enter|Exit" <file> | -w word match, -E regular expression. |
grep "lines.*empty" <file> | Matches patterns starting with "lines" and ending with "empty". |
grep -A <N> "string" <file> | N lines displayed after the match. |
grep -B <N> "string" <file> | N lines displayed before the match. |
grep -C 2 "Example" <file> | 2 lines from both before and after the match. |
grep -c "pattern" <file> | Count how many lines match. |
grep -v "pattern" <file> | Display lines which do NOT match. |
grep -v -e "p1" -e "p2" <file> | Does not match any of the given patterns. |
grep -l "pattern" <file> | Display only file names which match. |
grep "post_rating.*entering\|post_rating.*exiting" <file> | Check for function entry/exit. |
Other important Unix commands:
| Command | Details |
|---|---|
ps -ef | grep cm | awk -F ' ' '{print $2}' | ps to check running processes; awk to select column 2 (delimiter: space). |
sed -n -e '18120,18130p' <file> | sed to copy lines 18120–18130 from a file. |
sed -n '/2024-01-01 10:00/,/2024-01-01 11:00/p' <file> | Filter logs by time range. |
sed -i 's/bill/invoice/g' <file> | Replace word "bill" with "invoice" in a file. |
sed -i '/bill/d' <file> | Delete lines containing "bill". |
grep -n "string" <file> | awk '{print $1}' | cut -d ':' -f1 | cut to delimit output by colon and print first field. |
netstat -a | grep <port> | Check if a given port number is in use. |
top | Displays CPU usage, memory usage, running processes. |
df or du | Displays disk space usage. |
jobs | Lists active jobs running. |
nohup <command> & | Executes script/command in background (runs even if terminal is terminated). |
kill, pkill | Terminate process by PID (kill) or by name (pkill). |
tail | Prints data from the end of a specified file. |
vi <file> | Widely used text editor in Unix. |
Commonly Used Git Commands
Git is widely used as a version control system. Below commands help in managing files in Git:
| git Command | Details |
|---|---|
git add <filename> | Add one or more files to be checked in. |
git add -u | Adds all tracked files for staging/committing. |
git commit -m "comment" | Commit the staged files to the git branch. |
git push origin <branchname> | Push or check in the commit into the branch. |
git status | Provides information about the Git branch and file status. |
git branch | Lists git branches and the current branch checked out. |
git checkout <branchname> | Checkout/move to a different Git branch. |
git checkout <branchname> -- <filename> | Get a file from a particular branch. |
git pull | Fetch all the latest files from current branch. |
git fetch | Fetch new branches created from the Git repository. |
git reset --hard <branchname> | Forceful checkout to a branch if git checkout fails. |
Oracle SQL Performance Tuning
Key points to consider for Oracle SQL tuning:
- SELECT query tuning — Validate using "Explain Plan" in SQL Developer.
- Parallel hint (
/*+ parallel(8) */) with increased thread count for faster processing. - Use columns with index in
WHEREclause. - Use DB partitions to query data.
- Use
WITHclause for queries to make future changes easier. - Use
EXISTSinstead ofCOUNT. - Leverage Oracle JSON functions (
JSON_ARRAYAGG,JSON_VALUE) for multiple column selection.
- Parallel hint (
- PL/SQL Performance — Use
BULK COLLECTandFORALLfor bulk DML updates to reduce context switching. - Oracle SQL Developer shortcuts:
Ctrl+F7: Format SQL queryShift+F4: Opens describe window for current object/table at cursorF10: SQL cost estimate (Explain Plan)- Export data to XLS or clipboard
- Import data using
sqlldrutility from Unix (faster than insert queries)
Oracle DB Long-Running Queries
If any Oracle Database transaction is taking longer than expected, the DB query processing is likely stuck or waiting for another session to complete.
-
Fetch blocking sessions due to table lock:
select (select username from v$session where sid=a.sid) blocker, a.sid, ' is blocking ', (select username from v$session where sid=b.sid) blockee, b.sid from v$lock a, v$lock b where a.block = 1 and b.request > 0 and a.id1 = b.id1 and a.id2 = b.id2; -
Percentage completion of long-running sessions:
select sid, to_char(start_time,'hh24:mi:ss') stime, message, (sofar/totalwork) * 100 percent from v$session_longops where sofar/totalwork < 1; -
Fetch active DB sessions:
select S.USERNAME, s.sid, s.osuser, t.sql_id, sql_text from v$sqltext_with_newlines t, V$SESSION s where t.address = s.sql_address and t.hash_value = s.sql_hash_value and s.status = 'ACTIVE' and s.username <> 'SYSTEM' order by s.sid, t.piece;
-
Kill DB session (if needed):
select username, sid, serial# from v$session where sid=xxxx; alter system kill session 'sid#,serial#';
Recordings: YouTube channel videos