Introduction to Lexical Analyzer November 21, 2009
Posted by ZiKaS in Compilers Theory.add a comment
- Lexical Analyzer:

- Scanning consists of the simple processes that do not require tokenization of the input, such as deletion of comments and compaction of consecutive whitespace characters into one
-
Token is a pair consisting of a token name (boldface) and an optional attribute value.
- The token name is an abstract symbol representing a kind of lexical unit (keyword or identifier…)
- The token name is an abstract symbol representing a kind of lexical unit (keyword or identifier…)
- Pattern is a description of the form that the lexemes of a token may take
- lexeme is a sequence of characters in the source program that matches the pattern for a token
-
Token Classes:
- Keyword
- Comparison
- Identifiers
- Constants
- Punctuation Symbol
- Keyword
- The simplest recovery strategy is “panic mode” recovery. We delete successive characters from the remaining input, until the lexical analyzer can find a well-formed token at the beginning of what input is left
-
Error Recovery Techniques:
- Delete one character from the remaining input
- Insert a missing character into the remaining input
- Replace a character by another character
- Transpose two adjacent characters
- Delete one character from the remaining input
-
Input Buffering:
- It’s the process of reading source code file
-
2 Pointers to the input maintained:
- Pointer LexemeBegin: marks the beginning of current lexeme
- Pointer Forward: scans until a pattern matched is found
- Pointer LexemeBegin: marks the beginning of current lexeme
-
Sentinel Char:
- Special character that marks the end of source program (i.e. eof)
- Special character that marks the end of source program (i.e. eof)
- It’s the process of reading source code file
- Alphabet: any finite set of symbols as letters, digits and punctuation
- String
Over Alphabet: finite sequence of symbols drawn from that alphabet
- Language: any countable set of string over some fixed alphabet
-
Regular Expressions Precedence:
- *, concatenation, |
- *, concatenation, |
- Extensions for Regular Expressions: ?, +, Character Classes []
Introduction to Compilers Theory November 21, 2009
Posted by ZiKaS in Compilers Theory.add a comment
- Compiler is a program that can read a program in one language – the source language – and translate it into an equivalent program in another language – the target language
- Interpreter directly executes source code operations on input supplied by user
- Compiler is faster but interpreter give better error diagnostics
- Hybrid Compiler:

