Building Medium Size Projects' - PowerPoint PPT Presentation

1 / 47
About This Presentation
Title:

Building Medium Size Projects'

Description:

'Early optimization is the root of all evil.' Quote from Henessy and Patterson. ... the evils of early optimization. Understand Exceptions ... – PowerPoint PPT presentation

Number of Views:229
Avg rating:3.0/5.0
Slides: 48
Provided by: srilekhas
Category:

less

Transcript and Presenter's Notes

Title: Building Medium Size Projects'


1
Building Medium Size Projects.
  • Some Fundamentals and Principles.
  • By
  • Abdelilah Essiari

2
Conventions
  • Must agree on a set of conventions.
  • consistent gt professional gt good first
    impression
  • consistent gt predictability gt saving time
  • Examples
  • void addElementAt(Object element, int index)
  • Class names start with upper case
  • Function names start with lower case
  • Use of the this operator (this.arg arg) in a
    set method.

3
Languages
  • Choose a language. (Java/C/C/Python)
  • Prefer Object Oriented Language
  • Inheritance, Encapsulation, Polymorphism
  • Prefer safe languages.
  • Buffer overflows.
  • Automatic initialization.
  • Prefer static-typed languages
  • Help from the compiler

4
Languages
  • Objectives are the same.
  • Robustness
  • Small code size
  • Efficiency
  • Elegance
  • Easy to maintain/extend
  • Portability
  • It is the how that changes.

5
Languages
  • Know the weaknesses.
  • Know the strengths.
  • Dont push it.
  • Do unnatural things.
  • Not all features are good.

6
Walk before you run
  • Quote from Knuth.
  • Early optimization is the root of all evil.
  • Quote from Henessy and Patterson.
  • A program executes 90 percent of its
    instructions in 10 percent of its code.

7
WE DO NOT LIKE
  • Global variables/functions
  • Long methods and large classes.
  • Long parameter lists.
  • Code duplication.
  • Side effects.
  • Dependencies.

8
Global Variables/functions
  • Hard to find.
  • Polluting the global name space.
  • Rigid.
  • Use the Singleton pattern or a utility class.

9
How Java deals with system wide constants
  • void foo() Properties props
    System.getProperties()
  • String ssl props.getProperty(SSL,
    OFF)

  • if (ssl.equals(ON))
  • else

10
Long Parameter Lists
  • Do not pass in every thing the method needs.
  • Try passing enough so that the method can get to
    everything it needs.
  • As a last resort, use a Parameter Object.

11
Side effects
  • Avoid modifying global variables after they have
    been initialized. (READ ONLY)
  • Reduce number of functions that modify member
    variables inside a class, ideally to constructors
    and set methods.
  • Helper functions that do not modify member
    variables can be moved and tested more easily.

12
Dependencies
  • Design by Interfaces.
  • Construction Patterns. (Virtual Constructors,
    Factories)
  • Opaque pointers and forward declarations.
  • // The header file below has no need to
    include anything
  • class A // Forward declaration
  • class B // Forward declaration
  • class X
  • public
  • void f(const A a)
  • void g(B b) doIt(b) //
    Interesting
  • private
  • class Ximpl // Forward
    declaration
  • Ximpl impl

13
Do Not Remember What You Can Compute
  • Calling a simple getMethod()
  • I have an object x, its brother, and its cousin.
  • Calling a more involved function
  • I need x, y, xy, xy, x x,
  • This tends to make your classes have too many
    member variables. If your intent is
  • caching for efficiencys case, remember
  • the evils of early optimization.

14
Understand Exceptions
  • All modern languages have exception handling
    mechanisms.
  • Why Exceptions?
  • Programmers tend to ignore error codes.
  • Voluminous error handling code obscures the
    functional code
  • Constructors do not have return values

15
Understand Exceptions
  • Exceptions vs. Errors
  • Errors indicate bugs in the code.
  • Exceptions indicate errors by events external to
  • the code.
  • In java
  • Checked Exceptions. (External events)
  • Runtime Exceptions. (Programming bugs)
  • Errors (virtual machine bugs)
  • Java forces programmers to catch checked
    exceptions.

16
When to Catch Exceptions
  • Catch at the point closest to the occurrence of
    the exception that allows execution to proceed in
    a stable way.
  • You can catch and rethrow in order to
  • convert exceptions.
  • log major events in the system.

