본문으로 건너뛰기

"fsd" 태그로 연결된 9개 게시물개의 게시물이 있습니다.

모든 태그 보기

FSD +009

· 약 5분

Exception

  • Exeptions are throwable objects.
  • Checked Exceptions are checked by the compiler and should be handled (thrown or caught).
  • Unchecked or runtime Exceptions are not flagged by the compiler. Their occurrence during execution interrupts the program.
  • Exceptions can be thrown by developers. Throwing an exception delegates handling the exception to a different class or different level of the program.
  • Thrown exception is left not handled, it will cause runtime error.

Error

  • Java Errors usually indicate problems with the JVM or system resources.
    • it is not meant to be caught or handled by applications.
    • the base class is Error.
  • Python is no separate Error class hierarchy. Errors are represented as exceptions.
    • ValueError, TypeError, MemoryError, SystemError, etc. are subclasses of Exception.

Java vs Pythone Exceiptions

FeatureJavaPython
Syntaxtry-catch-finallytry-except-else-finally
tryattempts to execute a block of codeattempts to execute a block of code
catch/exceptexecute alternative code if exception arisesexecute alternative code if exception arises
finally (optional)executes code regardless of try/catch outcomeexecutes code regardless of try/except outcome
else (optional)Xexecutes code if no exception arises
public class ExceptionExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter first number: ");
int a = scanner.nextInt();
System.out.print("Enter second number: ");
int b = scanner.nextInt();
int result = a / b; // This will raise ArithmeticException
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
} catch (NumberFormatException e) {
System.out.println("Caught a number format exception: " + e.getMessage());
} finally {
System.out.println("This block always executes.");
}
}
}
def div(a, b):
return a / b

a = input("Enter first number: ")
b = input("Enter second number: ")

try:
result = div(int(a), int(b)) # This will raise ZeroDivisionError
print("Result:", result)
except ZeroDivisionError as e:
print("Caught an exception:", e)
except ValueError as e:
print("Caught a value error:", e)
else:
print("No exception occurred.")
finally:
print("This block always executes.")

Throwing Exceptions

class IncorrectAgeError(Exception):
def __init__(self, age):
self.age = age
self.message = f"Age {age} is not valid. Age must be between 0 and 120."
super().__init__(self.message)

number = int(input("Enter your age: "))

try:
if number < 0 or number > 120:
raise IncorrectAgeError(number)
print(f"Your age is {number}.")
except IncorrectAgeError as e:
print(e)

File Handlers

  • "r": Opens a file for reading, requires the file to exist
  • "w": Opens a file for writing. If the file exists, it is truncated to zero length. If the file does not exist, a new text file is created.
  • "a": Opens file for open for writing. The file is created if it does not exist.
  • "+": Opens a file in updating mode (reading and writing). It can be used with reading (r+) and writing (w+) modes.
  • "t": Opens a file in text mode (default mode).
  • "b": Opens a file in binary mode. It can be used with reading (rb) and writing (wb) modes.

File Handler Methods

os.path.exists("file.txt") # Check if file exists
os.remove("file.txt") # Delete a file
os.remove("dir") # Delete an empty directory
os.chdir("path/dir") # Change current working directory
os.getcwd() # Get current working directory
os.mkdir("path/dir") # Create a new directory

file_handler = open("file.txt", "r") # Open a file in read mode
file_handler.read() # Read the entire file content
file_handler.readline() # Read a single line from the file
file_handler.close() # Close the file

file_handler = open("file.txt", "w") # Open a file in write mode
file_handler.write("Hello, World!") # Write to the file
file_handler.write("\n") # Write a newline character
file_handler.close() # Close the file


import csv
with open("file.txt", "r") as file_handler: # Using 'with' to handle file
csv_object = csv.reader(file_handler)
for row in csv_object:
print(row)
file_handler.close()

with open("file.txt", "a") as file_handler: # Append mode
csv_writer = csv.writer(file_handler)
row = ["1", "gracefullight", "100"]
csv_writer.writerow(row)
file_handler.close()

import json
with open("data.json", "r") as file_handler:
data = json.load(file_handler) # Load JSON data from file
print(data)
file_handler.close()

with open("data.json", "w") as file_handler:
json.dump(data, file_handler) # Write JSON data to file
file_handler.close()
  • InputStream: reads byte-based input from various sources like files, memory, or network connections.
  • OutputStream: writes byte-based output to various network connections.

