# Presentation: 009395

## Building  Medium Size Projects.

- Some Fundamentals and Principles.
- By
- Abdelilah Essiari

## Conventions

- Must agree on a set of conventions.
- consistent => professional => good first impression
- consistent => predictability => 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.

## 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

## Languages

- Objectives  are the same.
- Robustness
- Small code size
- Efficiency
- Elegance
- Easy to maintain/extend
- Portability
- It is the “how” that changes.

## Languages

- Know the weaknesses.
- Know the strengths.
- Don’t push it.
- Do unnatural things.
- Not all features are good.

## 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.”

## WE DO NOT LIKE  

- Global variables/functions
- Long methods and large classes.
- Long parameter lists.
- Code duplication.
- Side effects.
- Dependencies.

## Global Variables/functions

- Hard to find.
- Polluting the global name space.
- Rigid.
- Use the Singleton pattern or a utility class.

## How Java deals with system wide constants

-   void foo() {  Properties props = System.getProperties();
-       String ssl  = props.getProperty(“SSL”,  “OFF”);
-       if (ssl.equals(“ON”)) {
-       } else {
-       }
-    }

## 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.

## 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.

## 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;
-      };

## 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, x+y, x*y, x * x,
-    This tends to make your classes have too many member variables. If your intent is
-     caching for efficiency’s case, remember
-     the evils of early optimization.

## 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

## 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.

## 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.

## 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) {
-          // Don’t have a clue what happened  }

## A very suspicious function

-          void doSomething() {         try {
-                 ...
-              } catch(Exception ex) {
-                  System.out.print( “Is anyone watching the screen?”);
-              }
-              return;
-          }

## 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(“SURPRISE SUPRISE”)
-       }

## 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();
-          }
-      }

## 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.

## 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();
-            }
-        }

## 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++

## 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 A&a) const;
-      const Y& foo(const A& a, const B& b) const;
- };

## 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.

## 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.

## 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.unmodifiableCollection(myPreciousCollection);
-               }
-       Cool if  one tries to modify my precious collection,  he will get an   UnsupportedOperationException.

## 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...”

## Smart Pointers

-     void foo() {    A* a = new A();
-          a->f();
-          a->g();
-          delete(a);       // Hope this line is executed. (Optimistic)
-     }
-     void foo() {        // a will always be deleted.
-         SmartPtr<A> a = new A();
-         a->f();
-         a->g();
-     }

## Smart Objects behave like ints

-   // internal class
-    class Ximpl {
-       public:
-          void f();
-       private:
-          // member variables
-       };

- // Exposed to clients.
- class X {
-    public:
-         void f() { impl->f();}
-    private:
-    SmartPtr<Ximpl> impl;
- };
- Usage:   X x;       // x is a smart
-               x.f();       // object

## Summary

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

## 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.

## 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

## 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 ->
- Good Error reporting
- No need for memory management/resource
-        management

## Threads

- Thread.start();
- Thread.join();
- Thread.getId();
- Thread cur  = Thread::getCurrentThread();
- Thread objects are smart Objects

## Threads

-  class MyCommand : public Runnable {
-   public:
-       void run() {
-              cur = Thread::getCurrentThread();
-        }
-   private:
-        Thread cur;
- };
-  void foo() {
-        Thread* t = new Thread(new MyCommand);
-         t->start();
-         delete(t);
- }
-  void foo() {
-      Command command(new MyCommand);
-      Thread  t(command);
-       t.start();
-  }

## 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. 

## Mutexes.

- Mutexes and Recursive mutexes.
-    class MyObject {
-      public:
-           void f() {
-               mutex.lock();
-                ...
-                mutex.unlock();
-           }
-           void g() {         SmartMutex sm(mutex);
-                ...
-           }
-       private:
-           Mutex mutex;
-      };

## Conditions

-  Condition cond;
-   cond.lock();
-   cond.wait();
-   cond.notify();
-   cond.notifyAll();

## Provider

-    // INSTALL PROVIDER AT START-UP
-    Provider provider = new OpenSSLProvider();
-      po.loadDigestAlgorithms();
-      po.loadSignatureAlgorithms();
-      po.seedRandomGenerator(seed);
-      Provider::setProvider(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)

## Private Keys/Public Keys

-   KeyFactory fac = KeyFactory::getInstance();
-    KeyPair pair = generateRSAKeyPair(1024, 3);
-    KeyPair pair = generateDSAKeyPair(512);
-    // DECODING
-    privateKey =  fac.initPrivateKeyFromFile(“PEM”, fileName);
-    // ENCODING
-    fac.writePrivateKeyToFile(“PEM”,  privateKey, fileName);

## Message Digest Engine

-     MessageDigest  eng =MessageDigest::getInstance(“MD5”);
-       eng.update(data);
-       eng.update(moreData);
-       string digest = eng.digest();
-       // Convenient
-       string digest = MessageDigest::digest(“MD5”, data);

## Base64 Engine

- // **ENCODING**
-  Base64 eng = Base64::getInstance();
-  eng.encodeUpdate(data);
-  eng.encodeUpdate(moreData);
-  string enc = eng.encode();
- // Convenient
- string enc = Base64::encode(data);

**// DECODING**
- Base64 eng = Base64::getInstance();
- eng.decodeUpdate(enc);
- string data = eng.decode();
- // Convenient
- string data = Base64::decode(enc);

## Signature Engine

-     // **Signing**
-       Signature eng = Signature::getInstance(“RSA/MD5”);
-       eng.initSign(privateKey);
-       eng.update(data);
-       string signature = eng.sign();
-       // **Verifying**
-       Signature eng = Signature::getInstance(“RSA/MD5”);
-       eng.initVerify(publicKey());
-       eng.update(data);
-       bool  verified = eng.verify(signature);

## X509 Certificates

- CertificateFactory fac = CertificateFactory::getInstance();
-  X509Certificate cert = fac.initCertFromFile(“PEM”, fileName);
-  bool verified = cert.verify(caPublicKey);
-  bool valid = cert.checkValidity();

## HMAC Engine

-   Hmac eng = Hmac::getInstance(“DES/MD5”);
-    eng.init(secretKey);
-    eng.update(data);
-    string keyedDigest = eng.digest();

## Conclusion

- Have a nice weekend.