17
A function that makes debugging hard
  • X createX(int arg1, A arg2, C arg3)
  • // This function does not throw
  • X x createX(arg1, arg2, arg3)
  • if (x NULL)
  • // Dont have a clue what happened

18
A very suspicious function
  • void doSomething() try
  • catch(Exception ex)
  • System.out.print( Is anyone
    watching the screen?)
  • return

19
Plan ahead
  • void doSomething(SomeObject obj) try
  • .
  • catch(SomeCheckedException ex)
  • // should never happen, I have
    analyzed the situation blah blah
  • What if the programmer miscalculated? Or
    maybe things have
  • changed. I know print something. NO!
  • How about throwing IllegalStateException(S
    URPRISE SUPRISE)

20
Planning for the future
  • A good Java Function.
  • void doSomething(SomeObject obj)
    switch(obj.getState()) case RUNNING
  • break case SUSPENDED
  • break
  • default
  • throw new IllegalStateException()

21
Try HARD not to do the following
  • Throw a checked exception when it is a runtime
    exception.
  • Throw a runtime exception when it is a checked
    exception.
  • Catch an exception and sit quietly on it.

22
Report Errors Immediately
  • void setHandler(Handler handler)
    this.handler handler
  • // bad unless handler is optional.
  • void setHandler(Handler handler)
    if (handler null) throw new
    IllegalArgumentException()

23
Signal intent/Prevent abuse
  • access modifiers (public/private/protected)
  • const
  • enumerations
  • passing by reference (C)
  • final in Java and virtual destructors in C
  • namespaces in C
  • packages in Java
  • friend in C

24
Signal intent/Prevent abuse
  • Class X // Pointers
  • public
  • constY foo(const A a, const B b) const //
    b can be null
  • Class X // References
  • public
  • const Y foo(const Aa) const
  • const Y foo(const A a, const B b) const

25
Signal intent/Prevent abuse
  • NEVER make member variables public.
  • Do not pollute the public interface of an object
    with helper functions. Hide them.
  • Protected member variables break encapsulation.
  • Try Factory methods.
  • Try protected get methods.

26
Prevent abuse
  • Encapsulation in C.
  • Hide the structures and provide clients
  • with the interface.
  • Header file (.h) contains forward
    declarations
  • and prototypes.
  • Source file (.c) contains structure and
    function definitions.
  • Forced to write init, free, getters, setters,
    copy.

27
Prevent abuse
  • Immutable objects (Java)
  • You do this by not providing public modifying
    methods such as set methods.
  • You can do this dynamically by using the Proxy
    pattern.
  • Collection getWidgets()
  • return Collections.unmodifiabl
    eCollection(myPreciousCollection)
  • Cool if one tries to modify my precious
    collection, he will get an UnsupportedOperation
    Exception.

28
Prevent abuse
  • Smart pointers in C
  • A proxy that holds a raw pointer.
  • Used for memory management.
  • They can make the difference between a
    successful project and a failure
  • Essential ingredient of successful, robust
    applications

29
Smart Pointers
  • void foo() A a new A()
  • a-gtf()
  • a-gtg()
  • delete(a) // Hope this line is
    executed. (Optimistic)
  • void foo() // a will always be
    deleted.
  • SmartPtrltAgt a new A()
  • a-gtf()
  • a-gtg()

30
Smart Objects behave like ints
  • // internal class
  • class Ximpl
  • public
  • void f()
  • private
  • // member variables
  • // Exposed to clients.
  • class X
  • public
  • void f() impl-gtf()
  • private
  • SmartPtrltXimplgt impl
  • Usage X x // x is a smart
  • x.f() // object

31
Summary
  • Classes exposed to clients should be immune to
    abuse.
  • Good error reporting.
  • Give reasonable default values.
  • Provide a builder for complex objects

32
Summary
  • Avoid the not to do list.
  • Consistency
  • Remember that the complexity of a piece of code
    should not be greater than the complexity of the
    problem that it is solving.

33
DSDS SHARED C LIBRARY
  • Support for linux, solaris, FreeBsd, andWindows
  • Threads/Synchronization
  • Sockets/ServerSockets
  • URL/URLConnections (file, http, https)
  • Security Wrappers around openssl C library
  • Properties, StringTokenizer, File,, etc

