Programming 10 Best Practises in any language e.g. C/Java/Javascript/Python .. | Read |
Coding and Problem-solving Skills are essential for delivering high quality software applications. Some of the good practises are as follows:
1. Modular and Efficient code (Reuse code by writing common functions). This helps in code optimization.
2. Null checks (guard clause for validation check null and return), proper variable names, null & length check,
set default values wherever possible.
3. Memory handling needs to be done in code in case of C programming.
4. Initialize/Reset variables in case of nested while loops.
5. Write Code Comments, makes easy to read code & understand the logic. Helps in maintaining and keeping code defect free.
6. Make code configurable for attributes whose values might change.
7. Refering cache in order to reduce database calls for better performance.
8. Code reviews by Peers. This makes us learn from each other and improve our skills.
9. Analysing log files to troubleshoot issues.
10. Happy Coding. Write great code and use great languages.
Other tips include:
- Embracing simplicity and avoiding unnecessary complexity
- Using built-in features and libraries
- Being mindful of performance
- Prioritizing human readability and writing comments for understanding
- Using meaningful variable names
- VSCode is an excellent code editor for development. Github Copilot can be enabled for assisting in coding.
|
|
|
|
Important Functions in C Programming .. | Read |
Function Name | Details |
strcmp() | compares two strings and returns zero if they are identical. |
strstr() | useful for searching and extracting substrings within larger strings! |
sprintf() | formats and stores output in a character string buffer. |
sscanf() | reads formatted input from a string in the provided variables. |
strcpy() | copies a string from one location to another. |
strlen() | calculates the length of a given string (excluding the null character). |
localtime() | converts time_t variable to a structure of type tm. |
mktime() | converts structure of type tm to a time_t variable. |
strptime() | converts time stored in string variable to struct tm variable (according to the given string format). |
strftime() | converts struct tm variable to string for printing to log for debugging. |
atoi_64() | converts string to numeric value. |
malloc() | dynamically allocates memory on the heap. |
free() | deallocates memory previously allocated by malloc().Helps prevent memory leaks by releasing unused memory. |
Code snippets for strcmp(), sprintf():
if(str1 && str2 && strcmp(str1, str2) == 0)
{
sprintf(printbuff, "str1 and str2 Strings are same and values are %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 characters from str1 into integer variable 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 "epoch_time" into struct tm variable "new_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 variable into unixtimestamp epoch variable
|
|
|
Java Annotations .. | Read |
Annotations help in avoid writing bolierplate code and improves coding efficiency. Below are some common Java Annotations:
Annotation Name | Details |
@Autowired | Facilitates dependency injection, automatically injecting Spring beans into your classes without explicit instantiation |
@Override | Overrides the default implementation |
@LogExecutionTime | Logs time take in execution of function |
@Component | Designates a Java class as a Spring-managed component |
@Slf4j | Logging annotation for Spring Boot applications |
@Repository | Indicate that a class is a Data Access Object (DAO) or repository, signifying its role in interacting with the database |
@Entity | To treat a Java class as a persistent entity, making it easier to perform database operations |
@Getter @Setter | Creates Getter and Setter functions automatically without explicitly defining them |
@ToString | Current state of the object will be returned as a String when toString() will be called |
@Id | Spring Data JPA – @Id Annotation, used to mark a field as the primary key of an entity |
Note: Lombok is a Java library that can generate known patterns of code for us, allowing us to reduce the boilerplate code.
|
|
|
Essential Unix Commands .. | Read |
Search string/pattern using grep commands:
grep Command | Details |
grep -n "string" <filename> | search string with line numbers displayed |
grep -i "string" <filename> | case insensitive search |
grep -r "string" | recursive search in folders/sub folders |
grep -E -w "Enter|Exit" <filename> | w word match, E regular expression |
grep "lines.*empty" <filename> | searches all patterns that starts with “lines” and ends with “empty” with anything in-between |
grep -A <N> "string" <filename> | N lines displayed after the match |
grep -B <N> "string" <filename> | N lines displayed before the match |
grep -C 2 "Example" <filename> | 2 lines from both after and before the match |
grep -c "pattern" <filename> | count that how many lines matches |
grep -v "pattern" <filename> | display the lines which does not matches |
grep -v -e "pattern" -e "pattern" <filename> | does not matches all the given pattern |
grep -l "pattern" <filename>* | display only the file names which matches |
Other Important Unix commands:
Command | Details |
ps -ef| grep cm | awk -F ' ' '{print $2}' | 'ps' command to check running process and 'awk' command to select column 2 (delimit values based on space) |
sed -n -e '18120, 18130p' <filename> | 'sed' command to copy based on line number 18120 to 18130 from a file |
sed -i 's/bill/invoice/g' <filename> | 'sed' command to replace word bill with invoice in a file |
sed -i '/bill/d' <filename> | 'sed' command to delete the lines of a file containing "bill" as a string |
grep -n "string" <filename> | awk -F ' ' '{print $1}' | cut -d ':' -f1 | 'cut' command to delimit output by colon and print first field |
netstat -a | grep <port-number> | To check if the 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 for long running jobs (runs even if current terminal is terminated) |
kill, pkill | terminate process using processid (kill) and by process name (pkill) |
tail | prints data from the end of a specified file |
vi <filename> | widely used text editor in UNIX |
|
|
|
|
Commonly used Git Commands .. | Read |
Git is widely used as a version control system. Below commands helps 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/commiting |
grep commit -m "comment" | Commit the files added to be checked in to git branch |
git push origin <branchname> | Push or checkin the commit into the branch |
git status | Provides information about the Git branch and files status |
git branch | Lists the git branches and the current branch checked-out in system |
git checkout <branchname> | Checkout/move to a different Git branch |
git checkout <branchname> -- <filename> | Get a file from a particular branch in the system |
git pull | Fetch all the latest files from current branch |
git fetch | Fetch the new branches created from the Git repository |
grep reset --hard <branchname> | Forceful checkout to a branch, if git checkout fails due to some reason |
|
|
|
|
Oracle SQL Performance tuning .. | Read |
Below are some key points to consider for Oracle SQL tuning:
1. "SELECT" queries tuning tricks. Query performance can be validated using "Explain Plan" option in SQL developer.
a. Parallel hint (/*+ parallel(8) */) with increased no of threads to perform faster processing.
b. Using columns with index in where clause of select statements
c. Using DB partitions to query data
d. Use WITH clause in select queries, in order to make changes in future easier
d. Use EXISTS instead of COUNT in queries
e. Leverage Oracle Json functions (JSON_ARRAYAGG, JSON_VALUE) for multiple columns selection
2. PL/SQL Performance Improvement - Use BULK COLLECT and FORALL for bulk DML updates for less context switching
3. Using Oracle SQL Developer tool
a. Query performance analysis using explain plan
b. Export data to xls or clipboard
c. Import data into table using "sqlldr" utility from unix (faster compared to insert queries)
d. SQL Developer shortcuts:
Ctrl+F7: Format SQL query
Shift+F4: Opens a describe window for current object/table at cursor
F10: SQL cost estimate (Explain Plan)
|
|
|
|
Oracle DB long running queries .. | Read |
If any Oracle Database transaction is taking longer time than expected, most likely the DB query processing is stuck or waiting for another session to complete.
Below queries are useful to identify the long running queries:
- 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 Runnning 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#';
|
|
|