Unit Testing

  • tests and verifies the smallest unis of an application such as functions, procedures, modules, or objects.
  • the conducted during the development phase of the SDLC.
  • Developers aim to identify defects and code bugs, which can save time and reduce costs in later testing stages.
  • software testing encompasses the fourmain testing phases, and unit testing is at the foundational level of the process.
    • Unit Testing
    • Integration Testing
    • System Testing
    • Acceptance Testing

Python unit testing

  • test cases are defined using classes that inherit from unittest.TestCase
  • assertions are used to validate results self.assertEquals()
  • the unittest.TextTestRunner class can be used to run tests
import unittest

class TestMathOperations(unittest.TestCase):

def test_addition(self):
self.assertEqual(2 + 3, 5)

def test_subtraction(self):
self.assertEqual(5 - 2, 3)

def test_multiplication(self):
self.assertEqual(4 * 3, 12)

def test_division(self):
self.assertEqual(10 / 2, 5)

FSD +008

· 약 5분

OOP Principles

Encapsulation

  • bundles data attributes (fields) with methods that use the data in a single unit called "Object"
  • hides sensitive data attributes by declaring the fields private.
  • fields can be declared protected in the parent class, allowing access from the child class.
  • exposes the data attributes values only through public getters/setters to allow access or modification of the field values.

Intheritance

class A:
pass

class B(A):
pass

class C(A):
pass
  • Superclass defines common method signatures (with/without implementation) and fields.
  • Subclasses provide the implementations for (or override) these method signatures
  • private attributes cannot be directly accessed from the child classes.
  • to refer to superclass properties (fields, methods) or constructor, use the keyword super()

Polymorphism

  • means many forms.
  • permits an object to have multiple types.
  • allows object of different types but with a common parent to be stored in the same collection.
  • enables inherited methods from the parent to perform different tasks when called by subclasses.

Abstraction

  • the process of hiding the implementation details and exposing only the necessary behavior to the user.
  • abstract class must at least contain one abstract method.
  • abstract class ccan have concrete methods.
  • abtract methods are only prototypes in the parent class, the actual implementation is provided by the subclasses that inherit the abstract class.
  • rules
    • if a class contains at least on abstract methods, it should be declared abstract.
    • if another class inherits an abstract class, it must implement all the abstract methods of that class.
from abc import ABC, abstractmethod

class Person(ABC):
def __init__(self, name):
self.name = name

@abstractmethod
def show(self):
pass

def show_name(self):
print(f"Name: {self.name}")

class Student(Person):
def __init__(self, name, id):
self.id = id
super().__init__(name)

def show(self):
super().show_name()
print(f"ID: {self.id}")
  • interfaces are complete abstract classes declared with the interface keyword.
  • only contain prototype (abstract) methods with empty body code.
  • cannot be instantiated nor inherited as they do not have constructors.
  • a class can implement multiple interfaces.
  • a class implementinig an interface must provide an implementation for all its abstract methods.
  • add an access layer to further hide the methods impelmentation.
  • act as a middleware inside the program, allowing human, machines, and other software to interact with the program's functionalities without knowing the implementation details.
# interface A is a fully abstract class
# interface A must inherit ABC
# class B(A) must implement all abstract methods of A
# interface A methods have the @abstractmethod decorator with pass as body-code
from abc import ABC, abstractmethod

class Person(ABC):
@abstractmethod
def show_info(self):
pass

class Student(Person):
def __init__(self, name, id):
self.name = name
self.id = id

def show_info(self):
print(f"Name: {self.name}, ID: {self.id}")

OOP Design Rules

  • How to split the code into seperate classes and preserve encapsulation
  • How to organizae the code into methods to hide the implementation details and expose the behavior
  • How the objects interact at runtime
  • How to name the class entities

5 Design Rules

  • Encapsulation
    • hide fields behind methdos
    • requires fields to be private while allowing methods to be public
    • requires a methods related to a field (such as access, modify, use) be defind in the same class.
  • Push code to the right
    • requires the code/methods used by objects of a class be written in the same class.
    • ensures methods are written for reusability and placed in the correct class so they can make use of the class's fields.
    • determines which class is responsible for defining the methods needed to achieve the program's goals.
  • Spread plans across classes
    • involves planning the distribution of code across multiple classes from the start.
    • focuses on distributing responsibilities logically among different classes, so that each class has a clear and focused role.
    • by convention, this rule requires using the same method name (for the same goal) across all classes.
  • Hide by default
    • hiding implementation details within a class and exposing only the necessary functionality to the outside.
    • helps in achieving encapsulation and abstraction.
    • promotes better design and maintainability.
  • Follow naming conventions
    • use nouns to name fiels.
    • use nouns to name functions.
    • use verbs to name procedures.
    • if an entitiy is compsed of two or more words.
      • use camelCase/snake_case for fields and methods.
      • use PascalCase for class names.
  • consolidates the action-trieggers of a program into a single method.
  • common design choice in applications with user interaction.
  • the menu methods is executed in the program's main method.
    • offers users interactive CLI command choices.
  • menu() requires a read-function in a while loop, allowing the menu() tor repeatedly read inpus from STDIN.