Developing EXE File: 
Source program -> -> modified source program -> -> Target Assembly Program -> -> Relocatable Machine Code -> -> Target Machine Code
-
Structure of Compiler:
-
Analysis Part (Front End):
- Break up source program into consistent pieces
- Then, imposes a grammatical structure on them
- After that, it uses this structure to create an intermediate representation of the source program
- Here also we create symbol table
- Break up source program into consistent pieces
-
Synthesis Part (Back End):
- Constructs the desired target program from the intermediate representation and the information in the symbol table
- Constructs the desired target program from the intermediate representation and the information in the symbol table
-
- Compiler Phases:
-
Lexical Analysis:
- The lexical analyzer reads the stream of characters making up the source program and groups the characters into meaningful sequences called lexemes
- For each lexeme, the lexical analyzer produces as output a token of the form <Token Name-Value>
- The lexical analyzer reads the stream of characters making up the source program and groups the characters into meaningful sequences called lexemes
-
Syntax Analyzer (Parser):
- Creates a tree-like intermediate representation that depicts the grammatical structure of the token stream
- Creates a tree-like intermediate representation that depicts the grammatical structure of the token stream
-
Semantic Analyzer:
-
Check the source program for semantic consistency with the language definition
- Example: operator’s type checking
- Example: operator’s type checking
-
-
Intermediate Code Generator:
- Generates an explicit low-level or machine-like intermediate representation, which we can think of as a program for an abstract machine
-
Properties:
- Easy to produce
- Easy to translate into the target machine
- Easy to produce
- Generates an explicit low-level or machine-like intermediate representation, which we can think of as a program for an abstract machine
- Code Optimization:
-
Compiler Construction Tools:
- Parser Generator: requires grammatical description of the language
- Scanner Generator: requires RE description of the tokens of the language
-
Syntax Directed Translation Engine:
- Produce collections of routines for walking a parse tree and generating intermediate code
- Produce collections of routines for walking a parse tree and generating intermediate code
-
Code Generator Generators:
- Produce a code generator from a collection of rules for translating each operation of the intermediate language into the machine language for a target machine
- Produce a code generator from a collection of rules for translating each operation of the intermediate language into the machine language for a target machine
-
Data-Flow Analysis Engines:
- Facilitates the gathering of information about how values are transmitted from one part of a program to each other part. Data-flow analysis is a key part of code optimization
- Facilitates the gathering of information about how values are transmitted from one part of a program to each other part. Data-flow analysis is a key part of code optimization
-
Compiler-Construction Toolkits:
- Provides an integrated set of routines for constructing various phases of a compiler
- Provides an integrated set of routines for constructing various phases of a compiler
- Parser Generator: requires grammatical description of the language
- Finite-state machines and regular expressions models useful for describing the lexical units of programs (keywords, identifiers, ..) and for describing the algorithms used by the compiler to recognize those units
- Context-free grammars, used to describe the syntactic structure of programming languages such as the nesting of parentheses or control constructs
- Trees for representing the structure of programs and their translation into object code
-
Compiler optimizations must meet the following design objectives:
- The optimization must be correct, that is, preserve the meaning of the compiled program
- The optimization must improve the performance
- The compilation time must be kept reasonable
- The engineering effort required must be manageable
- The optimization must be correct, that is, preserve the meaning of the compiled program
- Data-flow optimizations, has been developed to analyze the flow of data through the program and removes redundancies across these constructs
-
Optimizations for Computer Architectures:
-
Parallelism
- Hardware scheduler can change the instruction ordering to increase the parallelism in the program
- Try to use the microprocessor mechanisms of parallelism (as processors able to work on vectors in parallel way)
- Hardware scheduler can change the instruction ordering to increase the parallelism in the program
-
Memory Hierarchies:
- It has been found that cache-management policies implemented by hardware are not effective in some cases, especially in scientific code that has large data structures
-
It is possible to improve the effectiveness of the memory hierarchy
- Changing the layout of the data
- Change the layout of code
- Changing the order of instructions accessing the data
- Changing the layout of the data
- It has been found that cache-management policies implemented by hardware are not effective in some cases, especially in scientific code that has large data structures
-
-
Program Translations:
- Binary Translation
- Hardware Synthesis
- Database Query Interpreters
- Compiled Simulation
- Binary Translation
Basic Pattern Definitions November 21, 2009
Posted by ZiKaS in Pattern Classification.add a comment
- Model: is anything that has specific descriptions in mathematical form.
- Preprocessing: operation of simplifying subsequent operations without losing relative information.
- Segmentation: operation of isolating image objects from background.
- Feature space: space containing all pattern features.
- Feature vector is a vector from feature space that contains the actual values of current model.
- Feature Extraction: operation of reducing the data by measuring certain features or properties.
- Training Samples: samples used to extract some information about domain of problem.
- Decision Theory: theory of making a decision rule in order to minimize cost.
- Decision Boundary: a boundary that distinguishes classes decision regions.
- Novel Patterns: patterns that were not included in the training samples.
- Generalization: classifier ability to classify novel patterns in right class.
- Analysis by Synthesis: technique used to resolve problem of insufficient training data by having a model of how each pattern was produced.
- Image Processing: techniques to process images for enhancements and other purposes.
- Associative Memory: technique used to discover representative features of a group of patterns.
- Regression: area of finding some functional description of data in order to predict new value.
- Interpolation: area of inferring the function for intermediate ranges of input.
- Density Estimation: the problem of estimating the density (probability) that a member of a certain category will be found to have particular features.
- Pattern Recognition System:

- Mereology: is the study of part/whole relationships in order to make the classifier categorize inputs as “make sense” rather than matching but not too much.
- Invariant (distinguishing) Feature: features that are invariant to irrelevant transformations of the input
- Occlusion: concept of hiding part of an object by other part
- Feature Selection: operation of selecting most valuable features from a larger set of candidate features
- Noise: any property of the sensed pattern which is not duo to the underlying model but instead to randomness in the world or the sensors
- Error Rate: percentage of new patterns that are assigned to the wrong category
- Risk (Conditional Risk): total expected cost
- Evidence pooling, idea about having several classifiers used to categorize one sample. Here how can we resolve the problem of disagreeing classifying?
- Multiple Classifier: multiple classifiers working on different aspects of the input
- Design of Classification System:

