1/54
Testing, SOLID, Design Patterns, Threads, Comparators, Generics, Collections
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
Exception
event that disrupts the normal flow of instructions during the execution of a program
can be handled and the program can continue
Error
A serious problem that shouldn’t be caught. The program can’t recover from it so it must terminate.
Checked Exception
Exceptions that appear at compile time and are handled with a try-catch block or throwing an exception.
Unchecked Exception
Exception that occurs at runtime and aren’t checked by the compiler. Indicated by poor quality coding.
finally block
optionally added after the try-catch blocks. used to clean up resources like closing files or readers
Unit Testing
smallest piece of testable code. Simple, independent, focused
Test Driven Development
Agile. Write tests first 1. Arrange 2. Act 3. Assert.
Let it compile. Let it fail. Make it Pass. Refactor
How do you test void methods?
Use verify() from Mockito or just call it in a method to ensure it at least runs
Mockito
Create a mock object that doesn’t need to know any implementation details - has no methods or properties. For testing interactions with classes and not the logic.
Stubbing
Adding limited behavior to methods of mock objects. Allows you to return a specific value from a method.
Verification
for testing methods that return void. you can check how many times that method is called
Collection
groupings of logically related items. has access to methods
Collection Interfaces
List, Set, Map, Queue
Collection classes
ArrayList, Vector, HashSet, TreeSet, HashMap, TreeMap
Ordered Collections
Usually can be accessed by index: Lists, queues
maintains order of items added
Unordered Collections
Can’t be accessed by index: HashSet, HashMap, HashTable
Queue
First In First Out. Items are removed from the front of the queue and adding items put them on the back. Peek() returns object at front of queue and poll() removes the object at front of queue and returns it.
Set
Scattered Elements. doesn’t allow for duplicate values(will overwrite the existing one). only has methods that collections contains
Map
Stores data in key value pairs. duplicate keys not allowed (original gets overwritten) but duplicate values are. doesn’t extend the collection class.
Generics
specifies types for collections, classes and methods which will let you catch type related errors at compile time instead of runtime
Reusable, type safe
Placeholder T or ? for a wildcard
Can represent and object that is a child or parent of a class with extends or super keyword <T extends Class> < T super class>
Sorting collections
java chooses appropriate algorithm given the collection unless it has its own implementation (treeset, priorityqueue, treemap)
Comparable Interface
defines a default sort order for a custom class that you create in the class (Collections.sort() can then be used to call it)
compareTo(secondValue)
returns an int, positive means first value is larger, negative means second value is larger, and 0 means they are equal
Comparator Interface
defines custom sorts on any attribute of a class when you need multiple sorting orders. created outside of the object so compareTo method is left alone.
Unsorted Collections:
Collections.sort(listToBeSorted, new SpecificComparator())
Sorted Collections:
new TreeSet<Trainee>(new TraineeAgeComparator)
use if/else statements in compare method to prevent data loss if directly comparing doubles
Logging
provides a trace to figure out circumstances that cause issues at runtime
Log Levels
Trace
Debug
Info
Warn
Error
Fatal
Loggers
named objects that log/record events according to levels. root logger is always at the top of hierarchy.
thread safe, timestamped
configure what levels of messages you want to see
Will log to the appenders and any logger above it in the hierarchy
do not type check
Appenders
indicate output destination of log messages. a logger can have multiple appenders
SonarLint
code analysis for compliance with given standards. cheapest way compared to sonarqube. helps you find bugs, vulnerabilities, and code smell
SonarQube
dynamic code analysis more effective than sonarlint. more expensive in terms of resources but less likely to give false positives. can create your own rules too
Single Responsibility
a class should only do one thing, and therefore only have one reason to change. closely related tasks. a change in one method should not affect responsibilities in others
encapsulation, cohesion
Open Closed
classes should be open for extension but closed for modification. shouldn’t have extra code that a class inheriting it doesn’t need. extend the class then add new methods
polymorphism, abstraction
Liskov Substitution
subclasses should be substitutable for their base classes fulfills expected behaviors from the super class
inheritance, polymorphism,
Interface Segregation
interfaces should be small and deal with one aspect of a problem. only allowing relevant behavior to be seen, shouldn’t be implementing methods we don’t need
cohesion, inheritance, abstraction
Dependency Inversion
classes should depend upon abstract concepts rather than concrete implementations. depend on high level modules (parent class) and not on the details (child class)
abstraction
3 types of design patterns
Creational: making objects
Structural: assemble objects into larger structures
Behavioral: how objects interact with each other
Singleton
only one instance of an object can be created in a program. private constructor, private static instance variable of its own type, public static getinstance method
creational
Factory Method
class with a sole responsibility to create single objects from a hierarchy of classes. each factory has its own logic to create the object. uses an interface that subclasses can implement to create more specific types of objects
creational
abstract factory method
creates families of related objects without specifying the concrete classes. abstract methods for creating each product. concrete factories will implement this to create the specific objects
creational
Adapter
allows 2 incompatible interfaces to work together. acts as a middleman to bridge the gap between them. when you shouldn’t be modifying either class and need a new one altogether
structural
Command
object encapsulating a method call used when actions need to be stored and performed at a later time. client, command object, invoker, receiver
behavioral
Object Pool
allows reuse of objects without creating a new one each time to save resources for expensive ones. object pool, reusable object, client
Thread
sequence of instructions that exist within a process. shares resources and memory with other threads
Thread states
New: first created
Runnable: start method called on it and enters queue
Running: thread is doing work - can enter waiting or sleep and return to the queue from this point
Terminated: thread completed
Join()
the thread currently being exeuted must stop and wait for this thread to be done before continuing (usually means the main thread is waiting)
Multithreading
single program has multiple threads so methods don’t need to wait for each other to finish before running. multiple cores in CPUs to run their own threads
Process
space/memory and resources allocated to single program (usually just one)
has at least one thread (main thread)
Concurrency
performs more than one thing simultaneously. is mimicked in java as it switches back and forth between threads
Race Condition
2 or more threads have access to an object’s data and you don’t know which thread will finish first. the time they read the values may not be the expected value before performing operatiosn
synchronization
synchronized keyword used for methods or blocks of code to avoid thread interference. only one thread can run that piece of code at a time
Reentrant Lock
a lock put on a specific resource so that no other thread can access it while in use. uses lock() and must be unlocked by unlock()
Deadlock
2 threads hold a resource that the other thread wants but won’t unlock/release it until it receives the resource it needs.
livelock
like deadlock but the state of processes are constantly changing in regards to each other. depends on timing and may not happen all the time
starvation
process is perpetually denied necessary resources. forever in a state of waiting
optional
wrapper containing an object or null value
has a return type so it will never return null
solves problem of null pointer exception especially when chaining method calls