<condition> = read_choice()

loop (<condition>):
check (<condition>):
case 1: do task <action_1()>
case 2: do task <action_2()>
...
case n: do task <action_n()>
default: <alternative-action>
menu(self):
choice = input("Enter choice: (d/w/b/h/x): ").lower()
while choice != "x":
match choice:
case "d":
self.deposit()
case "w":
self.withdraw()
case "b":
self.show_balance()
case "h":
self.show_history()
case "x":
self.exit()
case _:
self.show_invalid_choice_message()

choice = input("Enter choice: (d/w/b/h/x): ").lower()

FSD +007

· 약 3분

Collection

a data sturcucture that groups multiple elemtns togehter logically.

  • referenced by the collection name, and its elements are accessed using indexing or look up methods.
  • some collections allow dynamic sizing, expanding and shrinking with the data, others have a fixed size.
  • can store mixed data types.
    • Java collections are typically type-safe using generics.
    • Python uses dynamic typing.

Python List

mylist = ["Tom", 30, 112.5]
len(mylist)
mylist[index]
mylist.append(item)
mylist.insert(index, item)
# returns a slice of a list from first to last-1
mylist[first:last]
mylist.index(item)

# replaces items from first to last-1 with a list
mylist[first:last] = [list-values]
# adds list 2 at the end of list 1
mylist = list1 + list2
# adds list 2 at the end of list 1
list1.extend(list2)

mylist.remove(item)
mylist.pop(index)
mylist.pop()
del mylist[index]
del mylist
mylist.clear()

# Sorts the list alphanumerically, ascending
mylist.sort()
mylist.sort(reverse =True)
mylist.reverse()
mylist.count()

Python Set

  • unordered, not indexed.
  • mutable, unique.
myset = { 'hello', 5, True, 3.5 }

for x in myset:
print(x)

myset.add(item)
# Merges myset iwth the otherset, rtaining unique values
myset.update(otherset)
# Adds other set items to a set (only unique items are retained)
mynewset = myset.union(otherset)
# Retain only the items that exists into set1 and set2
myset = set1.intersection(set2)

# report error if item not found
myset.remove(item)
myset.discard(item)

myset.pop()
myset.clear()
del myset

Python Tuple

  • a cllection of items of any type
  • ordered, indexed
  • unchangable, once a tuple is created the elemets are fixed
mytuple = ("Tom", 30, 112.5)
len(mytuple)
mytuple[index]
mytuple[first:last]
mytuple = tuple + tuple2

Python Dictionary

  • a collection of items represented as key-value pairs
  • unordered, indexed by uniaue keys
  • itmes are mutable
  • allow duplicate values but not duplicate keys
mydata = {
"name": "Tom",
"age": 30,
"role": "admin"
}

mydata.keys()
len(mydata)
mydata[key]
mydata[key] = new-value
del mydata[key]
del mydata

# Deletes an entry associated with key
val = mydata.pop(key)
# Updates/Inserts { k: v } entry into the dictionary
mydata.update({ k: v })

Java List

  • an interface of the Java Collection Framework (JCF)
  • cannot be instantiated.
  • common implementation of List interface
    • ArrayList
    • LinkedList
List<Integer> numbers = new ArrayList<>();
List<String> names = new LinkedList<>();

numbers.get(0);
numbers.get(numbers.size() - 1);

names.get(indexOf("Hello"));
names.get(lastIndexOf("Hello"));

numbers.add(5);
names.remove("Hello");
names.remove(indexOf("Hello"));

numbers.removeAll(<another list>);
// set(2, 12) replaces the item at index 2 with 12
numbers.set(2, 12);

Java Set

  • an interface of the Java Collection Framework (JCF)
  • unordered, unique objects.
HashSet<String> names = new HashSet();
HashSet<String> names = new HashSet(Array.asList("Tom", "Jerry", "Mickey"));

