Karteikarten
Computer Science
Karten in diesem Stapel (65)
- 1Objects-Objects are nouns = Books, Pens
-Objects are used to give structure to Code
-Real world objects become objects in programming
-This helps understand how your code impacts on the real users of the system
-A Class is an idea, an abstraction e.g Smartphone..?
-An object is an instance of that idea e.g iPhone, Nexus....
-Many objects can be the same Class
-Objects have attributes: Data, Methods - 2Objects: PropertiesProperties in C# are:
- A hybrid between field and method
-Utilize the keywords set and get
-Often used as a convenient shorthand to provide a public 'field'
-Allows more interesting options, such as: a read-only fiels or a write-only field - 3Objects: ConstructorsAn object can define more than one constructor.
-Each constructor must have a unique signature(as defined by the type of the arguments)
-A constructor does not have to assign a value to every field in the object
-If the empty argument constructor is not explicitly defined, the compiler provides one for you - 4Static fields and methodsThe static keyword can be applied to a field or a method. In doing so it:
- Specifies that the field or method belongs to the type itself (the class) rather than an object instance - 5Objects: More in detailVisible:
- private - in class
-public - all classes
- protected - current and derived (inheriting) classes
- ToString()
- Equals(Obj) same instance
- Equals(Obj1, Obj2) same instance in static version
- Finalize()/Destructor tidies up after use:
-- called by the Garbage Collector
-- used to release 'unmanaged resources' - 6Objects: SummaryA Class defines what an object is
Key Points:
- Data + Methods
- Properties
- Constructors - methods with the same name as class
- Static - Class level variables and methods
- Scope - local to method, in object or the in the class - 7Inheritance- You can only inherit from one class
- A class can inherit from a class which in inherits from another
- Interfaces can be inherited from other interfaces - 8Inheritance - Abstract ClassAn abstract Class may have abstract methods:
- The class and at least one method/property must be abstract
- an abstract method has no definition in the abstract class
- a derived class MUST define all the abstract methods
- a derived class must use the keyword override when defining abstract methods - 9Inheritance - InterfaceAn interface is like a class but all methods are abstract
- 10Inheritance (more)- The 'sealed' keyword defines a class that cannot be inherited
- the 'new' keyword defines a method that hides the base-class version - 11Inheritance - Further terminologyEXAMPLE
- 'Book' can be referred to as a child of 'Product'
- Conversely, Product is the parent of Book
- Product is also known as the base class - 12Polymorphism (Definition)Polymorphism is a feature that allows values of different data types to be handled using a uniform way
- Applies to both datatypes and functions
- Data type == classes
- Functions == methods - 13PolymorphismPolymorphism in objected oriented programming goes deeper than method calls
- It goes to the very objects themselves
Sometimes called the third pillar to Object-Orientation
- After encapsulation and inheritance - 14Polymorphism at the Object LevelBase classes may define and implement virtual methods and derived classes can override them, which means they provide their own definition and implementation. At run-time, when client code calls the method, the CLR looks up the run-time type of the object and invokes that override of the virtual method. Thus in your source code you can call a method on a base class, and cause a derived class's version of the method to be executed
- 15Polymorphism (Summary)- Applies to functions and data-types
- Which equates to methods and objects in C# parlance
=To Understand polymorphic methods
- Think in terms of method signatures
=To understand polymorphic objects:
- Think in terms of casting and whether a method is virtual or new
- With polymorphic objects your program operates with both a Compile-time Type and Run-time type:
--A x = new C()
-- Compiler uses A to decide what methods can be called
--At run-time C is used to decide which version of a method is used - 16Problem Solving with Recursion (Divide and Conquer)Divide and conquer:
- An important algorithm design paradigm
- Works by breaking down a problem into two or more sub-problems of the same (or related) type....
- ...until these become simple enough to be solved directly
- The solutions to the sub-problems are then combined to give a solution to the original problem - 17How divide and conquer works.....A divide and conquer algorithm works by recursively breaking down a problem into two or more sub-problems of the same (or related type, until these become simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem.
- 18RecursionRecursion is a very powerful construct in programming: It can lead to elegant solutions that are easier to code than their iterative counterparts
- which in turn can result in more efficient code
- But there's no such thing as a free lunch...
- Recursion requires a little more thinking
- OK, recursion requires a lot more thinking about
- But the payoff is worth it - 19Recursion (Examples)- Factorial of N
- Fibonacci Number of N
- Graphics Flood-fill
- MergeSort.... and many more - 20Recursion (Approach)- Think of a way to divide the problem into smaller examples of the same problem....
- If a solution is a method then: one call to the method may call the method again for a smaller problem
--Base Case--solve a small (trivial) problem
--Recursive Case--solve a large problem on the assumption you can solve a smaller problem - 21Recursion (Example One: Factorial)- n! = n * (n-1) * (n-2) * ... 3 * 2 * 1
- write a method to compute factorial??
public int fact(int n)
{
if(n == 0)
{
return 1;
}
else
{
return n*fact(n - 1);
}
} - 22Recursion (Example Two: Fibonacci Numbers)The fibonacci series is given as follows:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Named after the turn of the 13th century italian mathematician, Leonardo Fibonacci of Pisa - 23Refactoring (Being Pragmatic)Programmers spend more of their time trying to understand existing code
In essence refactoring is :
- Improving the design after it has been written
- Acts as a counter-point to the software development mantra of design first then code - 24Refactoring (Definition)Refactoring is the process of changing a software system in such a way that it does not alter the external behaviour of the code yet improves its internal structure
- It is a disciplined way to clean up code that minimizes the chances of introducing bugs
- In essence when you refactor you are improving the design of the code after it has been written - 25Refactoring (More in detail)With refactoring you can take a bad design, chaos even, and rework it into a well-designed code. Each step is simple, even simplistic. You move a field from one class to another, pull some code out of a method to make into its own method, and push some code up or down a hierarchy. Yet the cumulative effect of these small changes can radically improve the design. It is the exact reverse of the normal notion of software decay.
- 26Refactoring (Key points)- Improve readability
- Improve maintainability
- Improve extensibility
- Reduce complexity - 27Refactoring in Visual Studio- Rename(variables, methods, classes, filename...
- Extract method
- Encapsulate Field
- Extract Interface
- Remove Parameters
- Reorder parameters
Tip: Best to apply these when there are no compile errors in your code
But as we shall see, refactoring is primarily a manually driven process, and the built-in tools only help so much - 28Refactoring (The need for testing)By its very definition, refactoring is about making changes to the code that do not affect how the code operates
Consequently, it is useful to combine refactoring with testing and in particular unit testing as a way to ensure things are still working as before - 29Testing: A software PerspectiveOften drawn from traditional engineering practices, there are many forms of software testing:
- Black-box testing
- White-box testing
- Unit Testing
- Integration Tesing
- Acceptance Testing - 30Software Testing:Things to note:
- Many different schools of thought prevail in this area
- Sometimes the coined phrase refers to:
-- the level or stage that testing occurs
-- other times the methodology or technique used to construct tests - 31Unit TestingThe core activity in Unit Testing is:
- Focus on the methods you just have written
- Think of each method's operation in isolation
- Write short sequences of code that test just one particular feature at a time
-- test its basic operation
-- test a boundary condition
Doesn't have to be methods you have already written, could be methods you are currently writing or even are away to write! - 32Unit Testing (in practice)Originally, developing such a series of tests, and bringing them together into a test suite was left to the programmer to initiate, develop and manage
-- from scratch
- Over time, API's have been developed to assist and guide programmers in developing tests of this form
- More recently, support for unit testing has been integrated into mainstream IDE's - 33Code ContractsCode contracts programmatically define how your software should behave, Specifically:
- What does it expect? (Pre-conditions)
- What does it guarantee? (Post-conditions)
- What does it maintain? (Invariants)
This can be used for:
- static checking and verification
- dynamic checking via generation
- runtime debugging by keeping the contracts in code during testing
Effectively the compiler uses the contracts to statically check if, at run-time, an error can occur!
In visual studio this capability is built upon a satisfiability Mudulo Theories (SMT) prover - 34Use full ContractsMethods start executing in some pre-state and end at in a post-state
- a method usually 'Requires' the pre-state to satisfy some condition in order that the method executes correctly
- Upon termination a method 'Ensures' the post state is related to the prestate in some way. - 35Contracts (Simple preconditions)Using System.Diagnostics.Contracts;
public string AddProduct(string name, string ID) {
Contract.Requires(name != null);
Contract.Requires(ID != null);
}
- Add Requires contracts to the start of the method
- defends your code from misuse
- allows tests to be automatically generated
var name = Console.ReadLine();
var ID = Console.ReadLine();
var y = AddProduct(name, ID);
- Error at compile time! - 36Contracts (Precondition - Custom Error Message)public double Divide(int number, int divisor) {
Contract.Requires(divisor != 0, "Divide by zero is not allowed.");
return number / divisor;
}
- Divide by 0 now throws an ArgumentOutOfRangeException with message
"Divide by zero is not allowed". - 37Contracts (Simple Postconditions)Using System.Diagnostics.Contracts;
public string AddProduct(string name, string ID) {
.....
Contract.Ensures(Product.lastID == Product.lastID + 1);
Contract.Ensures(Contract.Result().EndsWith(Product.lastID.ToString()));
- Add Ensures contracts at the end of the method
- These contracts ensure that
-- Product.lastID is incremented
-- The new Produce ID ends with Product.lastID - 38Class InvariantIf we require a condition to be true when ever the object is visible to a client
*
[ContractInvariantMethod]
private void ClassContract() {
Contract.Invariant(Y > X);
}
- This method consists only of a list of Contract.Invariants
- The compiler can check the condition is never violated - 39Black-Box TestingExamining the functionality of the programme and not its internal features and structures or workings
- 40Whitebox testingUsing specific knowledge of programming codes to examine outputs
- 41Code EliminationMacro - Huge amounts
Micro - Smaller amounts - 42Better ObjectsObjects:
- Good House Keeping!
- Worth taking the trouble to define:
-- Override ToString()
- Also good practice--particularly for fundamental classes to a project--to define
--Override Equals(Obj)
--Implement the operators ==, !=
--Override GeHashCode() - 43Better Objects (Objects as Reference or Value?)Determine whether it is more natural to copy or share data/information for a given situation
- 44Better Objects (Objects contain Code and Data)One Object can say Order may contain other objects, say Product, in a field.
- Now methods on the Product say ToString() can be called by the 'Order' object.
- Note how to print the product details only defined once---less code duplication easier to maintain! - 45Better Objects (Objects as first class citizens)- Objects can contain both data + code
- The value in a data field int x can be changed at run-time: x = 2;
- The code in a method is fixed at compile time. But parameters are fixed at run-time.
- Parameters can be Objects and hence contain code.
For example: one Sort method that sorts Products by name, another that sorts by ID, and another some as yet to be thought of criteria. - 46Better Objects (Formalized)Many (bespoke) ways to leverage from this core ability
- Often described in terms of Design Patterns
- We have already encountered some "Classic" forms:
-- Delegation
--Composition
--Aggregation
--Inheritance - 47DelegateUse delegates to "tease out" inner functional differences
- 48Composition- Use composition to assemble behaviours from other classes
- Composition is about ownership
- Pizza: composed of different ingredients that can be swapped and still be a pizza
- House - room
- In composition an object owns the behaviours of other objects and the behaviours are lost when the object is destroyed. - 49Aggregation- Composition without sudden death
- Course 204 - Student
- Aggregation - One class is used as part of another but its existence is not dependant on the using class
- In your software implementation you may shift your design from composition and aggregation (or vice versa) as you better understand the requirements of the problem you are solving
- ...or when the requirements change! - 50Octal (base 8)000 000 000
421 421 421 - 51Hexadecimal (Base 16)0000 0000
8421 8421
0123456789ABCDEF - 52Decimal (base 2)00000000
128 64 32 16 8 4 2 1 - 53Two's complimentif converting to Two's Compliment, simply negate the 0's and 1's then add one to the result
- 54Difference between Object and Class?Class is an abstraction and an object is an instance of the class
- 55Difference between Abstract Method and Virtual Method?Virtual Method can be overriden and also be defined in the base class. An abstract method contains no definition and all subclasses must implement it.
- 56Difference between read/write property and public class variable?The class variable is a field and the read/write property is property which can get and set the value . The class variable is declared directly in the class
- 57Difference between Local Variable and public class variable?The local variable is only available to the class whereas the public class variable is available to all classes
- 58Difference between value parameters and reference parameters?Reference parameters can change the value of the parameter whereas value parameters just pass the value.
- 59Difference between Interface and Class?With an interface all methods are abstract whereas a class they are not
- 60Difference between Throwing an Exception and Catching an Exception?Catch is done in the try catch structure and has pre-made error messages, throwing an exception you have your own exception and rules..
- 61Difference between Composition and Inheritance?Composition is about ownership, you use it to copy behaviours from other classes but not inherit them, Inheritance you inherit behaviours from other classes.
- 62Difference between whitebox and blackbox testing?Whitebox tests the running of the programme without looking at its internal structure, where blackbox looks at the internal structure
- 63Add 01011010 and 0101110010110110
- 64From Binary to CirtcuitsWe have already encountered the Boolean Mapping false or true and 1 respectively
It is also common to map these values to voltages, and design circuits that exhibit the same Boolean logic: for instance 0V is false and 5V for true
The exact voltage values are often abstracted away, and details expressed in terms of LOW and HIGH voltages mapped to false and true respectively
Also commonly abbreviated to L and H - 65Physical Digital CircuitsBut it's a messy world in reality
Microscopic amounts of time needed for a circuit to "change state"
Once particular integrated Circuit (IC) Technology chosen, fairly easy to abstract back to High & Low, true & False, 1 & 0
Informationen
- Beschreibung
- Karteikarten am Computer Science, erstellt von Cherese Eriepa am 26/10/2015.
- Erstellt von
- Cherese Eriepa · Okt 2015
- Aktualisiert
- 27 Jun 2016
- Aufrufe
- 1
- Bewertung