annaprograms-blog
Anna's Programming Observations
7 posts
Welcome! I am Anna and I program. Sometimes I find bugs in the code that I write or learn something new and cool about programming.  This blog is dedicated to my programming finds!
Don't wanna be here? Send us removal request.
annaprograms-blog · 8 years ago
Text
Lessons from Effective Java (Joshua Bloch) - Chapter 2 “Creating and Destroying Objects”
This chapter concerns creating and destroying objects: when and how to create them, when and how to avoid creating them, how to ensure they are destroyed in a timely manner, and how to manage any cleanup actions that must precede their destructions.
Item 1: Consider static factory methods instead of constructors
Static factory method - a static method that returns an instance of the class.
For example:
public static Boolean valueOf(boolean b){ return b ? Boolean.TRUE : Boolean.FALSE; }
An advantage of a static factory method is that unlike constructors, they have names.
Another advantage is that they are not required to create a new object each time they’re invoked. Therefore, immutable classes use pre-constructed classes, or to cache instances as they are constructed, and dispense them repeatedly to avoid creating unnecessary duplicate objects.
Because of that we are always maintaining control over what instances exist at any time (we call these objects instance-controlled).
Third advantage - unlike constructors,** they can return an object of any subtype of their return type**. An API can return objects without making their classes public. This technique of hiding implementation classes leads to a very compact API.
Welcome interface-based frameworks! (drum roll)
Using a static factory method requires the client to refer to the returned object by its interface rather than its implementation class. Any class that is a subtype of the declared return type is permissible.
Sometimes, the class of the object returned by a static factory method need not even exist when the class containing the method is written. These flexible static factory methods form the basis of service provider framework (example: JDBC - Java Database Connectivity API). A service provider framework is a system in which multiple service providers implement a service, and the system makes the implementations available to its clients, decoupling them from the implementations.
3 essential components:
service interface - providers implement these.
provider registration API - the system uses this to register implementations, giving clients access to them.
service access API - clients use to obtain an instance of the service.
(optional) service provider interface - providers implement to create instances of their service implementation.
Example:
// Service Provider framework sketch // Service interface public interface Service{ // ... // Service-specific methods go here // ... } // Service provider interface public interface Provider{ Service newService(); } // Noninstantiable class for service registration and access public class Services{ public Services(){}; // Maps service names to services private static final Map<String, Provider> providers = new ConcurrentHashMap<String, Provider>(); public static final String DEFAULT_PROVIDER_NAME = "<def>"; // Provider registration API public static void registerDeafultProvider(Provider p){ registerProvider(DEFAULT_PROVIDER_NAME, p); } public static void registerProvider(String name, Provider p){ providers.put(name, p); } // Service access API public static Service newInstance(){ return newInstance(DEFAULT_PROVIDER_NAME); } public static Service newInstance(String name){ Provider p = providers.get(name); if(p == null) throw new IllegalArgumentException("No provider registered with name " + name); return p.newService(); } }
Fourth advantage of static factory methods is that they reduce the verbosity of creating parametrized type instances.
Disadvantages of only static factory methods;
Classes without public or protected constructors cannot be subclassed.
They are not readily distinguishable from other static methods. They do not stand out in API documentation in the way that constructors do, so it can be difficult to figure out how to instantiate a class that provides static factory methods instead of constructors.
Common names for static factory methods: valueOf, of, getInstance, newInstance, getType, newType.
Item 2: Consider a builder when faced with many constructor parameters
There are several different ways to construct a complex object.
Some well-known techniques:
It kind of sucks because it is hard to write client code when there are so many parameters, and harder still to read it.
Not good either because a JavaBean may be in an inconsistent state partway through its construction.
A builder whose parameters have been set makes a fine Abstract Factory. A client can pass such a builder to a method to enable the method to enable the method to create one or more objects for the client. Need a type to represent a builder.
Disadvantage: in order to create an object, first create its builder. The Builder pattern is also more verbose than the telescoping pattern, so it should be used if there are enough parameters.
The client calls the constructor (or static factory) with all of the required parameters and gets a builder object. Then the client calls setter-like methods on the builder object to set each optional parameter of interest.
NutritionFacts CocaCola = new NutritionFacts.Builder(240, 8).calories(100).sodium(35).build();
Item 3: Enforce the singleton property with a private constructor or an enum type.
A singleton is a class that is instantiated only once. Singletons typically represent a system component that is intrinsically unique, such as the window manager or file system. Making a class a singleton can make it difficult to test its clients.
// Singleton with public final field public class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis (){...}
public void leaveTheBuilding();
} The private constructor will only be called once, to initialize the public static field Elvis.INSTANCE. The lack of a public or protected constructor guarantees a "monoelvistic" universe: exactly one Elvis instance will exist once the Elvis class is initialized - no more, no less. Second approach of implementing singletons is the public member is a static factory method. public class Elvis{ private static final Elvis INSTANCE = new Elvis(); private Elvis(){...} // getInstance is a static factory method // all calls to Elvis.getInstance return the same object // and no other Elvis instance will be created. public static Elvis getInstance(){return INSTANCE;}
public void leaveTheBuilding(){...};
} Advantage: the declarations make it clear that the class is a singleton: the public static field is final, so it will always contain the same object reference. To preserve the singleton property, declare that to be an enum with one element. // Enum singleton - the preferred approach public enum Elvis{ INSTANCE;
public void leaveTheBuilding(){...}; } A single-element enum type is the best way to implement a singleton. 
Item 4: Enforce noninstantiability with a private constructor In cases when we are writing a class that is just a grouping of static methods and static fields, like for example if we are grouping methods on a final class, instead of extending a class.
A class can be made noninstantiable by including a private constructor: // Noninstantiable utility class public class UtilityClass{ // Suppress default constructor for noninstantiability
// explicit constructor below private UtilityClass{ throw new AssertionError(); } ... // Remainder omitted } The explicit constructor is private, so it is inaccessible outside of the class. 
Item 5: Avoid creating unnecessary objects Immutable objects can always be reused. We can avoid creating unnecessary objects by using static factory methods in preference to constructors on immutable classes that provide both.
Example: static factory method Boolean.valueOf(String) is almost always preferable to the constructor Boolean(String).
Use static initializer.
Example: static{ ... }
This allows for creating fields once when the object is initialized. Objects suck because they create new instances of themselves every time.
autoboxing - a new way to create unnecessary objects that allows the programmer to mix primitive and boxed primitive types, boxing and unboxing automatically as needed. Autoboxing blurs but does not erase the distrinction between primitive and boxed primitive types. 
Prefer primitive to boxed primitives, and watch out for unintentional autoboxing. 
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. 
Item 6: Eliminate obsolete object references 
Memory leaks - manifest themselves as reduced performance due to increased garbage collector activity or increased memory footprint. In extreme cases, such memory leaks can cause disk paging and even program failure with an OutOfMemoryError, but such failures are relatively rare. 
Obsolete references - a reference that will never be dereferenced again. (aka unintentional object retentions). 
They suck because not only the object reference is unintentionally retained, but also the object is excluded from garbage collection, along with the objects that are referenced by the other object.
Fix: null out references once they become obsolete. Another benefit of doing that is if they are subsequently dereferenced by mistake, the program will immediately fail with a NullPointerException. 
Nulling out object references should be the exception rather than the norm. 
By defining a variable in a narrowest possible scope, we eliminate these obsolete references. 
Generally, whenever a programmer manages its own memory, the programmer should be alert for memory leaks. 
Caches are also a source of memory leaks. 
A third common source of memory leaks is listeners and other callbacks. use WeakHashMap. 
WeakHashMap - Hash table based implementation of the Map interface, with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations. Memory leaks may stay in the system for years. Use heap profiler to debug your code. 
Item 7: Avoid finalizers
Finalizers are unpredictable, often dangerous, and generally unnecessary.
We do not know how long it will take for finalizers to be executed. It can take arbitrarily long between the time that an object becomes unreachable and the time that its finalizer is executed. 
Never do anything time-critical in a finalizer. The promptness with which a finalizer is executed is a function of the garbage collection algorithm, which varies from JVM to a JVM implementation. 
Do not depend on a finalizer to update critical persistent state. 
System.gc and System.runFinalization may increase the odds of finalizers getting executed, but they do not guarantee it. 
Finalizers also take a lot longer. 
Instead of using a finalizer, provide an explicit termination method.
Examples of those include:
close methods on InputStream, OutputStream and the cancel method on Java.util.Timer. 
Explicit termination methods are typically used in combination with the try-finally construct to ensure termination. 
// try-finally block guarantees execution of termination method Foo foo = new Foo(...); try{ //Do what must be done with foo }finally{ foo.terminate(); } 
Finalizers are good for:
To act as a "safety net" in case the owner of an object forgets to call its explicit termination method.
Native peers - a native peer is a native object to which a normal object delegates via native methods.
0 notes
annaprograms-blog · 8 years ago
Text
semicolons
ugh, a wasted few minutes of life
Tumblr media
0 notes
annaprograms-blog · 8 years ago
Text
not a bug, but
JavaScript just kind of sucks (coming from a person who is used to a strong type system)
0 notes
annaprograms-blog · 8 years ago
Text
JavaScript
Tumblr media
See the dot?
I could not figure out why player (a field received through an ajax call) was not getting passed to the addPerson function, even though it was already in the scope. It was because of the dot. addPerson function was still getting called without any problems.
0 notes
annaprograms-blog · 8 years ago
Text
“Find The Bug” tips
In Chapter 2, Adam Burr suggests a few things you could do while walking through code. An interesting method he identifies as a way for programmers to find bugs in their code is “inspeculation”, which is the mixture of “inspection”, “simulation” and “speculation.” Barr says: “In other words [programmers] either go away and think about something else for a while, or else spend a lot of time reading through the code and thinking about it, possibly hand-stimulating an execution run.” Instead of stimulating the run of the code and monitoring the execution, the programmer thinks about the program.
The following list contains the steps to aid in the process of inspeculation. Barr goes into more detail of each step later in the chapter. 
Split the code into sections with goals.
Identify the meaning of each variable.
Look for known “gotchas.”
Choose inputs for walkthroughs.
Walk through each action.
0 notes
annaprograms-blog · 8 years ago
Text
Squash it
The perfect read to go along with this blog! Picked up this bad boy from the library a few days ago. 
Tumblr media
0 notes
annaprograms-blog · 8 years ago
Text
Programming calculators is more fun than studying for Statistics!
I was adding a formula to my TI-84 and found that the function would return the same constant for any input. After reviewing the code I discovered that I was returning the same variable that was not overwritten since the last function invocation because I forgot to add a variable assignment command at the end of the computation. The title says it all.
0 notes