HashSet<String> names = new HashSet();
ArrayList list1 = new ArrayList();
ArrayList list2 = new ArrayList();

list1.add("Tom");
list1.add("Jerry");

names.addAll(list1);
names.addAll(list2);

names.remove("Tom");
boolean isRemoved = names.remove("Tom");

for (String name : names) {
System.out.println(name);
}

Iterator<String> it = names.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}

names.clear();
names.isEmpty();
names.contains("Tim");
names.size();
names.removeAll(set2);
names.containsAll(set2);
// Retain set2 elements and discard the rest
names.retainAll(set2);

Java Map

  • interface from java.util stores data as a keiy-value pairs
  • contain unique keys that are associated with specific values.
HashMap<Integer, String> people = new HashMap<>();
people.put(1, "Tom");
people.put(2, "Jerry");
people.put(3, "Mickey");

people.putIfAbsent(2, "Donald");
System.out.println(people.get(2));

people.put(2, "Lucy");
people.replace(2, "Amy");
people.remove(2);

System.out.prinln(people.keySet());
System.out.println(people.values());

people.clear();
people.isEmpty();
people.containsKey(2);
people.size();
people.getOrDefault(50, "Unknown");
// Checks if the value is mapped with one or more keys
people.containsValue("Jim");

Operation Patterns

  • Finding an item in a list: Using the lookup pattern
  • Finding multiple items in a list: Using the updated-lookup pattern
  • Removing certain items from a list: Using the remove-all pattern

FSD +006

· 약 4분

OOP vs Procedural Programming

OOP

  • a programming paradigm built around the concept of objects, which contain data and code to manipulate data.
  • The idea to model real-world entities and their interactions.
  • Global Data (fields) are enclosed in the objects.
  • Program components/tasks are easily divided across the development team / Requires more planning and design preparation
  • Easier to manage and maintain dependencies between objects / OOP programs are much larger and complex
  • Objects export the interface and hide the implementation and data / Tend to use more memory and GPU
  • Code is highly reusable and easy to scale and distribute / Making changes in one class potentially impact others, which can complicate the development of the code.

Procedural Programming

  • the concept of procedure calls by structuring the program around procedures. (or functions/subroutines)
  • a sequential manner unless directed otherwise.
  • Global data (elements) is exposed to all the functions.
  • Easier to compile and interpret / Difficult to scale or extend
  • Straightforward and simpler to code / Dependencies between elements are unclear and not well-structured.
  • Less memory requirements / Data is exposed and insecure due to its exposure across the whole program
  • Easy to track the program flow / Hard to divide the work among programmers in a team.

Classes

  • A class is a template/blueprint used to create objects
javapython
a pure OOP languagesupports OOP
code must be written in classesclasses are optional
executable class must have main()scripts run without including a class
Encapsulation can be enforced by declaring fields as privatefields (global variables) are public by default
Visibility is managed through access modifiersN/A ("_" to identify private data attributes, but still accessible)
class <class-name> (<extend - superclass>):
<variable-name> = <value> #Class fields - data members

def __init(self, <parameters>): #class constructor - object sbuilder
<code>

<method-name> (self, <parameters>): #methods
<code>

Classes Py

KeywordsFunctions
class__init__()
self: keyword used to refer to object propertiesdel: the function is used to delete an object
pass: keyword used to occupy no-code placement in a function__str__(): The function is used to return string representation of instances
cls: keyword used to refer to class propertiessuper(): the function is used call a parent method in a child class
  • Accessors: functions (with no parameters) in a Python class that provide access to the data attributes of an object.
    • known as getter methods, are named starting with the verb get, followed by the field name, which should start with an uppercase letter.
  • Mutators: procedures (with parameter) in a Python class that enable the developer to modify the values of object attributes.
    • known as setter methods, are named starting with the verb set, followed by the field name, which should start with an uppercase letter.
def get<Variable> ():
return self.<field>

def set<Variable> (self, value):
self.<field> = value

Classes Java

public class Bank {
private Customer customer;
private String branch;

public Bank() {
customer = new Customer();
}

public Bank(String name) {
this();
this.branch = name;
}

public boolean find(Bank bank) {
return this.branch.equals(bank.branch);
}
}

Packages

Packages Java

  • used to group related classes
  • like folders containing files (classes)
  • either Java defined or user-defined
  • used to write maintainable and portable code and to avoid class name conflicts.