34
DSDS SHARED C LIBRARY
  • Use the Standard C library.
  • Emphasis on Design and Robustness.
  • Provide clients with easy to use smart objects.
  • No pointers
  • No need to use the or the -gt
  • Good Error reporting
  • No need for memory management/resource
  • management

35
Threads
  • Thread.start()
  • Thread.join()
  • Thread.getId()
  • Thread cur ThreadgetCurrentThread()
  • Thread objects are smart Objects

36
Threads
  • class MyCommand public Runnable
  • public
  • void run()
  • cur ThreadgetCurrentThread()
  • private
  • Thread cur
  • void foo()
  • Thread t new Thread(new MyCommand)
  • t-gtstart()
  • delete(t)
  • void foo()
  • Command command(new MyCommand)
  • Thread t(command)
  • t.start()

37
Socket/ServerSocket
  • SocketImpl connect, getInputStream,
    getOutputStream,
  • bind, listen, accept
  • Socket connect. getInputStream,
    getOutputStream
  • ServerSocket bind, listen, accept)
  • SSLSocket extends Socket
  • SSLSocketImpl extends SocketImpl
  • Socket s
  • SSLSocket secureSocket (SSLSocket) s
  • We will not be denied. ?

38
Mutexes.
  • Mutexes and Recursive mutexes.
  • class MyObject
  • public
  • void f()
  • mutex.lock()
  • mutex.unlock()
  • void g() SmartMutex
    sm(mutex)
  • private
  • Mutex mutex

39
Conditions
  • Condition cond
  • cond.lock()
  • cond.wait()
  • cond.notify()
  • cond.notifyAll()

40
Provider
  • // INSTALL PROVIDER AT START-UP
  • Provider provider new OpenSSLProvider()
  • po.loadDigestAlgorithms()
  • po.loadSignatureAlgorithms()
  • po.seedRandomGenerator(seed)
  • ProvidersetProvider(po)
  • Provides Base64, MessageDigest, Signature,
    Hmac,
  • PublicKey/PrivateKey
    generation, encoding, and decoding
  • X509Certificate generation,
    encoding, decoding
  • SecretKey generation,
    encoding, and decoding.
  • SSLContext, SSLSocket,
    SSLServerSocket,
  • KeyStore. (PKCS12)

41
Private Keys/Public Keys
  • KeyFactory fac KeyFactorygetInstance()
  • KeyPair pair generateRSAKeyPair(1024, 3)
  • KeyPair pair generateDSAKeyPair(512)
  • // DECODING
  • privateKey fac.initPrivateKeyFromFile(PEM,
    fileName)
  • // ENCODING
  • fac.writePrivateKeyToFile(PEM, privateKey,
    fileName)

42
Message Digest Engine
  • MessageDigest eng MessageDigestgetInstance
    (MD5)
  • eng.update(data)
  • eng.update(moreData)
  • string digest eng.digest()
  • // Convenient
  • string digest MessageDigestdigest(MD5,
    data)

43
Base64 Engine
  • // ENCODING
  • Base64 eng Base64getInstance()
  • eng.encodeUpdate(data)
  • eng.encodeUpdate(moreData)
  • string enc eng.encode()
  • // Convenient
  • string enc Base64encode(data)
  • // DECODING
  • Base64 eng Base64getInstance()
  • eng.decodeUpdate(enc)
  • string data eng.decode()
  • // Convenient
  • string data Base64decode(enc)

44
Signature Engine
  • // Signing
  • Signature eng SignaturegetInstance(RSA/
    MD5)
  • eng.initSign(privateKey)
  • eng.update(data)
  • string signature eng.sign()
  • // Verifying
  • Signature eng SignaturegetInstance(RSA/
    MD5)
  • eng.initVerify(publicKey())
  • eng.update(data)
  • bool verified eng.verify(signature)

45
X509 Certificates
  • CertificateFactory fac CertificateFactorygetIn
    stance()
  • X509Certificate cert fac.initCertFromFile(PEM
    , fileName)
  • bool verified cert.verify(caPublicKey)
  • bool valid cert.checkValidity()

46
HMAC Engine
  • Hmac eng HmacgetInstance(DES/MD5)
  • eng.init(secretKey)
  • eng.update(data)
  • string keyedDigest eng.digest()

47
Conclusion
  • Have a nice weekend.
Write a Comment
User Comments (0)
About PowerShow.com