- Overfitting: situation where the classifier is tuned on training samples and is unable to classify novel pattern correctly.
- Supervised Learning: learning technique where a teacher provides a category label or cost for each pattern in training set.
- Unsupervised Learning (Clustering): learning technique where the system itself makes “natural groupings” of input patterns.
- Reinforcement Learning: Calculating a tentative value for each category label to improve classification.
Chapter # 2
- State of Nature: class that the current sample belongs to.
- Prior: probability that the next sample will belongs to a specific class.
- Decision Rule: rule that decides for which class the current sample belongs to.
- Posterior: the probability of the state if nature being belongs to a specific class given that feature value x has been measured.
- Evidence Factor: scaling factor that guarantees that the posterior probabilities sum to one
- Loss Function: function that states how costly each action is, and is used to convert a probability determination into a decision.
- Bayes Risk: minimum overall risk
- Zero-One (symmetrical) Loss: loss function where each action is assigned to its category (i=j)
- Decision Region: region for each class on the histogram
- Dichotomizer: classifier that places a pattern in one of only two categories
- Polychtomizer: classifier that places a pattern in more than two categories
- Linear Discriminate Function: a linear function that is able to discriminate classes on the histogram
- Template Matching: assigning x to the nearest mean
Introduction to Communication Network and Internet November 21, 2009
Posted by ZiKaS in Data and Computer Communication.add a comment
- Data communication deals with the transmission of signals in a reliable and efficient manner.
-
Data Communication Study Area:
- Signal transmission
- Transmission media
- Signal encoding
- Interfacing
- Data link control
- Multiplexing
Data Communication and Networking for Today’s Enterprise
-
There are three different forces that driven the architecture and evolution of data communication:
- Traffic growth: seeking for maximizing transmission capacity and minimizing costs
- Development of new services
- Advances in technology: advanced in technology that should support growth of traffic an services
-
Technology Trends in Data Communication and Networking:
- Faster and cheaper in computing and communication
-
Voice-Oriented telecommunications networks (such as PSTN and data networks) are more intelligent
-
The intelligence appears in two areas:
- Offers of different QoS. As specifications for maximum delay, minimum throughput…
- Supports variety of customization services in the areas of network management and security
-
- Internet, web and associated applications have emerged as dominant features of business and personal world
- Increasing mobility for librating workers. Which results in voice mail, remote data access …
-
Requirements for High-Speed LANs:
- Centralized Server Farms: ability to centralize data for multiuser access
- Power Workgroup: ability to send large amounts of data
- High-Speed Backbone: ability for high transferring speed
- Fundamental purpose of a communication system is the exchange of data between two parties