Modules Py

  • used to grou prelated functio nand classes together
  • normal Python scripts that are used into other scripts
  • either Python defined or user-defined
  • used to write maintainable and portable code to improve reusability

FSD +005

· 약 2분

Method

  • a block of code grouped together and has a name
  • can be invoked by its name to perform certain action
  • can have parameters that represent the values needed for the method to run
  • can have local variables usable only within its own code block.

Function vs Procedure

  • Procedure: no return value, perform an action
    • Example: move(), run(), deposit(), eat()
  • Function: have a return value, do not perform any action
    • Example: total(), sum(), area()
  • a function and behaves as a combined function procedure, but not recommended.

Method Overloading

  • Java allows methods in the same class to have the same name but different parameters.
  • method signature: The method name together with the number and types of a method's parameter.

Parameter vs Arguments

  • Parameter: placeholder variables used at method definition, indicate the type and order of argument
  • Arguments: data values passed to the method when the method is invoked or called.

Patterns

The read pattern

def <name>():
<prompt>;
return <type>

The update read-loop pattern

<read function>
while (<value> != <end value>):
<use the value>
<read function>

The array-loop pattern

for <value> in <range>:
>use the item from array>

The any-pattern

for <item> in <collection>:
if (<test>):
return True
return False

The every-pattern

for <item> in <collection>:
if (not(<test>)):
return False
return True

The none-pattern

for <item> in <collection>:
if (<test>):
return False
return True

Boolean Functions

def isEven(number):
if number % 2 == 0:
return True
else:
return False

def isEven(number):
return (number % 2 == 0)

Recursion

  • a technique where a method calls itself repeatedly.
  • to provide a termination logic for a recursive method to avoid infinite execution.
def factorial(n):
return 1 if (n == 1 or n == 0) else n * factorial(n - 1)

def factorial(n):
F = lambda n: n * F(n-1) if n > 1 else 1
return F(n)

Process in Programming

  • process is the method used to solve a problem
  • Break it down-Build it up is a technique structured approach to handle complex problems.

FSD +004

· 약 1분

match

match term:
case pattern-1:
action-1
case pattern-2:
action-2
case pattern-3:
action-3
# the underscore _ case executes the default code
case _:
action-default

Repetition Statements

  • The count-controlled repetition: a fixed number of times.
  • The sentinel-controlled repetition: a designated value that ends the loop.
  • The infinite repetition: continues until externally stopped.

The For Loop

for <value> in <range of values>:
<code>
sum = 0;

# [1, 2, ..., 19]
# adds values from 1 to 19 to sum
for e in range(1, 20):
sum += e

print(f"The sum is: {sum}")

Loop-And-A-Half

n = 5
sum = 0

while n < 10:
sum += n

if sum > 100:
break

FSD +003

· 약 4분

Terminology

  • Software: A set of statements written in a programming language to perform tasks
  • Statement: A single instruction in a program that performs an action when executed.
  • Snippet: A block of statements.
  • Software Development: The process of creating a software program.
  • OOP: Program composed of interconnected objects at runtime.
  • Expression: An entity-code component of a statement that can be evaluated to produce a value.
  • Assign: The process of storing the result (a value) of one or more expressions.
  • Value: A data item (literal or computed) that is stored in a variable.
  • Compiler: A special program that translates a programming language's source code into machine code.
    • Compilers complete the conversion process all at once after changes are made to the code and before the code is executed
  • Interpreter: A computer program that directly executes code without requiring it to be previously compiled into machine language.
    • Interpreters complete the conversion process one step at a time while the code is being executed.

Software development

  • Software development process is an iterative approach.
  • java
    • javac Welcome.java: Compiles the Java source file Welcome.java into class binary file.
    • java Welcome: Executes the Java program Welcome.
  • python
    • python welcome.py: Executes the Python script welcome.py.

OOP

  • Object: An object is a thing, tangible and intangible. An object has fields that contain the data and methods to access and modify the data.
  • Class: A class is an abstract definition of objects. A class is a template of a blueprint that defines what data and methods are included in objects.
  • Method: A block of code grouped together to perform an operation. A method has a name, parameters, and a return type.
  • Field: A field is a data attribute of an object. A field value is exposed using object methods.
  • Organizing code into classes improves modularity, reusability, extendability, and scalability.

Java vs Python

