├── Algorithm └── two pointer.md ├── DataBase ├── MongoDB │ └── MongoDB CheatSheet.md ├── NoSQL Introduction │ ├── NoSQL Introduction.pdf │ └── Notes.md ├── PL SQL │ └── scaler.md └── SQLExamples │ └── Weather Observation Station 5.md ├── IntelliJ └── IntelliJ basics.md ├── Java ├── Exceptions │ ├── best practices files │ │ ├── Avoid Returning null in Exception Handling.md │ │ ├── Be Careful What You Log.md │ │ ├── Check for Suppressed Exceptions.md │ │ ├── Custom Exceptions.md │ │ ├── Don’t Bury Thrown Exceptions.md │ │ ├── Don’t Close Resources Manually.md │ │ ├── Don’t Log and Rethrow.md │ │ ├── Exception Chaining.md │ │ ├── Keep Exception Handling Separate.md │ │ ├── Throw Early and Handle Exceptions Late.md │ │ └── Using return in a finally Block Is an Anti-Pattern.md │ └── best practices.md ├── Generics │ ├── Chapters │ │ ├── Lower Bounded Wildcards.md │ │ ├── Unbounded Wildcards.md │ │ └── Upper Bounded Wildcards.md │ └── Generics.md └── Hibernate │ ├── Hibernate.md │ ├── HibernateDemo │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── github │ │ └── javabaz │ │ └── Main.java │ ├── assets │ └── 01 - Hibernate Architecture.png │ └── chapters │ ├── Hibernate Lifecycle.md │ └── ldentifierGenerator.md ├── LICENSE ├── Paradigms └── Event-driven.md ├── README.md └── REST API └── REST API.md /Algorithm/two pointer.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaBaz/presentations/1c97989f746238dfa6b7a1d7f43e51ebbd205ad3/Algorithm/two pointer.md -------------------------------------------------------------------------------- /DataBase/MongoDB/MongoDB CheatSheet.md: -------------------------------------------------------------------------------- 1 | # MongoDB Cheat Sheet 2 | 3 | ## Table of Contents 4 | 1. [Installation](#installation) 5 | 2. [Basics of MongoDB](#basics-of-mongodb) 6 | 3. CRUD 7 | 3.1 [Create](#create) 8 | 3.2 [Read](#read) 9 | 3.3 [Update](#update) 10 | 3.4 [Delete](#delete) 11 | 12 | 13 | 14 | ## Installation 15 | To install MongoDB, follow the official [MongoDB installation guide](https://docs.mongodb.com/manual/installation/). 16 | 17 | 18 | 19 | 20 | ## Basics of MongoDB 21 | To **Start** database, use the following command: 22 | 23 | ```bash 24 | mongod 25 | ``` 26 | 27 | To **Connect** database, use the following command: 28 | 29 | ```bash 30 | mongo 31 | ``` 32 | 33 | [PS : mongo vs mongod](https://stackoverflow.com/questions/4883045/mongodb-difference-between-running-mongo-and-mongod-databases) 34 | 35 | 36 | To **Show name of current database** database, use the following command: 37 | 38 | ```bash 39 | db 40 | ``` 41 | 42 | 43 | To **Show all databases**, use the following command: 44 | 45 | ```bash 46 | show dbs 47 | ``` 48 | 49 | 50 | To **Switch to database db**, use the following command: 51 | 52 | ```bash 53 | use db 54 | ``` 55 | 56 | 57 | To **Display current database collec­tions**, use the following command: 58 | 59 | ```bash 60 | show collec­tions 61 | ``` 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | ## CRUD 70 | 71 | ### Create 72 | To **insert document(s) returns write result**, use the following command: 73 | 74 | ```bash 75 | insert­(data) 76 | ``` 77 | 78 | 79 | To **insert one document**, use the following command: 80 | 81 | ```bash 82 | insertOne (data, options) 83 | ``` 84 | 85 | 86 | 87 | To **insert many documents**, use the following command: 88 | 89 | ```bash 90 | insert­Man­y(data, options) 91 | ``` 92 | 93 | 94 | 95 | 96 | To **insert many documents**, use the following command: 97 | 98 | ```bash 99 | insert­Man­y(data, options) 100 | ``` 101 | 102 | if **needs square brackets**, use the following command: 103 | 104 | ```bash 105 | insert­Man­y([­{},­{},{}]) 106 | ``` 107 | 108 | ### Read 109 | 110 | To **Display documents from collection**, use the following command: 111 | 112 | ```bash 113 | db.co­­lle­­ct­i­o­n.f­­ind() 114 | ``` 115 | 116 | To **find all matching documents**, use the following command: 117 | 118 | ```bash 119 | find(f­ilter, options) 120 | ``` 121 | 122 | 123 | To **find first matching document**, use the following command: 124 | 125 | ```bash 126 | findOn­e(f­ilter, options) 127 | ``` 128 | 129 | ### Update 130 | 131 | 132 | 133 | To **Change one document**, use the following command: 134 | 135 | ```bash 136 | update­One­(fi­lter, data, options) 137 | ``` 138 | 139 | 140 | 141 | To **Change many documents**, use the following command: 142 | 143 | ```bash 144 | update­Man­y(f­ilter, data, options) 145 | ``` 146 | 147 | 148 | 149 | To **Replace document entirely**, use the following command: 150 | 151 | ```bash 152 | replac­eOn­e(f­ilter, data, options) 153 | ``` 154 | 155 | ### Delete 156 | 157 | 158 | To **Delete one document**, use the following command: 159 | 160 | ```bash 161 | delete­One­(fi­lter, options) 162 | ``` 163 | 164 | 165 | 166 | To **Delete many documents**, use the following command: 167 | 168 | ```bash 169 | delete­Man­y(f­ilter, options) 170 | ``` 171 | 172 | 173 | 174 | -------------------------------------------------------------------------------- /DataBase/NoSQL Introduction/NoSQL Introduction.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaBaz/presentations/1c97989f746238dfa6b7a1d7f43e51ebbd205ad3/DataBase/NoSQL Introduction/NoSQL Introduction.pdf -------------------------------------------------------------------------------- /DataBase/NoSQL Introduction/Notes.md: -------------------------------------------------------------------------------- 1 | ### Usefull links 2 | [How to Choose the Right NoSQL Database](https://www.dataversity.net/choose-right-nosql-database-application/) 3 | 4 | [MongoDB Questions and Answers – Introduction to MongoDB](https://www.sanfoundry.com/mongodb-questions-answers-basics/) 5 | -------------------------------------------------------------------------------- /DataBase/PL SQL/scaler.md: -------------------------------------------------------------------------------- 1 | ### SUBSTR 2 | returns a string value. If length is a negative number 3 | 4 | ```sql 5 | SELECT COLUMN_NAME, SUBSTR(COLUMN_NAME, start_position [, length ] ) 6 | FROM TABLE_NAME 7 | ``` 8 | > NOTE: it might return null values. 9 | 10 | > NOTE: If length is a negative number, then the SUBSTR function will return a NULL value. 11 | 12 |
13 | 14 | ------ 15 | 16 | ### LENGTH 17 | returns the length of the specified string. 18 | 19 | If string1 is NULL, then the LENGTH function will return NULL. 20 | 21 | ```sql 22 | SELECT COLUMN_NAME, LENGTH(COLUMN_NAME) 23 | FROM TABLE_NAME 24 | ``` 25 | 26 |
27 | 28 | ------ 29 | 30 | 31 | ### CONCAT 32 | allows you to concatenate two strings together. 33 | 34 | 35 | ```sql 36 | SELECT CONCAT( string1, string2 ) 37 | FROM TABLE_NAME 38 | ``` 39 | 40 |
41 | 42 | ------ 43 | 44 | 45 | ### LOWER 46 | converts all letters in the specified string to lowercase. 47 | 48 | ```sql 49 | SELECT LOWER(COLUMN_NAME) 50 | FROM TABLE_NAME 51 | ``` 52 | > NOTE: If there are characters in the string that are not letters, they are unaffected by this function. 53 |
54 | 55 | ------ 56 | 57 | 58 | ### UPPER 59 | converts all letters in the specified string to uppercase. 60 | ```sql 61 | SELECT UPPER (COLUMN_NAME) 62 | FROM TABLE_NAME 63 | ``` 64 | > NOTE: If there are characters in the string that are not letters, they are unaffected by this function. 65 |
66 | 67 | ------ 68 | 69 | ### INSTR 70 | returns the location of a substring in a string. 71 | 72 | ```sql 73 | SELECT INSTR( string, substring [, start_position [, th_appearance ] ] ) 74 | FROM TABLE_NAME 75 | ``` 76 |
77 | 78 | ------ 79 | 80 | ### LPAD 81 | pads the left-side of a string with a specific set of characters (when string1 is not null). 82 | 83 | ```sql 84 | SELECT LPAD( string1, padded_length [, pad_string] ) 85 | FROM TABLE_NAME 86 | ``` 87 | > NOTE: If "pad_string" parameter is omitted, the LPAD function will pad spaces to the left-side of string1. 88 |
89 | 90 | ------ 91 | 92 | ### RPAD 93 | pads the right-side of a string with a specific set of characters (when string1 is not null). 94 | 95 | ```sql 96 | SELECT RPAD( string1, padded_length [, pad_string] ) 97 | FROM TABLE_NAME 98 | ``` 99 | > NOTE: If "pad_string" parameter is omitted, the RPAD function will pad spaces to the right-side of string1. 100 |
101 | 102 | ------ 103 | 104 | ### TO_CHAR 105 | converts a number or date to a string. 106 | 107 | ```sql 108 | SELECT TO_CHAR( value [, format_mask] [, nls_language] ) 109 | FROM TABLE_NAME 110 | ``` 111 | #### Example 112 | ``` 113 | TO_CHAR(1210.73, '9999.9') 114 | Result: ' 1210.7' 115 | 116 | TO_CHAR(-1210.73, '9999.9') 117 | Result: '-1210.7' 118 | 119 | TO_CHAR(1210.73, '9,999.99') 120 | Result: ' 1,210.73' 121 | 122 | TO_CHAR(1210.73, '$9,999.00') 123 | Result: ' $1,210.73' 124 | 125 | TO_CHAR(21, '000099') 126 | Result: ' 000021' 127 | ``` 128 | 129 |
130 | 131 | #### Example 132 | 133 | ``` 134 | TO_CHAR(sysdate, 'yyyy/mm/dd') 135 | Result: '2003/07/09' 136 | 137 | TO_CHAR(sysdate, 'Month DD, YYYY') 138 | Result: 'July 09, 2003' 139 | 140 | TO_CHAR(sysdate, 'FMMonth DD, YYYY') 141 | Result: 'July 9, 2003' 142 | 143 | TO_CHAR(sysdate, 'MON DDth, YYYY') 144 | Result: 'JUL 09TH, 2003' 145 | 146 | TO_CHAR(sysdate, 'FMMON DDth, YYYY') 147 | Result: 'JUL 9TH, 2003' 148 | 149 | TO_CHAR(sysdate, 'FMMon ddth, YYYY') 150 | Result: 'Jul 9th, 2003' 151 | ``` 152 | 153 | >NOTE: You will notice that in some TO_CHAR function examples, the format_mask parameter begins with "FM". This means that zeros and blanks are suppressed. This can be seen in the examples below. 154 | 155 | #### Example 156 | ``` 157 | TO_CHAR(sysdate, 'FMMonth DD, YYYY') 158 | Result: 'July 9, 2003' 159 | 160 | TO_CHAR(sysdate, 'FMMON DDth, YYYY') 161 | Result: 'JUL 9TH, 2003' 162 | 163 | TO_CHAR(sysdate, 'FMMon ddth, YYYY') 164 | Result: 'Jul 9th, 2003' 165 | ``` 166 | 167 | ------ 168 | 169 | ### ROUND 170 | returns a number rounded to a certain number of decimal places. 171 | 172 | ```sql 173 | SELECT ROUND( number [, decimal_places] ) 174 | FROM TABLE_NAME 175 | ``` 176 | > NOTE: "decimal_places" parameter is Optional. It's the number of decimal places rounded to. This value must be an integer. If this parameter is omitted, the ROUND function will round the number to 0 decimal places. 177 | 178 |
179 | 180 | #### Example 181 | ``` 182 | ROUND(125.315) 183 | Result: 125 184 | 185 | ROUND(125.315, 0) 186 | Result: 125 187 | 188 | ROUND(125.315, 1) 189 | Result: 125.3 190 | 191 | ROUND(125.315, 2) 192 | Result: 125.32 193 | 194 | ROUND(125.315, 3) 195 | Result: 125.315 196 | 197 | ROUND(-125.315, 2) 198 | Result: -125.32 199 | ``` 200 | ------ 201 | 202 | ### TRUNC 203 | returns a date truncated to a specific unit of measure. 204 | 205 | ```sql 206 | SELECT TRUNC ( date [, format ] ) 207 | FROM TABLE_NAME 208 | ``` 209 | format : 210 | 211 | | Unit | Valid format parameters | 212 | | ---- | ----------------------- | 213 | | Content Cell | Content Cell | 214 | | Year | SYYYY, YYYY, YEAR, SYEAR, YYY, YY, Y | 215 | | ISO Year | IYYY, IY, I | 216 | | Quarter | Q | 217 | | Month | MONTH, MON, MM, RM | 218 | | Week | WW | 219 | | IW | IW | 220 | | W | W | 221 | | Day | DDD, DD, J | 222 | | Start day of the week | DAY, DY, D | 223 | | Hour | HH, HH12, HH24 | 224 | | Minute | MI | 225 | 226 | 227 | 228 |
229 | 230 | #### Example 231 | ``` 232 | TRUNC(TO_DATE('22-AUG-03'), 'YEAR') 233 | Result: '01-JAN-03' 234 | 235 | TRUNC(TO_DATE('22-AUG-03'), 'Q') 236 | Result: '01-JUL-03' 237 | 238 | TRUNC(TO_DATE('22-AUG-03'), 'MONTH') 239 | Result: '01-AUG-03' 240 | 241 | TRUNC(TO_DATE('22-AUG-03'), 'DDD') 242 | Result: '22-AUG-03' 243 | 244 | TRUNC(TO_DATE('22-AUG-03'), 'DAY') 245 | Result: '17-AUG-03' 246 | ``` 247 | 248 | ------ 249 | 250 | 251 | ### SYSDATE 252 | returns the current system date and time on your local database. 253 | 254 | ```sql 255 | SELECT SYSDATE 256 | FROM DUAL 257 | ``` 258 | #### Example 259 | ```sql 260 | SELECT TO_CHAR(SYSDATE, 'yyyy/mm/dd') 261 | FROM DUAL 262 | ``` 263 | 264 | ------ -------------------------------------------------------------------------------- /DataBase/SQLExamples/Weather Observation Station 5.md: -------------------------------------------------------------------------------- 1 | Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically. 2 | The STATION table is described as follows: 3 |
4 | 5 | ![structure of table](https://s3.amazonaws.com/hr-challenge-images/9336/1449345840-5f0a551030-Station.jpg) 6 | 7 | 8 | Sample Input 9 | 10 | For example, CITY has four entries: DEF, ABC, PQRS and WXY. 11 | 12 | Sample Output 13 | 14 | ABC 3 15 | PQRS 4 16 | 17 | ---- 18 | My answer : 19 | 20 | ```SQL 21 | (SELECT CITY, Length(CITY) 22 | FROM STATION 23 | ORDER BY LENGTH(CITY), CITY ASC 24 | LIMIT 1) 25 | 26 | UNION ALL 27 | 28 | (SELECT CITY, Length(CITY) 29 | FROM STATION 30 | ORDER BY LENGTH(CITY) DESC, CITY DESC 31 | LIMIT 1) 32 | ``` 33 | 34 | OR 35 | 36 | ```SQL 37 | SELECT City, LENGTH(City) AS CityLength 38 | FROM STATION 39 | ORDER BY CityLength ASC, City 40 | LIMIT 1; 41 | 42 | SELECT City, LENGTH(City) AS CityLength 43 | FROM STATION 44 | ORDER BY CityLength DESC, City 45 | LIMIT 1; 46 | ``` 47 | 48 | OR 49 | 50 | ```SQL 51 | SELECT City, CityLength 52 | FROM ( 53 | SELECT City, LENGTH(City) AS CityLength, 54 | ROW_NUMBER() OVER (ORDER BY LENGTH(City), City) AS AscRank, 55 | ROW_NUMBER() OVER (ORDER BY LENGTH(City) DESC, City) AS DescRank 56 | FROM STATION 57 | ) Ranked 58 | WHERE AscRank = 1 OR DescRank = 1; 59 | ``` -------------------------------------------------------------------------------- /IntelliJ/IntelliJ basics.md: -------------------------------------------------------------------------------- 1 | # IntelliJ IDEA Shortcuts 2 | 3 | **1) Mouse Zoom Setting** 4 | 5 | **2) Basic Movement (using CTRL and Arrow keys)** 6 | 7 | - Use CTRL + Arrow keys for basic movement. 8 | 9 | **3) Line Manipulation:** 10 | 11 | - CTRL + Shift + Arrow keys: Move a line. 12 | - CTRL + D: Duplicate line. 13 | - CTRL + X: Cut line. 14 | - Use selection with CTRL + Arrow keys to move multiple lines. 15 | 16 | **4) Block Navigation:** 17 | 18 | - CTRL + [ or ]: Jump to a block. 19 | - SHIFT + CTRL + [ or ]: Select a block. 20 | 21 | **5) Text Selection:** 22 | 23 | - CTRL + W: Expand selection. 24 | - SHIFT + CTRL + W: Shrink selection. 25 | 26 | **6) Multiple Cursors:** 27 | 28 | - SHIFT + ALT + Mouse selection. 29 | - Press CTRL twice + Arrow key. 30 | 31 | **7) Code Folding:** 32 | 33 | - CTRL + - or +: Collapse or expand a block. 34 | - SHIFT + CTRL + - or +: Collapse or expand all. 35 | 36 | **8) Tab Management:** 37 | 38 | - Alt + “x”: Close all inactive tabs. 39 | - Shift + Ctrl + V: Choose content to paste. 40 | 41 | **9) Code Formatting:** 42 | 43 | - Ctrl + Alt + L: Reformat code. 44 | - Ctrl + Alt + S: Code Style settings. 45 | 46 | **10) File Navigation:** 47 | 48 | - CTRL + F12: Navigate along file structure. 49 | 50 | **11) Selection and Navigation:** 51 | 52 | - Alt + J: Select multiple occurrences. 53 | - CTRL + G: Go to line:column. 54 | - Ctrl + HOME & Ctrl + END. 55 | 56 | **12) Project Navigation:** 57 | 58 | - Double CTRL or Double SHIFT. 59 | - Alt + 1: Files. 60 | - Alt + 4: Run. 61 | - Alt + 5: Debug. 62 | - Alt + 6: Errors. 63 | - Alt + 9: Version Control. 64 | - Alt + 0: Commits. 65 | 66 | **13) Comparing Project Files:** 67 | 68 | - Alt + 1: Select files to compare. 69 | - Press CTRL + D. 70 | 71 | **14) Version Control:** 72 | 73 | - CTRL + K: Commit changes. 74 | - SHIFT + CTRL + K: Push changes. 75 | 76 | **15) Code Inspection:** 77 | 78 | - ALT + ENTER: Quick fix for errors. 79 | - F2: Navigate to the next error. 80 | - ALT + F7: Show usages. 81 | 82 | **16) Refactoring:** 83 | 84 | - SHIFT + ALT + CTRL + T. 85 | 86 | **17) Source Code Navigation:** 87 | 88 | - Ctrl + B: Go to source code. 89 | -------------------------------------------------------------------------------- /Java/Exceptions/best practices files/ Avoid Returning null in Exception Handling.md: -------------------------------------------------------------------------------- 1 | # Why You Should Avoid Returning `null` in Exception Handling 2 | 3 | Returning `null` from methods during exception handling is an anti-pattern that can introduce ambiguity and errors into your code. Here's why it’s problematic and what to do instead. 4 | 5 | --- 6 | 7 | ## Problems with Returning `null` in Exception Handling 8 | 9 | ### Ambiguity in Results: 10 | - When a method returns `null` due to an exception, the caller cannot distinguish between a valid `null` (if applicable) and a failure caused by an exception. 11 | 12 | 13 | ```java 14 | public String getData() { 15 | try { 16 | return fetchDataFromDatabase(); 17 | } catch (SQLException e) { 18 | return null; // Ambiguous: Was this a valid result or an error? 19 | } 20 | } 21 | ``` 22 | 23 | ### Increased Risk of `NullPointerException`: 24 | - If the caller doesn’t anticipate a `null` return value and tries to use it without a null check, it can lead to a `NullPointerException`. 25 | 26 | ```java 27 | String result = getData(); 28 | System.out.println(result.length()); // Potential NPE if getData() returned null 29 | 30 | ``` 31 | 32 | ### Hides the Exception Cause: 33 | - Returning `null` discards valuable information about the exception, such as its type and cause, making debugging difficult. 34 | 35 | ```java 36 | public String getData() { 37 | try { 38 | return fetchDataFromDatabase(); 39 | } catch (SQLException e) { 40 | return null; // The SQLException is silently swallowed 41 | } 42 | } 43 | ``` 44 | 45 | ### Breaks Semantic Meaning: 46 | - Returning `null` during exception handling changes the method’s contract implicitly, making it unclear to the caller that an exception occurred. 47 | 48 | ```java 49 | 50 | ``` 51 | 52 | ## What to Do Instead 53 | 54 | ### Throw the Exception: 55 | - If the calling code can handle the exception, propagate it by throwing it again. This preserves the exception’s context. 56 | 57 | ```java 58 | public String getData() throws SQLException { 59 | return fetchDataFromDatabase(); // Let the exception propagate 60 | } 61 | ``` 62 | 63 | ### Wrap and Rethrow the Exception: 64 | - If the method needs to abstract away the underlying exception, wrap it in a custom exception that provides context while preserving the original cause. 65 | 66 | ```java 67 | public String getData() { 68 | try { 69 | return fetchDataFromDatabase(); 70 | } catch (SQLException e) { 71 | throw new DataAccessException("Error fetching data from the database", e); 72 | } 73 | } 74 | ``` 75 | 76 | ### Use `Optional`: 77 | - If returning a value is optional, use `Optional` to indicate the absence of a value explicitly. 78 | 79 | ```java 80 | public Optional getData() { 81 | try { 82 | return Optional.ofNullable(fetchDataFromDatabase()); 83 | } catch (SQLException e) { 84 | return Optional.empty(); // Explicitly indicate no value due to an exception 85 | } 86 | } 87 | ``` 88 | 89 | ### Return a Default Value: 90 | - If a default value is appropriate and makes sense for the context, return it explicitly instead of `null`. 91 | 92 | ```java 93 | public String getData() { 94 | try { 95 | return fetchDataFromDatabase(); 96 | } catch (SQLException e) { 97 | return ""; // Explicit default value 98 | } 99 | } 100 | 101 | ``` 102 | 103 | ### Log the Exception and Handle Gracefully: 104 | - Log the exception for debugging purposes and take appropriate fallback actions instead of returning `null`. 105 | 106 | ```java 107 | public String getData() { 108 | try { 109 | return fetchDataFromDatabase(); 110 | } catch (SQLException e) { 111 | log.error("Database error: " + e.getMessage(), e); 112 | return "Fallback Data"; // Provide a meaningful fallback 113 | } 114 | } 115 | ``` 116 | 117 | --- 118 | 119 | ## Key Takeaways 120 | 121 | - **Avoid returning `null`** during exception handling to prevent ambiguity, debugging challenges, and potential `NullPointerExceptions`. 122 | - **Throw or propagate exceptions** when they can be handled meaningfully by the caller. 123 | - Use `Optional`, default values, or custom exceptions to convey intent explicitly and improve code clarity. 124 | -------------------------------------------------------------------------------- /Java/Exceptions/best practices files/Be Careful What You Log.md: -------------------------------------------------------------------------------- 1 | # Why You Must Be Careful 2 | 3 | ## Security Risks: 4 | - Logs can be stored in systems with varying levels of protection, such as low-cost storage solutions, which might not have robust security measures. 5 | - If sensitive data (e.g., passwords, credit card numbers, or personal identifiers) is logged, it becomes vulnerable to unauthorized access or breaches. 6 | 7 | ## Privacy Compliance: 8 | - Many jurisdictions have strict laws (e.g., GDPR, CCPA) governing how personal data is stored, processed, and accessed. 9 | - Logging protected data, even unintentionally, could put your company out of compliance, leading to fines, lawsuits, or reputational damage. 10 | 11 | ## Risk to Your Career: 12 | - Logging sensitive data carelessly could be seen as a professional lapse, especially if it causes harm or a data breach. This could lead to serious repercussions for you as a developer. 13 | 14 | 15 | 16 | ## What Not to Log: 17 | 18 | ### Protected Data: 19 | - Passwords 20 | - API keys or authentication tokens 21 | - Personally Identifiable Information (PII) like Social Security Numbers (SSNs), names, addresses, or phone numbers 22 | - Financial information like credit card or bank account numbers 23 | 24 | ### Internal System Details: 25 | - Stack traces in production logs (can reveal internal workings of your system) 26 | - System environment variables or configurations that might include credentials 27 | 28 | 29 | 30 | 31 | ## Best Practices for Secure Logging: 32 | 33 | ### Sanitize Logged Data: 34 | - Mask sensitive data before logging it. 35 | - **Example:** Instead of logging a full credit card number, log only the last four digits. 36 | ```java 37 | log.info("Processing payment for card ending in ****5678"); 38 | ``` 39 | 40 | ### Use Logging Libraries with Filtering: 41 | - Many logging frameworks (e.g., Log4j, SLF4J) support filters to exclude sensitive data. Use these features to prevent sensitive information from being logged. 42 | 43 | ### Log at Appropriate Levels: 44 | - Avoid excessive logging, especially at the DEBUG level, in production environments. 45 | - Use `INFO`, `WARN`, or `ERROR` levels judiciously to log only what is necessary for operational monitoring and debugging. 46 | 47 | ### Encrypt Logs: 48 | - If logs must contain sensitive data for any reason (e.g., regulatory audits), ensure they are encrypted to protect against unauthorized access. -------------------------------------------------------------------------------- /Java/Exceptions/best practices files/Check for Suppressed Exceptions.md: -------------------------------------------------------------------------------- 1 | # Explanation: Check for Suppressed Exceptions 2 | 3 | Suppressed exceptions are a feature introduced in Java 7 with `try-with-resources`. They occur when an exception is thrown while a resource is being closed in a `try-with-resources` block, in addition to a primary exception already being thrown from the main body of the `try` block. 4 | 5 | Checking for suppressed exceptions ensures you don’t miss critical information about what went wrong during resource cleanup. 6 | 7 | --- 8 | 9 | ## How Suppressed Exceptions Work 10 | 11 | When using `try-with-resources`, resources (like files, streams, or connections) are automatically closed when the block exits. If the resource's `close()` method throws an exception while another exception is already being thrown from the `try` block, the closing exception is suppressed to avoid overwriting the primary exception. These suppressed exceptions are stored inside the primary exception and can be accessed using the `getSuppressed()` method. 12 | 13 | --- 14 | 15 | ## Why Check for Suppressed Exceptions? 16 | 17 | ### Detect Hidden Problems: 18 | - If you don’t check for suppressed exceptions, you might miss important errors that occurred during resource cleanup (e.g., failing to close a database connection). 19 | 20 | ### Debugging Insights: 21 | - Suppressed exceptions often reveal additional context about the issue, especially in complex scenarios involving multiple resources. 22 | 23 | ### Comprehensive Error Handling: 24 | - Ignoring suppressed exceptions may result in incomplete error handling and leave unresolved issues in your application. 25 | 26 | --- 27 | 28 | 29 | 30 | ## Example: Primary and Suppressed Exceptions 31 | 32 | ### Code Example: 33 | 34 | ```java 35 | class Door implements AutoCloseable { 36 | public void swing() throws SwingException { 37 | throw new SwingException("Door swinging failed"); 38 | } 39 | 40 | @Override 41 | public void close() throws CloseException { 42 | throw new CloseException("Door closing failed"); 43 | } 44 | } 45 | 46 | class SwingException extends Exception { 47 | public SwingException(String message) { 48 | super(message); 49 | } 50 | } 51 | 52 | class CloseException extends Exception { 53 | public CloseException(String message) { 54 | super(message); 55 | } 56 | } 57 | 58 | public class SuppressedExceptionExample { 59 | public static void main(String[] args) { 60 | try (Door door = new Door()) { 61 | door.swing(); // This throws a SwingException 62 | } catch (Exception e) { 63 | System.out.println("Primary Exception: " + e.getMessage()); 64 | for (Throwable suppressed : e.getSuppressed()) { 65 | System.out.println("Suppressed Exception: " + suppressed.getMessage()); 66 | } 67 | } 68 | } 69 | } 70 | ``` 71 | ### Output: 72 | 73 | ```plaintext 74 | Primary Exception: Door swinging failed 75 | Suppressed Exception: Door closing failed 76 | ``` 77 | 78 | 79 | ## Best Practices for Handling Suppressed Exceptions 80 | 81 | ### Always Check for Suppressed Exceptions: 82 | - When catching an exception, check if it has any suppressed exceptions using `getSuppressed()`. This ensures you don’t miss secondary errors. 83 | 84 | ### Example 85 | ```java 86 | try { 87 | // Code with resources 88 | } catch (Exception e) { 89 | System.out.println("Primary Exception: " + e); 90 | for (Throwable suppressed : e.getSuppressed()) { 91 | System.out.println("Suppressed Exception: " + suppressed); 92 | } 93 | } 94 | ``` 95 | 96 | ### Log Both Exceptions: 97 | - Log the primary and suppressed exceptions separately to retain all debugging information. 98 | 99 | ### Design Resources to Minimize Exceptions in `close()`: 100 | - Ensure that your `AutoCloseable` resources handle errors gracefully during cleanup to avoid generating suppressed exceptions unnecessarily. 101 | 102 | ### Use Suppressed Exceptions for Insights, Not Overrides: 103 | - Do not override or discard suppressed exceptions; they provide crucial context about secondary failures. 104 | 105 | --- 106 | 107 | ## Key Takeaways: 108 | 109 | - **What are suppressed exceptions?** 110 | Exceptions that occur during resource cleanup in a `try-with-resources` block but are stored in the primary exception to preserve the original context. 111 | 112 | - **Why check for them?** 113 | To avoid missing secondary errors that might reveal critical problems during cleanup. 114 | 115 | - **How to handle them?** 116 | Use `getSuppressed()` to log or analyze them alongside the primary exception. 117 | 118 | --- 119 | 120 | By consistently checking for suppressed exceptions, you ensure a thorough understanding of all errors in your application, leading to better debugging and more robust error handling. 121 | -------------------------------------------------------------------------------- /Java/Exceptions/best practices files/Custom Exceptions.md: -------------------------------------------------------------------------------- 1 | # Why Use Custom Exceptions? 2 | 3 | Custom exceptions are specific to your application and provide more meaningful error messages. They make your code clearer, easier to debug, and better aligned with your business logic. 4 | 5 | ## Key Benefits: 6 | - **Clarity:** Instead of generic exceptions, custom ones like `InvalidUserInputException` make it obvious what went wrong. 7 | - **Grouping:** Allows specific handling of related errors (e.g., `PaymentFailedException` and `OutOfStockException`). 8 | - **Context:** Add extra details like error codes or problem-specific data. 9 | - **Domain Logic:** Encapsulate business-specific problems for better abstraction. 10 | 11 | ## Example: 12 | 13 | ```java 14 | public class InvalidUserInputException extends Exception { 15 | public InvalidUserInputException(String message) { 16 | super(message); 17 | } 18 | } 19 | 20 | 21 | if (input == null) throw new InvalidUserInputException("Input cannot be null."); 22 | ``` 23 | 24 | 25 | 26 | 27 | ```java 28 | public class InvalidUserInputException extends IllegalArgumentException { 29 | public InvalidUserInputException(String message) { 30 | super(message); 31 | } 32 | } 33 | 34 | 35 | if (input == null) throw new InvalidUserInputException("Input cannot be null."); 36 | ``` 37 | -------------------------------------------------------------------------------- /Java/Exceptions/best practices files/Don’t Bury Thrown Exceptions.md: -------------------------------------------------------------------------------- 1 | # Why You Shouldn’t Bury Exceptions 2 | 3 | 4 | 5 | ## Why Burying Exceptions is Bad: 6 | 7 | ```java 8 | try { 9 | riskyOperation(); 10 | } catch (Exception e) { 11 | // Ignoring the exception 12 | } 13 | ``` 14 | 15 | - No action is taken, no logs are recorded, and the exception’s details are lost. 16 | - Debugging will be difficult if something goes wrong. 17 | 18 | 19 | 20 | ## Key Reasons: 21 | 22 | ### Lack of Visibility: 23 | - If you catch an exception and do nothing, you lose critical information about the error, such as its cause, location, and context. 24 | - This makes diagnosing and fixing the problem almost impossible. 25 | 26 | ### Debugging Becomes Harder: 27 | - Without a trace of the exception in logs or error messages, developers have no clue where or why the issue occurred, leading to wasted time and frustration. 28 | 29 | ### Unexpected Behavior: 30 | - Ignoring exceptions can leave your application in an inconsistent or unstable state because it may continue running as if nothing went wrong. 31 | 32 | ### Poor Maintenance: 33 | - Burying exceptions creates technical debt, as future maintainers of the code won't have the necessary information to understand or address problems. 34 | 35 | --- 36 | 37 | 38 | 39 | ## What to Do Instead: 40 | 41 | ### Log the Exception: 42 | - If the exception doesn't need immediate handling, at least log its details (e.g., type, message, stack trace) so developers can investigate later. 43 | 44 | ```java 45 | try { 46 | riskyOperation(); 47 | } catch (Exception e) { 48 | log.error("Exception occurred: " + e.getMessage(), e); 49 | } 50 | ``` 51 | 52 | ### Handle the Exception Appropriately: 53 | - If the exception can be resolved, handle it in the `catch` block. 54 | 55 | ```java 56 | try { 57 | connection.open(); 58 | } catch (IOException e) { 59 | System.err.println("Failed to open connection: " + e.getMessage()); 60 | retryConnection(); 61 | } 62 | 63 | ``` 64 | 65 | ### Rethrow the Exception: 66 | - If the current method can’t handle the exception, rethrow it to let higher levels deal with it. 67 | 68 | ```java 69 | try { 70 | parseFile(filePath); 71 | } catch (ParseException e) { 72 | throw new RuntimeException("Error parsing file: " + filePath, e); 73 | } 74 | 75 | ``` 76 | 77 | ### Use Exception Wrapping: 78 | - Wrap the exception with additional context if needed, while preserving the original exception. 79 | 80 | ```java 81 | try { 82 | executeTask(); 83 | } catch (SQLException e) { 84 | throw new DataAccessException("Error executing database task", e); 85 | } 86 | ``` 87 | 88 | 89 | --- 90 | 91 | ## Takeaway: 92 | 93 | Never bury exceptions. Always take one of these actions: 94 | - Log it to retain error details. 95 | - Handle it to recover from the issue. 96 | - Rethrow it if it’s not your method’s responsibility to fix it. 97 | 98 | This ensures visibility, simplifies debugging, and maintains the stability of your application. 99 | -------------------------------------------------------------------------------- /Java/Exceptions/best practices files/Don’t Close Resources Manually.md: -------------------------------------------------------------------------------- 1 | # Explanation: Don’t Close Resources Manually 2 | 3 | Manually closing resources like files, database connections, or sockets can lead to resource leaks if not done correctly, especially when exceptions occur. Using `try-with-resources` is a better, safer, and cleaner way to manage resources in Java. 4 | 5 | --- 6 | 7 | ## Why Avoid Manual Resource Management? 8 | 9 | ### Error-Prone: 10 | - Forgetting to close resources manually is a common mistake, leading to resource leaks, which can degrade application performance or even crash the system. 11 | - If an exception occurs before the resource is closed, the code may not reach the `close()` call. 12 | 13 | ### Messy Code: 14 | - Manual closing requires extra boilerplate code, making your code less readable and harder to maintain. 15 | 16 | ### Difficult Debugging: 17 | - Leaking resources (e.g., file handles, database connections) often results in subtle bugs that are hard to trace and debug. 18 | 19 | ### Automatic Management: 20 | - With `try-with-resources`, the JVM ensures that the `close()` method of any `AutoCloseable` resource (e.g., files, streams, connections) is automatically called, even if an exception is thrown within the block. 21 | 22 | --- 23 | 24 | ## How Try-With-Resources Works 25 | 26 | The `try-with-resources` statement automatically closes any resource that implements the `AutoCloseable` interface when the block completes execution, either normally or via an exception. 27 | 28 | --- 29 | 30 | ## Advantages of Try-With-Resources: 31 | 32 | - **Automatic Resource Management:** 33 | Ensures resources are closed properly without manual intervention. 34 | 35 | - **Exception Safety:** 36 | Resources are guaranteed to be closed even if an exception occurs within the `try` block. 37 | 38 | - **Reduces Boilerplate Code:** 39 | Eliminates the need for redundant `finally` blocks, keeping the code clean. 40 | 41 | - **Fewer Bugs:** 42 | Prevents resource leaks caused by forgetting to close resources. 43 | 44 | --- 45 | 46 | ## Applicability: 47 | 48 | `Try-with-resources` works with any resource that implements the `AutoCloseable` interface, such as: 49 | - Input/output streams (`FileReader`, `BufferedReader`) 50 | - Database connections (`Connection`, `Statement`, `ResultSet`) 51 | - Custom resources (like the `Door` example) that implement `AutoCloseable`. 52 | -------------------------------------------------------------------------------- /Java/Exceptions/best practices files/Don’t Log and Rethrow.md: -------------------------------------------------------------------------------- 1 | # Why Avoid Logging and Rethrowing? 2 | 3 | ## Key Issues: 4 | 5 | ### Duplicate Log Entries: 6 | - When you log an exception and then rethrow it, the same exception will likely be logged multiple times—once where it was caught and again when it's handled at a higher level. 7 | - This clutters log files and makes it harder to determine where the error was first encountered. 8 | 9 | ### Code Duplication: 10 | - Logging and rethrowing the same exception often duplicates the information and bloats your code unnecessarily. 11 | 12 | ### Confusing Stack Traces: 13 | - When the same exception is logged multiple times, it can create confusion about where the error occurred and how it propagated through the application. 14 | 15 | ### Separation of Concerns: 16 | - Low-level code (where the exception is caught) may not have the full context to decide how an exception should be logged or handled. It’s better to let the higher-level method handle it. 17 | 18 | 19 | ## What to Do Instead 20 | 21 | ### Option 1: Log and Continue 22 | - If you handle the exception locally and do not need to propagate it further, log the exception and continue with your application logic. 23 | 24 | ```java 25 | try { 26 | Class.forName("com.mcnz.Example"); 27 | } catch (ClassNotFoundException ex) { 28 | log.warning("Class was not found: " + ex.getMessage()); 29 | // Take corrective action or continue 30 | } 31 | ``` 32 | 33 | ### Option 2: Rethrow Without Logging 34 | - If the current method cannot handle the exception properly, rethrow it and let a higher-level method handle logging and recovery. 35 | 36 | ```java 37 | try { 38 | Class.forName("com.mcnz.Example"); 39 | } catch (ClassNotFoundException ex) { 40 | throw ex; // Let the calling method decide how to log or handle 41 | } 42 | ``` 43 | 44 | ### Option 3: Wrap and Rethrow (With Context) 45 | - If you need to add additional context to the exception, wrap it in a custom or higher-level exception and rethrow it. The higher-level exception can then be logged at a later point. 46 | 47 | ```java 48 | try { 49 | Class.forName("com.mcnz.Example"); 50 | } catch (ClassNotFoundException ex) { 51 | throw new MyCustomException("Failed to load required class", ex); 52 | } 53 | ``` 54 | 55 | 56 | ## When to Log and When to Rethrow 57 | 58 | ### Log Locally: 59 | - If you can handle the exception completely (e.g., logging an error and taking corrective action), log it locally and do not rethrow. 60 | 61 | ### Rethrow Without Logging: 62 | - If you cannot handle the exception, rethrow it and let the caller (or a centralized handler) log it. 63 | 64 | ### Centralized Logging: 65 | - For large applications, use a centralized exception handler (e.g., a global exception handler in a web app) to log exceptions consistently and avoid duplication. 66 | 67 | --- 68 | 69 | ## Key Takeaways: 70 | - **Choose one:** Either log the exception or rethrow it, but not both. 71 | - **Avoid clutter:** Prevent duplicate log entries to keep logs clean and meaningful. 72 | - **Separate concerns:** Let higher-level methods decide how and where to log exceptions when rethrowing them. 73 | 74 | --- 75 | 76 | By following this guideline, you ensure that logs remain concise, readable, and useful for troubleshooting. -------------------------------------------------------------------------------- /Java/Exceptions/best practices files/Exception Chaining.md: -------------------------------------------------------------------------------- 1 | # Why Use Exception Chaining? 2 | 3 | Exception chaining is an essential technique in Java because it helps retain the full context of an error while adding more meaningful information. Here are the key reasons why you should use it: 4 | 5 | ## 1. Preserve the Original Cause 6 | 7 | When an exception is thrown, the stack trace provides critical information about where and why the error occurred. 8 | If you replace the original exception without chaining it, this information is lost. 9 | 10 | **Why it matters:** 11 | Losing the original exception makes debugging much harder. Exception chaining allows the original exception to be preserved as the "cause," so both the higher-level and lower-level issues are visible. 12 | 13 | ## 2. Add More Context 14 | 15 | Often, the original exception doesn't provide enough information for someone reading the error to understand what went wrong in the specific context of your application. 16 | By wrapping the original exception, you can add custom messages or context that makes the error easier to diagnose. 17 | 18 | **Why it matters:** 19 | The developer troubleshooting the issue gets a clearer picture of what happened at both the low level (original exception) and the higher level (your additional context). 20 | 21 | ## 3. Maintain Abstraction Layers 22 | 23 | In well-designed software, exceptions should be translated when they cross abstraction boundaries. For example: 24 | - A low-level data access layer might throw an `SQLException`. 25 | - When this exception reaches the business logic layer, you might want to wrap it in a higher-level `DataAccessException` to reflect its meaning in that context. 26 | 27 | **Why it matters:** 28 | This ensures that: 29 | - The details of the lower layer remain encapsulated. 30 | - The higher layer provides meaningful exceptions relevant to its domain. 31 | 32 | ## 4. Improve Debugging Efficiency 33 | 34 | Exception chaining gives a full "trail" of what went wrong, from the low-level technical cause to the higher-level business impact. 35 | This trail reduces the time and effort needed to identify the root cause of an issue. 36 | 37 | **Why it matters:** 38 | Without exception chaining, developers may spend unnecessary time tracing the origin of an error. 39 | 40 | ## 5. Avoid Information Loss 41 | 42 | Wrapping an exception without chaining (or catching it and doing nothing) leads to information loss. This can obscure the real issue or make debugging significantly harder. 43 | Chaining ensures that no details are discarded. 44 | 45 | **Why it matters:** 46 | Preserving the original exception ensures that even "impossible" errors are traceable and fixable. 47 | 48 | ## How Exception Chaining Works 49 | 50 | When wrapping an exception, use the constructor of the new exception to include the original exception as its cause. 51 | 52 | **Example:** 53 | 54 | ```java 55 | try { 56 | // Low-level operation that throws SQLException 57 | throw new SQLException("Database connection error"); 58 | } catch (SQLException e) { 59 | // Wrap the original exception in a higher-level exception 60 | throw new DataAccessException("Failed to access data", e); 61 | } 62 | ``` 63 | 64 | Here: 65 | - The `SQLException` is the original, low-level exception. 66 | - The `DataAccessException` is the higher-level exception that adds context but retains the original error as its cause. 67 | 68 | When debugging, both exceptions and their stack traces will be available. 69 | 70 | ## How It Looks in Practice 71 | 72 | When exception chaining is used, the stack trace will show the sequence of exceptions, like this: 73 | 74 | ```JAVA 75 | DataAccessException: Failed to access data 76 | at com.example.DataAccessLayer.method(DataAccessLayer.java:25) 77 | Caused by: SQLException: Database connection error 78 | at com.example.DatabaseConnection.connect(DatabaseConnection.java:12) 79 | ``` 80 | 81 | **Key Benefits:** 82 | - Top-level message (`DataAccessException`): Explains the higher-level issue. 83 | - Cause (`SQLException`): Explains the lower-level technical error. 84 | 85 | ## Summary 86 | 87 | Exception chaining is valuable because it: 88 | - Preserves the original exception and its details. 89 | - Adds meaningful context for better debugging and understanding. 90 | - Maintains clear separation and encapsulation of responsibilities across abstraction layers. 91 | - Prevents information loss, ensuring that the root cause of an error is always traceable. 92 | 93 | By chaining exceptions, you create more informative and maintainable error-handling systems, saving time and effort during troubleshooting. 94 | 95 | 96 | ## Always correctly wrap the exceptions in custom exceptions so that the stack trace is not lost 97 | 98 | ```java 99 | catch (NoSuchMethodException e) { 100 | throw new MyServiceException("Some information: " + e.getMessage()); //Incorrect way 101 | } 102 | ``` 103 | 104 | This destroys the stack trace of the original exception and is always wrong. The correct way of doing this is: 105 | 106 | ```java 107 | catch (NoSuchMethodException e) { 108 | throw new MyServiceException("Some information: " , e); //Correct way 109 | } 110 | ``` 111 | 112 | ## Always include all information about an exception in the single log message 113 | 114 | ```java 115 | LOGGER.debug("Using cache sector A"); 116 | LOGGER.debug("Using retry sector B"); 117 | ``` 118 | Don’t do this. 119 | 120 | Using a multi-line log message with multiple calls to LOGGER.debug() may look fine in your test case, but when it shows up in the log file of an app server with 400 threads running in parallel, all dumping information to the same log file, your two log messages may end up spaced out 1000 lines apart in the log file, even though they occur on subsequent lines in your code. 121 | 122 | Do it like this: 123 | 124 | ```java 125 | LOGGER.debug("Using cache sector A, using retry sector B"); 126 | ``` 127 | 128 | ## Always terminate the thread which it is interrupted 129 | 130 | ```java 131 | while (true) { 132 | try { 133 | Thread.sleep(100000); 134 | } catch (InterruptedException e) {} //Don't do this 135 | doSomethingCool(); 136 | } 137 | ``` 138 | 139 | InterruptedException is a clue to your code that it should stop whatever it’s doing. Some common use cases for a thread getting interrupted are the active transaction timing out, or a thread pool getting shut down. 140 | 141 | Instead of ignoring the InterruptedException, your code should do its best to finish up what it’s doing and finish the current thread of execution. 142 | 143 | So to correct the example above: 144 | 145 | ```java 146 | while (true) { 147 | try { 148 | Thread.sleep(100000); 149 | } catch (InterruptedException e) { 150 | break; 151 | } 152 | } 153 | doSomethingCool(); 154 | ``` -------------------------------------------------------------------------------- /Java/Exceptions/best practices files/Keep Exception Handling Separate.md: -------------------------------------------------------------------------------- 1 | # Why Keep Exception Handling Separate? 2 | 3 | ## Key Benefits: 4 | 5 | - **Improves Code Readability:** 6 | - Mixing exception handling with the main logic clutters the code and makes it harder to follow. 7 | - Keeping the main logic focused on its task ensures your code remains clear and concise. 8 | 9 | - **Easier Maintenance:** 10 | - If exception handling is isolated, you can modify or improve error handling without affecting the main logic. 11 | - Debugging becomes simpler since error-handling code is in predictable locations. 12 | 13 | - **Encourages Reusability:** 14 | - By centralizing exception handling, you can avoid duplicating the same error-handling code in multiple places. 15 | - Common exception handling strategies (e.g., logging) can be implemented once and reused. 16 | 17 | --- 18 | 19 | ## How to Achieve This? 20 | 21 | 1. **Use try-catch Blocks Wisely:** 22 | Place try-catch blocks around specific operations prone to exceptions, not around entire methods or unrelated logic. 23 | 24 | ### Example (bad) 25 | ```java 26 | try { 27 | // Main logic 28 | readFile(); 29 | processFileData(); 30 | saveResults(); 31 | } catch (IOException e) { 32 | // Handles all exceptions 33 | e.printStackTrace(); 34 | } 35 | ``` 36 | ### Example (better) 37 | ```java 38 | try { 39 | readFile(); 40 | } catch (IOException e) { 41 | handleIOException(e); 42 | } 43 | 44 | processFileData(); 45 | saveResults(); 46 | ``` 47 | 48 | 2. **Use Helper Methods for Exception Handling:** 49 | Encapsulate error-handling logic in separate methods. 50 | ```java 51 | public void handleIOException(IOException e) { 52 | // Centralized logic: log the error or take appropriate action 53 | System.err.println("Error reading file: " + e.getMessage()); 54 | } 55 | ``` 56 | 57 | 3. **Centralized Exception Handling (if applicable):** 58 | For larger applications, use a global or centralized error-handling mechanism (e.g., in a web app, an error handler at the controller or middleware level). 59 | 60 | --- 61 | 62 | ## Benefits of Separating Exception Handling: 63 | 64 | - **Clarity:** Main logic focuses on the task; error handling is distinct. 65 | - **Flexibility:** Easily adapt to new error-handling requirements. 66 | - **Modularity:** Makes debugging and updating specific parts of the code easier. 67 | 68 | --- 69 | 70 | By keeping exception handling separate, you ensure your application is both easier to understand and maintain over time. -------------------------------------------------------------------------------- /Java/Exceptions/best practices files/Throw Early and Handle Exceptions Late.md: -------------------------------------------------------------------------------- 1 | # Why Throw Exceptions Early? 2 | 3 | ## Immediate Response to Problems: 4 | - If an error condition is detected, delaying the exception allows your program to execute additional code unnecessarily, potentially leading to incorrect or undefined behavior. 5 | - Throwing an exception immediately stops further processing, ensuring that invalid states or actions are avoided. 6 | 7 | ## Easier Debugging: 8 | - The exception stack trace points directly to where the error occurred. 9 | - Delaying the exception might make it harder to pinpoint the root cause. 10 | 11 | ## Clean Separation of Concerns: 12 | - Throwing an exception at the point of failure allows other parts of your application to decide how to handle it, rather than trying to recover in the same place. 13 | 14 | --- 15 | 16 | # Why Handle Exceptions Late? 17 | 18 | ## Centralized Exception Handling: 19 | - Catching exceptions at a higher level reduces the number of `try-catch` blocks scattered throughout your code, improving readability and maintainability. 20 | - A centralized approach allows consistent handling, like logging or error reporting. 21 | 22 | ## Preserve the Stack Trace: 23 | - Allowing an exception to propagate upward preserves its context, making debugging easier. 24 | - Catching too early can obscure where the problem originated. 25 | 26 | ## Avoid Premature Handling: 27 | - Sometimes a low-level method may not know how to handle an exception properly. Letting it propagate ensures it is handled by the layer with enough context to decide what to do. 28 | 29 | --- 30 | 31 | # Key Points: 32 | 33 | - **Throw Early:** 34 | Detect problems immediately and throw exceptions to prevent invalid operations or undefined behavior. 35 | **Example:** Validating method inputs at the start. 36 | 37 | - **Handle Late:** 38 | Catch exceptions at higher levels where you can decide the appropriate recovery actions. 39 | Centralized handling reduces redundancy and improves code maintainability. 40 | 41 | --- 42 | 43 | # Advantages: 44 | 45 | ## Improved Readability: 46 | - Clear separation between error detection (throwing) and error handling (catching). 47 | 48 | ## Simplified Maintenance: 49 | - Fewer scattered catch blocks mean easier code maintenance and consistency. 50 | 51 | ## Better Debugging: 52 | - Preserved stack traces and centralized handling make root causes easier to trace. 53 | 54 | --- 55 | 56 | By adhering to this principle, you create more robust, maintainable, and readable code. -------------------------------------------------------------------------------- /Java/Exceptions/best practices files/Using return in a finally Block Is an Anti-Pattern.md: -------------------------------------------------------------------------------- 1 | # Why Using `return` in a `finally` Block Is an Anti-Pattern 2 | 3 | Using a `return` statement in a `finally` block must be avoided because it discards exceptions that occur in the `try` block, leading to silent failures and potentially severe issues in your application. This happens due to how Java's exception handling mechanism works when a `finally` block modifies the control flow. 4 | 5 | --- 6 | 7 | ## How It Works (and Why It’s Problematic): 8 | 9 | The `finally` block is always executed after the `try` or `catch` block, whether or not an exception occurs. If a `return` statement is included in the `finally` block, the following happens: 10 | 1. When an exception is thrown in the `try` block, it would normally propagate upward in the stack. 11 | 2. However, if the `finally` block has a `return` statement, it overrides the exception propagation, and the exception is discarded. 12 | 3. The method exits with the value returned from the `finally` block, effectively "swallowing" the exception. 13 | 14 | 15 | ## Code Example: 16 | ```java 17 | public int getPlayerScore(String playerFile) { 18 | int score = 0; 19 | try { 20 | throw new IOException("Error reading player file"); 21 | } finally { 22 | return score; // The IOException is silently discarded 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | System.out.println(new Example().getPlayerScore("player.txt")); 28 | } 29 | ``` 30 | 31 | ## Output: 32 | ```plaintext 33 | 0 34 | ``` 35 | 36 | ## Why This Is Dangerous: 37 | 38 | ### Exceptions Are Silently Swallowed: 39 | - Critical errors that should be addressed are lost. Developers may never realize an issue occurred because the exception is completely suppressed. 40 | 41 | ### Unexpected Behavior: 42 | - The method seems to complete successfully even when an error occurred. This can lead to inconsistent application states. 43 | 44 | ### Debugging Becomes Difficult: 45 | - When exceptions are dropped, developers lose visibility into the root cause of the problem, making debugging significantly harder. 46 | 47 | ### Violates Principle of Least Surprise: 48 | - Other developers working on the code might expect exceptions to propagate correctly, but a `finally` block with `return` introduces unexpected behavior. 49 | 50 | --- 51 | 52 | ## What the Java Language Specification Says: 53 | 54 | The behavior is defined in the Java Language Specification (JLS): 55 | - If the `finally` block executes normally (without abrupt control flow like `return`, `break`, or another exception), the exception from the `try` block is propagated. 56 | - If the `finally` block completes abruptly (e.g., via `return`, `break`, or another exception), the exception from the `try` block is discarded, and the control flow follows the `finally` block's instruction. 57 | 58 | --- 59 | 60 | ## Best Practices: 61 | 62 | ### Never Use `return` in a `finally` Block: 63 | - Avoid writing `return`, `break`, or throwing new exceptions in the `finally` block unless you fully understand the implications. 64 | 65 | ### Let Exceptions Propagate: 66 | - Let the `finally` block execute and allow any exceptions from the `try` block to propagate to the caller. 67 | 68 | ### Use `finally` Only for Cleanup: 69 | - Restrict the `finally` block to tasks like releasing resources (e.g., closing files or database connections). Avoid modifying control flow. 70 | 71 | --- 72 | 73 | ## Key Takeaways: 74 | 75 | - **Why it’s an anti-pattern:** 76 | `return` in a `finally` block suppresses exceptions, leading to silent failures, unexpected behavior, and harder debugging. 77 | 78 | - **How to avoid it:** 79 | Use the `finally` block only for cleanup tasks and let exceptions propagate naturally. 80 | 81 | - **What to remember:** 82 | Exceptions provide critical information for diagnosing issues. Suppressing them unintentionally through poor practices can lead to serious bugs. 83 | -------------------------------------------------------------------------------- /Java/Exceptions/best practices.md: -------------------------------------------------------------------------------- 1 | # General tips : 2 | 3 | ## Explicitly define exceptions in the throws clause 4 | 5 | Lazy developers use the generic Exception class in the throws clause of a method. Doing so is not a Java exception handling best practice. 6 | 7 | Instead, always explicitly state the exact set of exception a given method might throw. This allows other developers to know the various error handling routines they can employ if a given method fails to execute properly. 8 | 9 | 10 | ## Catch the most specific exception first 11 | 12 | This is more of a compiler requirement than a Java exception handling best practice, but a developer should always catch the most specific exception first, and the least specific one last. 13 | 14 | If this rule is not followed, the JVM will generate a compile time error with a fairly cryptic error message that is difficult to understand. 15 | 16 | Make your software development life easier, and always catch the most specific exception in your code first. 17 | 18 | 19 | ## Use modern exception handling techniques 20 | 21 | Is Java verbose? It is if you stick with the 20-year-old exception handling techniques. 22 | 23 | Java has added many features around error and exception handling that simplify development and greatly reduce the verbosity of Java code. 24 | 25 | Take advantage of the ability to catch multiple exceptions in a single catch block, automatically close resource with the try-with-resources block, and use RuntimeExceptions so other developers aren’t forced to handle the exceptions you throw. 26 | 27 | 28 | ## Never catch Throwable 29 | 30 | Well, it is one step more serious trouble. Because java errors are also subclasses of the Throwable. 31 | 32 | Errors are irreversible conditions that can not be handled by JVM itself. And for some JVM implementations, JVM might not actually even invoke your catch clause on an Error. -------------------------------------------------------------------------------- /Java/Generics/Chapters/Lower Bounded Wildcards.md: -------------------------------------------------------------------------------- 1 | ## Lower Bounded Wildcards 2 | 3 | The purpose of lower bounded wildcards is to restrict the unknown type to be a specific type or a supertype of that type. It is used by declaring wildcard character ("?") followed by the super keyword, followed by its lower bound. 4 | 5 | Syntax : 6 | ```Java 7 | List 8 | ``` 9 | 10 | which 11 | ? is a ***wildcard character***. 12 | super, is a ***keyword***. 13 | Integer, is a wrapper ***class***. 14 | 15 | Suppose, we want to write the method for the list of Integer and its supertype (like Number, Object). Using List is suitable for a list of type Integer or any of its superclasses whereas List works with the list of type Integer only. So, List is less restrictive than List. 16 | 17 | #### Example : 18 | 19 | ```Java 20 | import java.util.Arrays; 21 | import java.util.List; 22 | 23 | public class LowerBoundWildcard { 24 | 25 | public static void addNumbers(List list) { 26 | for(Object n:list){ 27 | System.out.println(n); 28 | } 29 | } 30 | 31 | public static void main(String[] args) { 32 | 33 | List l1=Arrays.asList(1,2,3); 34 | System.out.println("displaying the Integer values"); 35 | addNumbers(l1); 36 | 37 | List l2=Arrays.asList(1.0,2.0,3.0); 38 | System.out.println("displaying the Number values"); 39 | addNumbers(l2); 40 | } 41 | } 42 | ``` -------------------------------------------------------------------------------- /Java/Generics/Chapters/Unbounded Wildcards.md: -------------------------------------------------------------------------------- 1 | ## Unbounded Wildcards 2 | 3 | The unbounded wildcard type represents the list of an unknown type such as List. This approach can be useful in the following scenarios: - 4 | 5 | 1. When the given method is implemented by using the functionality provided in the Object class. 6 | 2. When the generic class contains the methods that don't depend on the type parameter. 7 | 8 | #### Example : 9 | ```Java 10 | import java.util.Arrays; 11 | import java.util.List; 12 | 13 | public class UnboundedWildcard { 14 | 15 | public static void display(List list){ 16 | for(Object o:list){ 17 | System.out.println(o); 18 | } 19 | } 20 | 21 | 22 | public static void main(String[] args) { 23 | List l1 = Arrays.asList(1,2,3); 24 | System.out.println("displaying the Integer values"); 25 | display(l1); 26 | 27 | List l2 = Arrays.asList("One","Two","Three"); 28 | System.out.println("displaying the String values"); 29 | display(l2); 30 | } 31 | } 32 | ``` 33 | -------------------------------------------------------------------------------- /Java/Generics/Chapters/Upper Bounded Wildcards.md: -------------------------------------------------------------------------------- 1 | ##Upper Bounded Wildcards 2 | 3 | The purpose of upper bounded wildcards is to decrease the restrictions on a variable. It restricts the unknown type to be a specific type or a subtype of that type. It is used by declaring wildcard character ("?") followed by the extends (in case of, class) or implements (in case of, interface) keyword, followed by its upper bound. 4 | 5 | Syntax : 6 | ```Java 7 | List 8 | ``` 9 | Which 10 | ? is a ***wildcard character***. 11 | extends, is a ***keyword***. 12 | Number, is a ***class*** present in java.lang package 13 | 14 | Suppose, we want to write the method for the list of Number and its subtypes (like Integer, Double). Using List is suitable for a list of type Number or any of its subclasses whereas List works with the list of type Number only. So, List is less restrictive than List. 15 | 16 | #### Example : 17 | 18 | ```Java 19 | import java.util.ArrayList; 20 | 21 | public class UpperBoundWildcard { 22 | 23 | 24 | private static Double add(ArrayList num) { 25 | 26 | double sum=0.0; 27 | 28 | for(Number n:num){ 29 | sum = sum+n.doubleValue(); 30 | } 31 | 32 | return sum; 33 | } 34 | 35 | public static void main(String[] args) { 36 | 37 | ArrayList l1=new ArrayList<>(); 38 | l1.add(10); 39 | l1.add(20); 40 | System.out.println("displaying the sum= "+add(l1)); 41 | 42 | ArrayList l2=new ArrayList<>(); 43 | l2.add(30.0); 44 | l2.add(40.0); 45 | System.out.println("displaying the sum= "+add(l2)); 46 | 47 | } 48 | } 49 | ``` -------------------------------------------------------------------------------- /Java/Generics/Generics.md: -------------------------------------------------------------------------------- 1 | ### Advantage of Java Generics 2 | 3 | 1. Type safety 4 | 2. Avoid type csting 5 | (It offen happens in the Lists.) 6 | 3. Compile-Time checking 7 | 8 | ### Advanced details 9 | 10 | 1. Java Generics using Map 11 | 12 | Short note : 13 | ```java 14 | Map map=new HashMap(); 15 | ``` 16 | Long note : 17 | 18 | ```java 19 | import java.util.*; 20 | class TestGenerics{ 21 | public static void main(String args[]){ 22 | Map map=new HashMap(); 23 | map.put(1,"vijay"); 24 | map.put(4,"umesh"); 25 | map.put(2,"ankit"); 26 | 27 | //Now use Map.Entry for Set and Iterator 28 | Set> set=map.entrySet(); 29 | 30 | Iterator> itr=set.iterator(); 31 | while(itr.hasNext()){ 32 | Map.Entry e=itr.next();//no need to typecast 33 | System.out.println(e.getKey()+" "+e.getValue()); 34 | } 35 | } 36 | } 37 | 38 | ``` 39 | 40 | --- 41 | 2. Generic class 42 | we can use generic types in our classes. 43 | The T type indicates that it can refer to any type (like String, Integer, and Employee). The type you specify for the class will be used to store and retrieve the data. 44 | ```java 45 | class MyGenContainer{ 46 | T obj; 47 | 48 | void add(T obj){ 49 | this.obj=obj; 50 | } 51 | 52 | T get(){ 53 | return obj; 54 | } 55 | } 56 | ``` 57 | 58 | Note : 59 | The type parameters naming conventions are important to learn generics thoroughly. The common type parameters are as follows: 60 | 61 | T - Type 62 | E - Element 63 | K - Key 64 | N - Number 65 | V - Value 66 | 67 | --- 68 | 69 | 3. Generic Method 70 | Like the generic class, we can create a generic method that can accept any type of arguments. Here, the scope of arguments is limited to the method where it is declared. It allows static as well as non-static methods. 71 | 72 | ```Java 73 | public class GenericsMethods { 74 | 75 | //Java Generic Method 76 | public static boolean isEqual(GenericsType g1, GenericsType g2){ 77 | return g1.get().equals(g2.get()); 78 | } 79 | 80 | public static void main(String args[]){ 81 | GenericsType g1 = new GenericsType<>(); 82 | g1.set("Pankaj"); 83 | 84 | GenericsType g2 = new GenericsType<>(); 85 | g2.set("Pankaj"); 86 | 87 | boolean isEqual = GenericsMethods.isEqual(g1, g2); 88 | //above statement can be written simply as 89 | isEqual = GenericsMethods.isEqual(g1, g2); 90 | //This feature, known as type inference, allows you to invoke a generic method as an ordinary method, without specifying a type between angle brackets. 91 | //Compiler will infer the type that is needed 92 | } 93 | } 94 | ``` 95 | 96 | --- 97 | 98 | ### Wildcard in Java Generics 99 | we use Wildcards to put a restriction on our generics to control it and prevent unwanted business. 100 | we do it by using wildcard element. 101 | The ? (question mark) symbol represents the wildcard element. It means any type. If we write , it means any child class of Number, e.g., Integer, Float, and double. Now we can call the method of Number class through any child class object. 102 | 103 | We can use a wildcard as a type of a parameter, field, return type, or local variable. However, ***it is not allowed to use a wildcard as a type argument for a generic method invocation, a generic class instance creation, or a supertype.*** 104 | 105 | we have 3 types of wildcard usage in Java Generics : 106 | 1. [Unbounded Wildcards](/Java/Generics/Chapters/Unbounded%20Wildcards.md) (no inheritance) 107 | 2. [Upper Bounded Wildcards](/Java/Generics/Chapters/Upper%20Bounded%20Wildcards.md) (using child classes by using **extends**) 108 | 3. [Lower Bounded Wildcards](/Java/Generics/Chapters/Lower%20Bounded%20Wildcards.md) ((using parent classes by using ***super***)) -------------------------------------------------------------------------------- /Java/Hibernate/Hibernate.md: -------------------------------------------------------------------------------- 1 | ### steps to use Hibernate : 2 | 1. create **org.hibernate.cfg.configuration** object 3 | 2. load the Meta information 4 | 3. create **org.hibernate.SessionFactory** object 5 | 4. make hibernate API call on session object 6 | 5. close the session 7 | 6. close the sessionFactory object 8 | 9 | ### Hibernate Architecture : 10 |
11 | 12 | ![Hibernate Architecture](./assets/01%20-%20Hibernate%20Architecture.png) 13 |
14 | 15 | each session Object has three lifecycle. 16 | [Here read more.](./chapters/Hibernate%20Lifecycle.md) 17 | 18 | 19 | ### Hibernate cores : 20 | 1. Configuration (org.configuration.cfg) : it gives two services in hibernate 21 | + Loads mapping file and configuration file into memory and makes them available to hibernate engine 22 | + Acts as factory to create the SessionFactory 23 | 24 |
25 | 26 | 2. SessionFactory (org.hibrnate.SessionFactory) 27 | - Hibernate (engine) implements SessionFactory interface 28 | + SessionFactory is one per DBMS (mostly one per application) 29 | + SessionFactory is Thread safe 30 | + SessionFactory is not a Singleton 31 | + It creates Session object, SessionFactory encapsulates, second level cache, connection pool, meta information cache, and pool of session 32 | 33 |
34 | 35 | 3. Session (org.hibernate.Session) 36 | + Hibernate engine implements Session interface 37 | + Session object acts as persistent manager 38 | + Session object is a light weight object 39 | + It encapsulates connection and first-level cache 40 | + Session object is not thread-safe 41 | + In every DAO method, Session object is created 42 | + It is used for CRDD operation 43 | 44 |
45 | 46 | 4. Transaction (org.hibernate.Transaction) 47 | + Hibernate engine implements this interface 48 | + When database connection is created by hibernate, connection associated with session is in autocommit disable mode. 49 | + Whenever any CRUD operation is performed, the changes will not be reflected in the database unless connection is maintained in auto-commit enabled mode. 50 | 51 |
52 | 53 | 5. ldentifier Generator 54 | + [read more here](chapters/ldentifierGenerator.md) -------------------------------------------------------------------------------- /Java/Hibernate/HibernateDemo/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.github.javabaz 8 | HibernateDemo 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 17 13 | 17 14 | UTF-8 15 | 16 | 17 | -------------------------------------------------------------------------------- /Java/Hibernate/HibernateDemo/src/main/java/com/github/javabaz/Main.java: -------------------------------------------------------------------------------- 1 | package com.github.javabaz; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | System.out.println("Hello world!"); 6 | } 7 | } -------------------------------------------------------------------------------- /Java/Hibernate/assets/01 - Hibernate Architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaBaz/presentations/1c97989f746238dfa6b7a1d7f43e51ebbd205ad3/Java/Hibernate/assets/01 - Hibernate Architecture.png -------------------------------------------------------------------------------- /Java/Hibernate/chapters/Hibernate Lifecycle.md: -------------------------------------------------------------------------------- 1 | # Hibernate Lifecycle 2 | 3 | Session Object has three lifecycle : 4 | 1.[Transient](#transient-state) 5 | 2.[Persistent](#persistent-state) 6 | 3.[Detached](#detached-state) 7 | 8 | 9 | 10 | ### Transient State: 11 | + The transient state is the initial state of an object. 12 | 13 | + Once we create an instance of POJO class, then the object entered in the transient state. 14 | 15 | + Here, an object is not associated with the Session. So, the transient state is not related to any database. 16 | 17 | + Hence, modifications in the data don't affect any changes in the database. 18 | 19 | + The transient objects exist in the heap memory. They are independent of Hibernate. 20 | 21 | ### Persistent State: 22 | + As soon as the object associated with the Session, it entered in the persistent state. 23 | 24 | + Hence, we can say that an object is in the persistence state when we save or persist it. 25 | 26 | + Here, each object represents the row of the database table. 27 | 28 | + So, modifications in the data make changes in the database. 29 | 30 | 31 | ### Detached State: 32 | + Once we either close the session or clear its cache, then the object entered into the detached state. 33 | 34 | + As an object is no more associated with the Session, modifications in the data don't affect any changes in the database. 35 | 36 | + However, the detached object still has a representation in the database. 37 | 38 | + If we want to persist the changes made to a detached object, it is required to reattach the application to a valid Hibernate session. 39 | 40 | + To associate the detached object with the new hibernate session, use any of these methods - load(), merge(), refresh(), update() or save() on a new session with the reference of the detached object. -------------------------------------------------------------------------------- /Java/Hibernate/chapters/ldentifierGenerator.md: -------------------------------------------------------------------------------- 1 | ## ldentifier Generator 2 | 3 | All the generator classes implement the org.hibernate.id.ldentifierGenerator interface. 4 | 5 | The application programmer may create one's own generator classes by implementing the IdentifierGenerator interface. 6 | 7 | 8 | 9 | Hibernate framework provides many built-in generator classes : 10 | 11 | 1. **assigned**: Default, value has to be explicitly assigned to persistent object before persisting it. generator class = assigned 12 | 13 |
14 | 15 | 2. **increment**: It increments value by 1. It generates short, int, or long type identifier. 16 | 17 |
18 | 19 | 3. **native**: It uses identity, sequence, or hilo, depending on the database vendor. 20 | 21 |
22 | 23 | 4. **sequence**: It uses the sequence of the database. If there is no sequence defined, it creates a sequence automatically. For example, in case of Oracle database, it creates a sequence named HIBERNATE_ SEQUENCE. 24 | 25 |
26 | 27 | 5. **hilo**: It uses high and low algorithm to generate the id of type short, int, and long. 28 | 29 |
30 | 31 | 6. **identify**: It is used in Sybase, My SQL, MS SQL Server, DB2, and SQL to support the id column. The returned id is of type short, int, or long. 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Creative Commons Legal Code 2 | 3 | CC0 1.0 Universal 4 | 5 | CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE 6 | LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN 7 | ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS 8 | INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES 9 | REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS 10 | PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM 11 | THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED 12 | HEREUNDER. 13 | 14 | Statement of Purpose 15 | 16 | The laws of most jurisdictions throughout the world automatically confer 17 | exclusive Copyright and Related Rights (defined below) upon the creator 18 | and subsequent owner(s) (each and all, an "owner") of an original work of 19 | authorship and/or a database (each, a "Work"). 20 | 21 | Certain owners wish to permanently relinquish those rights to a Work for 22 | the purpose of contributing to a commons of creative, cultural and 23 | scientific works ("Commons") that the public can reliably and without fear 24 | of later claims of infringement build upon, modify, incorporate in other 25 | works, reuse and redistribute as freely as possible in any form whatsoever 26 | and for any purposes, including without limitation commercial purposes. 27 | These owners may contribute to the Commons to promote the ideal of a free 28 | culture and the further production of creative, cultural and scientific 29 | works, or to gain reputation or greater distribution for their Work in 30 | part through the use and efforts of others. 31 | 32 | For these and/or other purposes and motivations, and without any 33 | expectation of additional consideration or compensation, the person 34 | associating CC0 with a Work (the "Affirmer"), to the extent that he or she 35 | is an owner of Copyright and Related Rights in the Work, voluntarily 36 | elects to apply CC0 to the Work and publicly distribute the Work under its 37 | terms, with knowledge of his or her Copyright and Related Rights in the 38 | Work and the meaning and intended legal effect of CC0 on those rights. 39 | 40 | 1. Copyright and Related Rights. A Work made available under CC0 may be 41 | protected by copyright and related or neighboring rights ("Copyright and 42 | Related Rights"). Copyright and Related Rights include, but are not 43 | limited to, the following: 44 | 45 | i. the right to reproduce, adapt, distribute, perform, display, 46 | communicate, and translate a Work; 47 | ii. moral rights retained by the original author(s) and/or performer(s); 48 | iii. publicity and privacy rights pertaining to a person's image or 49 | likeness depicted in a Work; 50 | iv. rights protecting against unfair competition in regards to a Work, 51 | subject to the limitations in paragraph 4(a), below; 52 | v. rights protecting the extraction, dissemination, use and reuse of data 53 | in a Work; 54 | vi. database rights (such as those arising under Directive 96/9/EC of the 55 | European Parliament and of the Council of 11 March 1996 on the legal 56 | protection of databases, and under any national implementation 57 | thereof, including any amended or successor version of such 58 | directive); and 59 | vii. other similar, equivalent or corresponding rights throughout the 60 | world based on applicable law or treaty, and any national 61 | implementations thereof. 62 | 63 | 2. Waiver. To the greatest extent permitted by, but not in contravention 64 | of, applicable law, Affirmer hereby overtly, fully, permanently, 65 | irrevocably and unconditionally waives, abandons, and surrenders all of 66 | Affirmer's Copyright and Related Rights and associated claims and causes 67 | of action, whether now known or unknown (including existing as well as 68 | future claims and causes of action), in the Work (i) in all territories 69 | worldwide, (ii) for the maximum duration provided by applicable law or 70 | treaty (including future time extensions), (iii) in any current or future 71 | medium and for any number of copies, and (iv) for any purpose whatsoever, 72 | including without limitation commercial, advertising or promotional 73 | purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each 74 | member of the public at large and to the detriment of Affirmer's heirs and 75 | successors, fully intending that such Waiver shall not be subject to 76 | revocation, rescission, cancellation, termination, or any other legal or 77 | equitable action to disrupt the quiet enjoyment of the Work by the public 78 | as contemplated by Affirmer's express Statement of Purpose. 79 | 80 | 3. Public License Fallback. Should any part of the Waiver for any reason 81 | be judged legally invalid or ineffective under applicable law, then the 82 | Waiver shall be preserved to the maximum extent permitted taking into 83 | account Affirmer's express Statement of Purpose. In addition, to the 84 | extent the Waiver is so judged Affirmer hereby grants to each affected 85 | person a royalty-free, non transferable, non sublicensable, non exclusive, 86 | irrevocable and unconditional license to exercise Affirmer's Copyright and 87 | Related Rights in the Work (i) in all territories worldwide, (ii) for the 88 | maximum duration provided by applicable law or treaty (including future 89 | time extensions), (iii) in any current or future medium and for any number 90 | of copies, and (iv) for any purpose whatsoever, including without 91 | limitation commercial, advertising or promotional purposes (the 92 | "License"). The License shall be deemed effective as of the date CC0 was 93 | applied by Affirmer to the Work. Should any part of the License for any 94 | reason be judged legally invalid or ineffective under applicable law, such 95 | partial invalidity or ineffectiveness shall not invalidate the remainder 96 | of the License, and in such case Affirmer hereby affirms that he or she 97 | will not (i) exercise any of his or her remaining Copyright and Related 98 | Rights in the Work or (ii) assert any associated claims and causes of 99 | action with respect to the Work, in either case contrary to Affirmer's 100 | express Statement of Purpose. 101 | 102 | 4. Limitations and Disclaimers. 103 | 104 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 105 | surrendered, licensed or otherwise affected by this document. 106 | b. Affirmer offers the Work as-is and makes no representations or 107 | warranties of any kind concerning the Work, express, implied, 108 | statutory or otherwise, including without limitation warranties of 109 | title, merchantability, fitness for a particular purpose, non 110 | infringement, or the absence of latent or other defects, accuracy, or 111 | the present or absence of errors, whether or not discoverable, all to 112 | the greatest extent permissible under applicable law. 113 | c. Affirmer disclaims responsibility for clearing rights of other persons 114 | that may apply to the Work or any use thereof, including without 115 | limitation any person's Copyright and Related Rights in the Work. 116 | Further, Affirmer disclaims responsibility for obtaining any necessary 117 | consents, permissions or other rights required for any use of the 118 | Work. 119 | d. Affirmer understands and acknowledges that Creative Commons is not a 120 | party to this document and has no duty or obligation with respect to 121 | this CC0 or use of the Work. 122 | -------------------------------------------------------------------------------- /Paradigms/Event-driven.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/JavaBaz/presentations/1c97989f746238dfa6b7a1d7f43e51ebbd205ad3/Paradigms/Event-driven.md -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # presentations 2 | My personal notes and presentations that I'd like to share with others. 3 | -------------------------------------------------------------------------------- /REST API/REST API.md: -------------------------------------------------------------------------------- 1 | ### Why use REST API? 2 |
3 | 4 | 1. **Securtiy** 5 | By using REST API, we can seperate backend from what user actually can see (client) and we can handle securtiy concerns. 6 |
7 | 8 | 2. **Versatile** 9 | By using REST API, we can have multiple clients (web, mobile app and etc.) 10 |
11 | 12 | 3. **Separation of concerns** 13 | By using REST API, backend and clients are fully separated and can be modified without messing up with the whole system. 14 |
15 | 16 | 4. **Interoperability** 17 | In REST API systems, each part of system can be made by different teams since there is Separation of concerns. 18 | Backend team can expose certain endpoints to other teams and make it public so other teams can consume api and use it in order to develop their product without involving backend team. 19 |
20 | --------------------------------------------------------------------------------