Simple Model of Communication
-
Key Tasks in Data Communication System:
-
Utilization of Transmission System:
- Need for efficient utilization of transmission facilities shared among communication devices
-
Used Techniques:
-
Multiplexing:
- Techniques
used to allocate the total capacity of a transmission medium among several users
- Techniques
-
Congestion Control:
- Techniques used to assure that the system is not overwhelmed by excessive demands for transmission services
-
-
Interface; point of connection between devices:
-
Mechanical Characteristics: Shape, # of pins …
-
Electrical Characteristics: values of volts …
-
Functional Characteristics: function (task) of the pin
-
Procedural Characteristics: the set and sequence of function to do a specific task (i.e. printing)
-
-
Signal Generation:
-
Responsible for generating signals. Here are signal characteristics:
-
Signal should be capable of being propagated through transmission system
-
Signals should be interpretable as data at the receiver
-
-
-
Synchronization:
-
Receiver must be able to determine the beginning and duration of each signal element
-
-
Exchange Management
-
If data are to be exchanged in both directions over a period of time, the two parties must cooperate
-
-
Error Detection and Correction:
-
Duo to non-perfect medium, a signal may be destroyed during transmission, So there must be a mechanism of detecting and correcting destroyed signals
-
-
Flow Control:
-
A receiver has limited resources (as buffers), so there must be some source control on the transmission so that the receiver buffers are not flooded
-
-
Addressing and Routing:
-
Using protocols. A protocol is grading rules to do a specific task
-
Each device must be assigned a unique identifier in the network to enable data transmission
-
-
Recovery:
-
The network must be able to recover from any failure duo to overload or other cases. No loss of data should occur
-
-
Message Formatting:
-
There should be a pre-specific format for messages that are transmitted over networks that’s defined by the communication protocol
-
Pre-specific pattern of signals must be exist between transmitter and receiver
-
-
Security:
-
Sender may wish to assure that only intended receiver received. A received wish to ensure that the received data has not been altered in transit
-
-
Network Management:
-
How to configure systems.
-
How to react to failure.
- How to plan for future scalability.
-
-
- The building block of any communications facility is the transmission line.
- The common communication mediums are fiber optic and wireless transmission.
-
Wireless transmission provides two important concepts:
-
Universal personal telecommunication:
- Ability of a person to identify himself easily and to use conveniently any communication system in a large area in terms of a single account.
-
Universal Access to Communications:
- Capability of using the same terminal in multiple environments to connect to information services
-
- Transmission services remain the most costly component of a communication budget
-
There are 2 common techniques used to increase the efficiency of transmission services:
- Multiplexing: ability of a number of devices to share a transmission facility
- Compression: ability to squeeze data down in order to get lower capacity, cheaper transmission facility
- Most commonly used transmission media are twisted-pair lines, coaxial cable, fiber cable, and terrestrial and satellite microwave.
- Error rate depends on signal and medium type to be used.
-
Multiplexing Techniques:
- Frequency division
- Synchronous time division
- Statistical time division
Networks
- Integration means that the customer equipment and networks can deal simultaneously with voice, data, image and even video
- Network Types: WAN, LAN and Wireless
-
WAN Implementation Techniques:
-
Circuit Switching:
- Here a dedicated communication path is established between two stations through network nodes
- Example: telephone network
-
Packet Switching:
- There’s no dedicated network path. Data are sent out in sequence of small chunks called packets
- This technique is commonly used for terminal-to-computer and computer-to-computer communications
-
Frame Relay:
- Reducing size of packets because the advance in the communication technologies that leads to low error rate
- Packet switching was designed for users with 64 kbps whereas frame relay designed for up to 2 Mbps
-
Asynchronous Transfer Mode (ATM) – Cell Relay Mode:
- Frame relay uses variable frame lengths whereas ATM used fixed frame length. This fixed frame called cell
- This technique is designed to work in range 10s and 100s of Mbps and in Gbps range
-
-
Differences between WAN and LAN:
- LAN scope is smaller than WAN scope
-
Usually LAN is owned by an organization. This leads to:
- Care when choosing LAN because there may be substation investment for purchasing and maintenance.
- Network management responsibility for a LAN falls solely on the user
- Internet data rates of LAN are much greater than WAN
- LAN scope is smaller than WAN scope
-
LAN Types:
-
Switched LAN:
- Switched Ethernet: consists of a single switch with a number of attached devices or number of interconnected switched
- Wireless LAN
- ATM LAN
- Fiber Channel
-
The Internet
- Purpose of the internet is to interconnect end systems called hosts
- IP datagrams (IP packets) beaked data from source that will be sent over network
- Central Office
the place where telephone companies terminate customer lines and locate switching equipment to interconnect those lines with other networks - Customer Premises Equipment (CPE): telecommunications equipment that is located on the customers physical location rather than on the providers physical location or in between
- Internet Service Provider (ISP): company that provides other companies or individuals with access to the internet
- Network Access Point (NAP): technique that is used to tie all ISPs together
- Network Service Provider(NSP): company that provides backbone service to ISP
- Point of Presences (POP): site that has a collection of telecommunication equipment usually refers to ISP or telephone company sites. An ISP POP is the edge of the ISP’s network; connections from users are accepted and authenticated here
Introduction to Pattern Recognition October 15, 2009
Posted by ZiKaS in Pattern Classification.add a comment
- Model is anything that have specific descriptions in mathematical form
- Segmentation is an operation to isolate objects from each other in images
- If we think in business wise, you can ignore errors that are acceptable by customers (Salmon, Sea-Bass Example)
- Decision theory is concerned with which pattern classification is perhaps the most important subfield
- Feature vector is a vector from feature space that contains the actual values of current model
- When selecting features in feature vector don’t choose redundant features
- Though, our satisfaction would be premature because the central aim of designing a classifier is to suggest actions when presented with novel patterns. This is the issue of generalization
- Sometimes classifier is tuned of the training samples, here one solution is to support the classifier with more training samples for obtaining a better estimate
- Complex classifiers could be simplified if the process doesn’t require this level of complexity
- Assuming that we somehow manage to optimize this trade off, can we then predict how well our system will generalize to new patterns? These are some of the central problems in statistical pattern recognition
- (“Entities are not to be multiplied without necessity”). Decisions based on overly complex models often lead to lower accuracy of the classifier
- There is no GPS (Simpson, Newell device). We conclude here that there’s no GPS
-
Each recognition technique is suitable for a specific domain of problem:
- Patterns that have statistical properties are more suitable using statistical pattern recognition
- Patterns with noise are more suitable for neural network pattern recognition
- If the model consists of some set of crisp logical rules, then we employ the methods of syntactic pattern recognition
- Patterns that have statistical properties are more suitable using statistical pattern recognition
-
A central aspect in PR problem is to achieve good representation
- Features of each sample are close to its category
- Simplify number of features
- Robust features: relatively insensitive to noise or other errors
- In practical applications we may need the classifier to act quickly, or use few electronic components, memory or processing steps
- Features of each sample are close to its category
- A central technique, when we have insufficient training data, is to incorporate knowledge of the problem domain. Indeed the less the training data the more important is such knowledge (analysis by synthesis)
- What about classifying patterns on depending on their functions (chair example)
- In acts of associative memory, the system takes in a pattern and emits another pattern which is representative of a general group of patterns.
Sub Problems of Pattern Recognition
- an ideal feature extractor would yield a representation that makes the job ofthe classifier trivial
- How do we know which features are most promising? Are there ways to automatically learn which features are best for the classifier? How many shall we use?
- We define noise very general terms: any property of the sensed pattern due not to the true underlying model but instead to randomness in the world or the sensors
- While an overly complex model may allow perfect classification of the training samples, it is unlikely to give good classification of novel patterns — a situation known as overfitting
- One ofthe most important areas ofresearch in statistical pattern classification is determining how to adjust the complexity ofthe model — not so simple that it cannot explain the differences between the categories, yet not so complex as to give poor classification on novel patterns
- model selection is concerned with how are we to know to reject a class of models and try another one
- How can we make model selection automated?
- Prior knowledge is pre knowledge about the problem helps is classification
- Occlusion!
- How should we train a classifier or use one when some features are missing?
- This is the problem of subsets and supersets — formally part of mereology, the study of part/whole relationships. It is closely related to that of prior knowledge and segmentation. In short, how do we recognize or group together the “proper” number of elements — neither too few nor too many
- In invariation, Thus here we try to build a classifier that is invariant to transformations such as rotation
- How might we insure that our pattern recognizer is invariant to such complex changes?
-
Evidence pooling, idea about having several classifiers used to categorize one sample. Here how can we resolve the problem of disagreeing classifying?
- How should a “super” classifier pool the evidence from the component recognizers to achieve the best decision?
- How should a “super” classifier pool the evidence from the component recognizers to achieve the best decision?
-
Costs and Risks
- How do we incorporate knowledge about such risks and how will they affect our classification decision?
- Can we estimate the total risk and thus tell whether our classifier is acceptable even before we field it?
- How do we incorporate knowledge about such risks and how will they affect our classification decision?
-
Computations Complexity:
- What is the tradeoff between computational ease and performance?
- How can we optimize within such constraints?
- What is the tradeoff between computational ease and performance?
- Throughout this book, we shall see again and again how methods of learning relate to these central problems, and are essential in the building of classifiers.
Learning and Adaptation
- Learning refers to some form of algorithm for reducing the error on a set of training data
-
Learning Forms:
-
Supervised Learning:
- How can we be sure that a particular learning algorithm is powerful enough to learn the solution to a given problem and that it will be stable to parameter variations?
- How can we insure that the learning algorithm appropriately favors “simple” solutions rather than complicated ones
- How can we be sure that a particular learning algorithm is powerful enough to learn the solution to a given problem and that it will be stable to parameter variations?
-
Unsupervised Learning (Clustering):
- System forms clusters or “natural groupings” of the input patterns
- System forms clusters or “natural groupings” of the input patterns
-
Reinforcement Learning (learning with a critic):
- This is analogous to a critic who merely states that something is right or wrong, but does not say specifically how it is wrong
- This is analogous to a critic who merely states that something is right or wrong, but does not say specifically how it is wrong
-
- Team reading: Summary of chapters
-
Questions:
- What’s Hypothesis testing
Introducing Book October 12, 2009
Posted by ZiKaS in Pattern Classification.add a comment
Posts in this category will be mainly quoted from Pattern Classification
UML Diagrams of BosWars October 12, 2009
Posted by ZiKaS in Graduation Project.add a comment
Hello all,
Find in the following posts some of BosWars UML Diagrams:
OO Analysis and Design Tips September 25, 2009
Posted by ZiKaS in Software Engineering Design Patterns.add a comment
- General overview
-
Meaning of great software:
- First, develop software that the customer needs and satisfy requirements
-
Second, apply basic OO principles to add flexibility (OOD)
- Like duplicate code
- Bad class design
- Like duplicate code
- Third, strive for maintainable, reusable design (DP)
- First, develop software that the customer needs and satisfy requirements
-
Object Characteristics:
- Objects should do what their names indicate: if I’m a plan I shouldn’t contain method GetTicket
- Each object should represent a single concept: like ball! This could be basketball of football
-
Unused properties are dead giveaway:
- If you have a field that is rarely has values. Why this property is a part from this object?
- If you have a field that is rarely has values. Why this property is a part from this object?
- Objects should do what their names indicate: if I’m a plan I shouldn’t contain method GetTicket
-
OOD:
- Keep your objects well encapsulated
- Keep your objects well encapsulated
-
Design Pattern:
- When try to edit your code you should modify the min number of classes
- With min number of code lines!
-
Explain the principle Loosely Coupled Objects:
- Separation of objects jobs so each one do its task separately and independently
- Separation of objects jobs so each one do its task separately and independently
- When try to edit your code you should modify the min number of classes
-
Customers/Programmer Golden Rules:
- Customers are satisfied when their apps work
- Customers are satisfied when their apps keep working
- Customers are satisfied when their apps upgraded
-
Programmers are satisfied when their apps reused
- (Open-Closed-Principle (OCP) & Single-Responsibility-Principle (SRP))
- (Open-Closed-Principle (OCP) & Single-Responsibility-Principle (SRP))
- Programmers are satisfied when their apps flexible -> Software Architects
- Customers are satisfied when their apps work
-
Notes:
- Encapsulation is breaking your application is logical parts
- Find parts that could change and separate them from the stable parts
- Encapsulation is breaking your application is logical parts
- Gathering Requirements
-
What exactly is a requirement?
- It’s a specific thing your system has to do to work correctly
- It’s a specific thing your system has to do to work correctly
-
When you are coming to requirements best thing to do is “let the customer talk”
- Take care of what the system should do rather than how to do it
- Take care of what the system should do rather than how to do it
- Make sure that the system could work although unexpected errors appear
- After understanding the system and determine requirements, think under negative thinking
- What is Main path and alternative path? What are the differences bettween them?
-
Requirements Should meet:
- Ensure that the system works like customer expect
- Covers all steps in the use cases
- Use your use cases to recover point ur customers didn’t tell you
- Ensure that the system works like customer expect
-
Characteristics of good use case:
- Starting Condition
- Stopping Condition
- External Initiator
- Clear Value
- Starting Condition
-
Chapter # 3:
- Rules # 1: The customer is always right: D
-
Chapter keywords:
- Scenario
- Scenario
- Rules # 1: The customer is always right: D
-
Chapter # 4:
- Your software should work in real world not perfect world
- Analysis helps you ensure your system works in a real world context
-
Analysis Steps:
- Identify the problem
- Plan a solution
- Identify the problem
- Delegation shields your objects from implementation changes to other objects in your software
-
Textual Analysis:
- Looking at the nouns ( and verbs) in your use case to figure out classes and methods
- Looking at the nouns ( and verbs) in your use case to figure out classes and methods
- Verbs in the use case are usually methods inside classes
-
Keywords:
- Real-world context, peal-world context, Textual Analysis, Association
- Real-world context, peal-world context, Textual Analysis, Association
- Your software should work in real world not perfect world
-
Chapter # 5:
- Good design = flexible software
- Keywords: Abstract Class, concrete, generalization, aggregation
- Rule: Always favor coding to the interface not the implementation
- Using a Map Data Structure to store variable properties
- cohesive class: class that does one thing really well and doesn’t try to do or be something else
- Keywords: cohesive class
- Good design = flexible software
-
Chapter # 7:
- Commonality
- Variability
- Commonality
-
OO Tips:
- Avoid duplicate code
-
Objects should be loosely coupled:
- objects are independent on each other
- Change of an object doesn’t require bench of changes to other objects!
- objects are independent on each other
- Classes shouldn’t store living things unless the system is going to store long-term information about them
-
Class Diagram Helps:
- If there’s a mistake you can figure out it before writing actual code and fix it in the drawing
- If there’s a mistake you can figure out it before writing actual code and fix it in the drawing
- Using a Map Data Structure to store variable properties
- Most good designs come from analysis of bad designs
- It’s not recommended to add a new class with a constructor only!
-
To test your software flexibility:
- How many classes did you have to add?
- How many classes did you have to change?
- How many classes did you have to add?
- Avoid duplicate code
-
OO Principles:
- Encapsulate what varies
- Always favor coding to the interface not the implementation
- Each class has one responsibility
- Encapsulate what varies
The more cohesive your software is, looser the coupling between classes
MACROS September 25, 2009
Posted by ZiKaS in C++.2 comments
What is a macro?
Let us start with a somewhat simple-minded example of a macro (not to be emulated in any real project):
#define SquareOf(x) x*x
It defines a kind of function which, used in an actual piece of code, looks exactly like any other function call:
double yout,xin=3;
yout = SquareOf(xin);
As we shall see in a moment, the problem is that SquareOf only pretends to be a function call, while it is really something completely different.
The formal syntax of a macro is:
#define name(dummy1[,dummy2][,...]) tokenstring
The symbols dummy1, dummy2, … are called dummy arguments (as usual, square brackets indicate optional items). There are a few additional rules such as that the macro can extend over several lines, provided one uses a backslash to indicate line continuation:
#define ThirdPowerOf(dummy_argument) \
dummy_argument \
*dummy_argument \
*dummy_argument
How does a compiler handle a macro?
What makes a macro different from a standard function is primarily the fact that a macro is a scripted directive for the compiler (rather than a scripted piece of run-time code) and therefore it gets handled and done with at compilation time rather than at run time.
When the compiler encounters a previously defined macro, it first isolates its actual arguments, handling them as plain text strings separated by commas. It then parses the tokenstring, isolates all occurrences of each dummy-argument symbol and replaces it by the actual argument string. The whole process consists entirely of mechanical string substitutions with almost no semantic testing!
The compiler then substitutes the modified tokenstring for the original macro call and compiles the resulting code script. It is only in that phase that compilation errors can occur. When they do, the result is often either amusing or frustrating, depending upon how you feel at the moment. You are getting mysteriously looking error messages resulting from the modified text and thus referring to something you have never written!
Example 1:
#define SquareOf(x) x*x
void main() {
int Test = 3;
cout << Test << endl;
cout << SquareOf(Test) << endl;
cout << SquareOf(Test + 4) << endl;
cout << SquareOf(Test + Test) << endl;
}
Intuitively, you probably expect the output of this program to be:
3
9
49
36
What you actually get, however, is this:
3
9
19
15
Before you conclude that computers are stupid and become a farmer, consider what has happened. When the compiler met the string “SquareOf(x+4)”, it replaced it with the string “x*x” and then replaced each of the dummy-argument-strings “x” by the actual-argument-string “x+4″, obtaining the final string “x + 4*x + 4″ which, in fact, evaluates to 18 and not to the expected 49. Likewise, it is now easy to work out the case of SquareOf(x + x) and understand why and how the result differs from the expected one.
The problem would have never happened if SquareOf(x) were a normal function. In that case, in fact, the argument xin+4 would be first evaluated as a self-standing expression and only then would the result be passed to the function SquareOf for the evaluation of the square.
Actually, none of the two ways is wrong. They are just two different recipes on how to handle the respective scripts. Given the formal similarity between the macro function call to a standard function call, however, the discrepancy is dangerous and should be removed. Fortunately, there is a simple way to do so. Replacing the original definition of the SquareOf macro by
#define SquareOf(x) (x)*(x)
the problem vanishes because, for example, the macro-call string “SquareOf(x+4)” is transformed into “(x)*(x)” and then into “(x+4)*(x+4)” which evaluates exactly as intended.
Example 2:
#define Sum(x, y) (x) + (y);
void main() {
int x = 20;
int y = 15;
int sum = Sum(x, y);
cout << sum << endl;
}
Output:
35
Example 3:
Macro can be expression
#define IsXGreaterThanY(x, y) {if ((x) > (y)) (x) = (y);}
void main() {
int x = 20;
int y = 15;
IsXGreaterThanY(x, y);
cout << x << endl;
cout << y << endl;
}
Output:
15
15
References:
http://www.ebyte.it/library/codesnippets/WritingCppMacros.html#2
Introduction To My Graduation Project September 25, 2009
Posted by ZiKaS in Graduation Project.add a comment