Identifier typeJavaPython
ClassUse CamelCase for multi-word classesUse snake_case for multi-word classes
Functionuse verbs or verb phrasesuse lowercase_with_underscores
Procedureuse verbs or verb phrasesuse lowercase_with_underscores
VariablecamelCaselowercase_with_underscores
ConstantAll uppercase words separated by underscoresAll uppercase words separated by underscores
PackageLowercase words separated by dotsLowercase words separated by underscores
  • Java uses the toString() function to return objects' information.
  • Python can refer to attributes directly or use the __str()__ function to return objects' information

Data types

Data TypeSizeDefault valueDescription
byte1 byte08-bit signed integer
short2 bytes016-bit signed integer
int4 bytes032-bit signed integer
long8 bytes064-bit signed integer
float4 bytes0.0f32-bit floating point
double8 bytes0.0d64-bit floating point
boolean1 bitfalsetrue or false
char2 bytes'\u0000'16-bit Unicode character

Non-Primitive Data Types

  • Non-primitive: Arrays, Classes, Interfaces, and Strings.
  • Non-primitive data types are by default set to null in Java, None in Python.

Variables

  • Static: enables the variable to be used without creating an object of its defining class.
  • Final: makes the variable unchangeable.

Operators

Operator CategoryJavaPython
Unaryexpr++ expr--
++expr --expr +expr -expr+expr -expr
Arithmetic* / &* / &
+ -+ -
Relational< > <= >=< > <= >=
== !=== !=
Logical! &&not and
||or
Ternary(expr1) ? <expr2> : <expr3>(expr1) if <expr2> then <expr3>
Assignment= += -= *= /= %== += -= *= /= %= **=
Identity/Membershipis is not in not in
  • Java: boolean q = (5 % 2 != 2) ? true : false
  • Python: q = True if (5 % 2 != 2) else False

Standard Input

import java.util.Scanner;

public class Inputs {
static Scanner in = new Scanner(System.in);

public static void main(String[] args) {
System.out.print("X = ");
int x = in.nextInt();
System.out.println("x squared = " + Math.pow(x, 2));
}
}
import sys

x = int(input("x = "))

print("x squared = ", pow(x, 2))

String

String (java)

Immutable

  • String s1 = "Hello";: initialize using literal syntax
  • String s2 = new String("Hello");: initialize using a constructor
s1 == s1 // false
s1.equals(s2) // true

String Format (Python)

SymbolMeaningExample codeOutput
<Left alignf'[{42:<5}]'[42 ]
>Right alignf'[{42:>5}]'[ 42]
^Center alignf'[{42:^5}]'[ 42 ]
< with fill charLeft align with custom fillf'[{42:-<5}]'[42---]
> with fill charRight align with custom fillf'[{42:->5}]'[---42]
^ with fill charCenter align with custom fillf'[{42:->5}]'[-42--]

Array

Array (java)

int[] x = {2, 4, -1, 11, 3};

  • Declaration: int[] x
  • Instantiation: x = new int[5];
  • Initialization: x[0] = 2; x[1] = 4; x[2] = -1;

FSD +002

· 약 7분

Classes & Objects

Class

  • A template that defines the attributes and methods of an object, which can be used to create many objects.
  • Name of the class is noun.
  • Functions are defined in the class, containing the function data.
  • Many objects can be created from the same class.
  • A class can be inherited by many sub-classes
  • A child class can have one or more parent classes. (super-classes)
  • Encapsulated data
  • Behaviors of a class are exposed while the implementation is hidden.

Object

  • An instance of a class, created the class template during runtime.
  • Object-oriented software is composed of many objects
  • a composite data type identified by its attributes (fields) and behaviors (functions), which are defined in the class.
  • object-oriented design analysis: to identify the classes and relationships between the classes to model how the system would work.

Procedure & Function

AspectProcedureFunction
Returns value?❌ Usually does not return a value✅ Usually returns a value
PurposePerform an actionCompute and return a result

Object-Oriented Paradigm Principles

Abstraction

  • hides the internal implementation of functions and expose to other class the behavior of those functions.
  • Data abstraction: hide the variables stored the data and only expose the values.
  • Function abstraction: hide the function code and only export the function behavior.

Encapsulation

  • a fundamental principle of OOP, increases data and code security, enhances performance by reducing object interactions.
  • minimize the number of interactions from outside.

Inheritance

  • allows classes to have sub-classes.
  • a parent class can have many children.
  • a child class can have more than one parent.
  • a child class inherits their parent class and can also override them.

Polymorphism

  • more of the same type of object can be used interchangeably.
  • object of different types to be treated as objects of a common parent.
  • multiple object types with the same parent can implement the same function in different ways.
  • multiple object types with the same parent can use the same attributes with different values.

Object-Oriented Design

  • The process of designing a software using oop.
  • Identify the classes -> Identify the classes' attributes and behaviors -> Identify the how classes interact with each other and create a visual class model

Identify classes

  • Classes are derived from use cases and actors described in the requirement analysis process.
  • Classes should be identified exactly as needed.
  • Reduce coupling and enable extensibility.
  • Identifying a class always requires to identify the fields and methods.
  • A class can use the methods of another class. -> one class (the client) uses or depends on another class (the supplier).

UML Class diagram

  • UML visual representation of the object-oriented software system.
  • Describes the attributes and operations of classes, relationships, and any constraints.
  • Used as a plan to construct executable code and define the way in which objects may interact.

Associations

  • a relationship between classes indicating a meaningful connection.
  • Labelled by
    • Association name
    • Role name
    • Multiplicity
    • Navigability

Multiplicity

  • how many instances of type A can be associated with on instance of type B.

Recursive or reflexive association

  • a class can have an association with itself.

Attributes

  • m:m association can be divided into two 1:m associations.

Association Classes

  • An attribute is related to an association.
  • Instance of the association class have a life-time dependency on the association.
  • an associative type should exist in the background somewhere.

Generalization & Specialization

  • Generalization: the activity of identifying commonalities among concepts and defining superclass (general concept) and subclass (specialized concepts) relationships.
  • "is-a" relationship
  • a subclass inherits from a superclass.

Benefits of generalization

  • Code Reusability
  • Cleaner/Simplified design
  • Scalability
  • Extensibility
  • Easier Maintenance
  • Testability
  • Modularity

Class inheritance

  • same as generalization and specialization.
  • the subclasses inherit the attributes and methods of the superclasses.
  • When a hierarchy is created, statements about the superclass apply to subclasses.
  • A conceptual subclass should be a member of the set of the superclass.
  • The conceptual subclass is a kind of superclass.
  • <subclass> is a <superclass>
  • Every instance of the <subclass> can be viewed as an instance of the <superclass>.

Subclass

  • has additional attributes of interest.
  • has additional associations of interest.
  • is handled differently than the superclass or other subclasses.
  • represents an object that behaves differently than the superclass or other subclasses.

Superclass

  • Create a conceptual superclass when:
    • The potential conceptual subclasses represent variations of a similar concept.
    • The subclass fully conforms to the attributes and associations of its superclass. (100% rule)
  • All subclasses have the same attributes and operations which can be factored out and expressed in the superclass.
  • All subclasses have the same associations which can be factored out and related to the superclass.

Abstract Class

  • a parent class that cannot be instantiated.
  • at least one of its operations is abstract.
  • an abstract operation has its signature defined in the abstract parent class, but the implementation is defined in the child class.
  • create a high-level modelling vocabulary.

Interface & Realization

  • a class with no attributes.
  • can't be instantiated.
  • simply declares a contract that may be realized by zero or more classes.
  • to separate the specification from its implementation.
  • only defines a specification for what the class should do and it never implies how it should do it.
  • the class implementing an interface has a realization relationship with the interface.

Aggregation

  • a type of whole-part relationship in which the aggregate is made up of many parts.
  • Signified with a hollow diamond.
  • implies the part may be in many composite instances.

Composition

  • a stronger form of aggregation.
  • the multiplicity at the composite end may be at most one
  • Signified with a filled diamond.
  • There is a create-delete dependency. Their lifetime is bound within the lifetime of the composite.

Dependency

  • a relationship between two or more model elements whereby a change to one element
  • The most common dependency stereotype is <<use>>, which simply states that the client makes use of the supplier in some way.

Visibility

  • + public
  • - private
  • # protected
  • ~ package

Example

UML Tools

FSD +001

· 약 8분

Software Engineering

SDLC

SW Development Methodologies

Waterfall

  • Pros
    • Simple & easy: each phase has specific deliverables
    • Clear & set milestones
    • Fixed requirements
    • Works well for small projects with specific set of requirements
    • Determine the schedule early
    • Clear structure
  • Cons
    • Working sw produced only at the end
    • High uncertainty of sw quality and functionality
    • Delayed testing, delays sw bugs discovery
    • After completion, no formal way to change the requirements
    • Fix working model, difficult to implement for complex projects

Agile

  • Iterative cyclical progression of the SDLC
    • Repetitive structure based on iterations (sprints)
    • 2 ~ 4 weeks, SDLC repeats
    • Each release has 3 or more iterations
    • Working prototype is produced at the end of each iteration
    • Prototype is for QA and used as input for next iteration
    • Multiple releases
  • Pros
    • Innovation through team collaboration
    • Time to market
    • Continuous testing
    • Risk reduction, finding sw bugs early
    • Customer feedback loop
    • Flexibility to change requirements
    • Automates most of the SDLC === DevOps approach
  • Cons
    • Lack of long-term planning
    • Cost estimation is difficult
    • Limited documentation
    • No finite end
    • Difficult to see the end result due due to cyclic nature of agile

SW Development Paradigms

Procedural Programming

  • Top-down decomposition: Each sub-problem is typically implemented as a function or procedure
  • Root represents the main program
  • Leaves denote individual procedures or functions

Object-Oriented Programming

  • Abstraction: The process of hiding unnecessary details
  • Encapsulation: Restricts the direct access to components of an object, while using methods to access and modify the data
  • Inheritance: The process of creating sub-class
  • Polymorphism: Allows for the creation, use, and storage of multiple objects that inherit from the same parent class

Requirements Analysis

Instructions provided by the stakeholder describe a target system

  • system properties, attributes and how a system should behave
  • Decomposed into Functional requirements / Non-functional requirements

Requirements Validation

  • Compliance
  • Correctness
  • Completeness
  • Consistency
  • Usability
CriteriaDescriptionSatisfactory Score (0-5)Recommendations
ComplianceDegree to which the requirements meet with industry standards and regulations0-
CorrectnessDegree to which the requirements is correct in terms of spelling, accuracy, grammatically.0-
CompletenessDegree to which the functional requirements match the intended software behavior0-
ConsistencyDegree to which the requirements can be mapped to use cases0-
ExpandabilityDegree to which the requirements can be modified and improved to meet the project objectives0-

Use Case

an actor wants the system to, and captures functional requirements

  • always started by an actor, always written from the perspective of the actor
  • a series of actions that a user must initiate to carry out some useful work and to achieve a goal
    • preconditions -> main flow -> alternative flow -> postconditions
  • reflects all the possible events in the system
  • complete set of use cases describes all the possible ways the system will behave and defines all the requirements

Use Case Backlog Template

IDUse Case TitleActor(s)Goal/DescriptionPreconditionsPostconditionsPriorityStatusNotes
UC-001User LoginUserAllow users to log in to the systemUser must have an accountUser is logged inHighOpen-
UC-002View ProfileUserAllow users to view their profile informationUser must be logged inUser profile is displayedMediumOpen-

User Stories

  • Planned to be delivered in a single iteration, some user stories may span multiple iterations
  • Single requirement expressed from developer's perspective
  • Describes a functional or non-functional requirement
  • As a student
  • I want to submit assignments online
  • so that I can receive feedback from my instructor.
IDUser StoryAcceptance CriteriaPriorityStatusStory PointsNotes
US-001As a student, I want to submit assignments online so that I can receive feedback from my instructor.- User can upload assignment files
- User receives confirmation of submission
- Instructor can view submitted assignments
HighOpen5-
US-002As a student, I want to view my grades online so that I can track my academic progress.- User can view grades for each assignment
- User can see overall course grade
- Grades are updated in real-time
MediumOpen3-

UML

  • Actors: Entity that performs actions in the system
  • Use Cases: Oval representation inside the system boundary of a functional requirement
  • System Boundary: Square representation of the system scope
  • Relationships
    • Association: Between an actor and a use case
    • Include: Between use cases, The included use case is always necessary for the completion of the activating use case.
    • Extend: Between use cases, The extension use case is activated occasionally at specific extension point.
    • Generalization/Inheritance: Between use cases, they achieve the same goal but in different ways.

Use Case Model

  • System boundary: Defines the scope of the system
  • Generalization: Describes the shared parts in a parent use case, then specializes in child use cases
    • Inherit features from their parent use case
    • Add new features
    • Change inherited features
  • Short, simple use cases on the core functionality may be completed within one iteration.
  • Keep use cases short and simple
  • Focus on what, not the how
  • Avoid functional decomposition

UML Use Case Model

  • CRUD
    • Create a record
    • Retrieve the record given a key
    • Update the record with new data and store it
    • Delete a record
  • Each is a separate goal, possibly carried by a different person with a different security level.