Core Values Theory: Hacking Emotions

Underwood: “And you don’t make decisions on emotions?” Tusk: “Decisions based on emotions aren’t decisions at all. They’re instincts, … which can be of value. The rational and the irrational complement each other. Individually they’re far less powerful.”

This exchange between the manipulative protagonist Frank Underwood and billionaire Raymond Tusk in House of Cards highlights a key argument I’ve been raising during discussions on relationships for years—decisions based on emotions aren’t decisions at all. It sets the scene for a rational account on relationships I’ve come to refer to as ‘core values theory‘ during many heated conversations late into the night. My own understanding of the concept, based on nothing else but the experience of life, seems to have solidified sufficiently in order to recount it here. Although you are reading a software design blog, don’t expect anything IT related beyond the title “Hacking Emotions” from here on out.

What do you want?

what do you want

Seems like a simple question doesn’t it? “What do you want in life?” The truth though is that the majority of people you ask this question either greet you with a blank stare, or simply state they “just want to be happy”. Try it out for yourself! Next time, rather than discussing the newest episode of Game of Thrones, catch a friend off guard by asking this very question. You might be surprised to discover a general consensus that we are all just pawns in the grand scheme of things; passive bystanders whose roles are limited to either jumping on the passing train, or waiting for the next one. “Carpe Diem” offers a rich perspective on life, make the most out of each moment, but does it exclude glancing at the train schedule so you know where you are headed?

The problem with the blank stare, or solely relying on emotions to decide on a course of action, is you assume a passive role in life. You let your environment decide for you and simply express approval or disapproval. You do not grow as a person—you do not learn what it is that makes you happy or unhappy, what your goal is in life. Ultimately, it is counterproductive; simply pursuing the experience of happiness does not guarantee it in the long run, as you do not gain an understanding of how to maintain it. A case in point being our current materialistic society; quick-fix possessions do not lead to true happiness, on the contrary, it is self-destructive.

In his book “The 7 habits of highly effective people”, Stephen R. Covey’s advocates becoming aware of one’s own internal ‘maps': where you stand, and where you want to be headed.

Each of us has many, many maps in our head, which can be divided into two main categories: maps of the way things are, or realities, and maps of the way things should be, or values. We interpret everything we experience through these mental maps. We seldom question their accuracy; we’re usually even unaware that we have them. – Stephen R. Covey

Far from being a book I would recommend, it still contains valuable ideas, including the suggestion of being proactive as opposed to reactive in lifeBeing proactive does not simply mean taking matter into your own hands, but also implies identifying that which concerns you, in order to work towards enlarging your influence on that which truly matters to you. It implies a positive stance in life, asking yourself “What can I do?”, rather than “Why does this happen to me?”, the result of which is a rewarding sense of empowerment.

Part of what makes us human is we do not have control over our emotions. It is outside of our circle of influence, but most definitely within our circle of concern. How then, to take a proactive stance when emotions are involved?

So, what DO you want?

Relationships, being one of the most fundamental building blocks in life, give rise to the strongest of emotions: love, hate, loneliness, jealousy, … and happiness. While I imagine that most people readily agree with the earlier quote from House of Cards, I have yet to meet anyone that truly applies it in all aspects of life, including relationships. On the contrary, mainstream culture seems to disregard any sense of rationality when it comes to love. Love is impenetrable to human thought, and should be left to destiny. Media does a good job of reinforcing this simplistic view, even in nontraditional “Once upon a time …” movies: “It just happened. […] I just woke up one day and I knew.” – 500 Days of Summer

Unless you aren’t looking for ‘happy ever after’, the problem is relationships (and marriages) also “just happen” to end because “the love is gone“. This common view on relationships is a reactive one.

One of my most controversial viewpoints in life is that relationships should not be dictated by feelings. I look at emotions as a manifestation of an underlying cause which you do have some level of control over. I am not declaring war on feelings here. Feelings (or lack thereof) are useful signposts put up by your body. However, it is your mind’s job to follow the right ones and decide where to go. A proactive approach by no means guarantees a ‘happy ever after’, but more importantly increases your awareness of what you are looking for and allows you to learn from past experiences (what to repeat, and what not to repeat). I do not believe in relationships built solely on top of feelings, and consider them a fruitless endeavor; emotional roller-coasters that make you feel alive, but in the end you still need to exit the theme park.

There is a need to identify who you are, what you want in life, i.e. to identify your identity—your core. As often expressed: “Find yourself before you find love.”

Core Values

In a nutshell, core values theory advocates identifying objective values you expect your partner to have in a relationship, based on your expectations in life. They are testable, meaning, as you get to know someone, you can objectively judge whether or not they fit these criteria. They are ‘core‘ values in the sense that they make up your identity; changing them would imply changing your nature, your personality. Emotions do not come into play. Within Stephen R. Covey’s diagram it could be depicted as an unbendable center you are unwilling to change.

core_values_theory

Ironically, a common response to this is “But how can you be so picky? If one thing on the list doesn’t work out, you give up? You do not open up yourself to new experiences”. The truth though is most people already have a similar list, but just aren’t aware about it. By externalizing and objectifying it for some reason it becomes a faux pas. Their list however is usually longer, transient, more restrictive than the core values I am talking about here, and includes subjective values like “it needs to feel right”, or “it needs to be love at first sight”. The ‘list’ is nothing more than a mental exercise, identifying key aspects in your life on which to make more rational decisions when clouded by emotion, or even in the absence of emotion. If anything, it is more in line with the idiom, “There are plenty of fish in the sea”, recognizing you are not after ‘the one’, but after anyone you can fully respect, and love.

There is some reasoning behind this madness. Firstly, you should not think less of your spouse; a relationship is built on mutual respect. In the case of conflicting core values I argue this is unsustainable. It easily turns into recurrent arguments throughout the relationship, where you want to out-argue the other, causing resentment and loss of respect. Secondly, you should not expect to change or ‘fix’ your partner in a relationship; do not expect the core values of your partner to change, it is outside of your circle of influence. Your energy should be focused elsewhere, where you can actually make a change, and where you can still discover yourself.

This ‘theory’ has some controversial implications. There is nothing wrong with dating someone you have no feelings for, yet are sexually attracted to. Consider it an opportunity to discover your core values. From my own experience I can tell you either feelings will follow, or you learn something new about yourself to take with you into subsequent relationships. But more importantly, a breakup should be indicative of discovering a mismatch in core values, which makes it less of a loss, and more of a learning experience.

Conclusion

This perspective on relationships comes at a price. Most people want to be swept off their feet, where emotions take center stage. I’m a rational person, and prefer placing rationality at the center. Either way, the stage is big enough, and there is room for both. It might seem hard to believe in a long-term relationship with such conflicting perspectives, but luckily, a rational center is not a core value to me. I know I can learn a lot from an emotional counterpart, and I like to think this works both ways.

2 Comments

Generic TypeConverter for XAML

TypeConverter‘s in WPF are part of the underlying mechanism which allow you to assign values to attributes of complex types within XAML using plain strings. For example, whenever you specify Point‘s.

<LinearGradientBrush StartPoint="0,0" EndPoint="1,1">

Typically, you specify a TypeConverter for a certain type by applying the TypeConverterAttribute to it.

[TypeConverterAttribute( typeof( PointConverter ) )]
public struct Point : IFormattable

Since attribute arguments cannot use type parameters, this prevents you from specifying a generic TypeConverter for a generic class. I came across this issue while implementing a type converter to support specifying instances of my generic Interval class from XAML. The following is not possible.

// attribute argument cannot use type parameters
[TypeConverter( typeof( IntervalTypeConverter<T, TSize> ) )]
public class Interval<T, TSize>

However, you can write a non-generic TypeConverter which is capable of converting strings to several different target types. When using XAML you can obtain a IDestinationTypeProvider service through the context which is passed to the ConvertFrom method. From here you can retrieve the fully specified target type, including generic type parameters. Through reflection you can then call a Parse method on the specific type to take care of initializing an instance of the desired type. An example for Interval can be found in my library.

public override object ConvertFrom(
    ITypeDescriptorContext context,
    CultureInfo culture,
    object value )
{
    var typeProvider =
      (IDestinationTypeProvider)context.GetService( typeof( IDestinationTypeProvider ) );
    Type targetType = typeProvider.GetDestinationType();

    // ... convert to desired target type using a parsing method

    return base.ConvertFrom( context, culture, value );
}

However, it is important to note that this type provider will only work for XAML, since the IDestinationTypeProvider service is only provided by XAML’s ServiceProviderContext. It is thus not desirable to add this TypeProvider to types which work independent from XAML, like my Interval class. In addition this would require referencing the System.Xaml assembly.

How then to make XAML use this type provider without applying the attribute to the type definition? One option is applying the TypeConverter attribute on a per-property basis.

The per-property type converter technique is particularly useful if you choose to use a property type from Microsoft .NET Framework or from some other library where you cannot control the class definition and cannot apply a TypeConverterAttribute there.

However, this implies a lot of redundancy, having to apply the attribute to every property of that specific type. Using TypeDescriptor.AddAttributes() you can assign a TypeConverter at runtime.

TypeDescriptor.AddAttributes(
  typeof( Interval<,> ),
  new TypeConverterAttribute( typeof( IntervalTypeConverter ) ) );

Any subsequent TypeDescriptor.GetConverter() call will then return the converter for the specified type. Unfortunately this does not work for XAML, since XAML does not seem to take component modifications at runtime into account. Therefore, in order for this to work, we need to implement this runtime behavior ourselves. Recall that XAML does load TypeConverter‘s specified in TypeConverterAttribute‘s. We can thus use a special type converter which redirects its implementation to a converter loaded through TypeDescriptor to hook into XAML’s type conversion runtime. I implemented a RedirectTypeConverter which can be used as a base class for this exact purpose. Each of its methods first ensures the converter is initialized using TypeDescriptor, and then redirects the call to this converter. When TypeDescriptor.GetConverter( _type ) returns the redirecting type converter itself, this means no converter was specified using TypeDescriptor, hence no conversion is supported for this type.

protected RedirectTypeConverter( Type type )
{
	_type = type;
}

public override object ConvertFrom(
	ITypeDescriptorContext context,
	CultureInfo culture,
	object value )
{
	InitializeConverter();
	return _converter.ConvertFrom( context, culture, value );
}

public void InitializeConverter()
{
	if ( _converter != null )
	{
		return;
	}

	_converter = TypeDescriptor.GetConverter( _type );
	if ( _converter.GetType() == GetType() )
	{
		string message = string.Format(
		  "Conversion failed. Converter for {0} is missing in TypeDescriptor.", _type );
		throw new InvalidOperationException( message );
	}
}
class RedirectIntervalTypeConverter : RedirectTypeConverter
{
	public RedirectIntervalTypeConverter()
		: base( typeof( Interval<,> ) )
	{
	}
}

Applying this converter using TypeConverterAttribute to generic types thus allows redirecting type conversion to a converter which supports multiple target types in environments which provide information about the target type (like XAML using IDestinationTypeProvider). You only need to add the converter once, and it will be supported for all of your dependency properties using them.

TypeDescriptor.AddAttributes(
  typeof( Interval<,> ),
  new TypeConverterAttribute( typeof( IntervalTypeConverter ) ) );

Leave a comment

Interval: Generic Ranges in C#

There is no doubt about it; out of all the programming languages I ever experimented with, C# has offered me the most streamlined positive development experience so far. It is a modern, ever-evolving language, which now that C# and the whole .NET framework is turning to open source, is guaranteed an even greater future. However, some core constructs commonly available in other languages, like intervals which I introduce an implementation of in this post, are missing. E.g., Ruby has had Ranges for quite some time.

A Range represents an interval—a set of values with a beginning and an end.

Straightforward, but due to the lack of support for generic calculations in C#, a hassle to implement. However, as introduced by Marc Gravell, with some runtime compilation trickery involving expression trees, far from out of reach. I’ve had an Interval<T> class within my core library for quite some time, but just now refactored it to also support more complex intervals, e.g. an interval between two DateTime instances, which thus represents a TimeSpan.

Without further ado, an example of what using this looks like in practice.

// Mockup of a GUI element and mouse position.
var timeBar = new { X = 100, Width = 200 };
int mouseX = 180;

// Find out which date on the time bar the mouse is positioned on,
// assuming it represents whole of 2014.
var timeRepresentation = new Interval<int>( timeBar.X, timeBar.X + timeBar.Width );
DateTime start = new DateTime( 2014, 1, 1 );
DateTime end = new DateTime( 2014, 12, 31 );
var thisYear = new Interval<DateTime, TimeSpan>( start, end );
DateTime hoverOver = timeRepresentation.Map( mouseX, thisYear );

// If the user clicks, zoom in to this position.
double zoomLevel = 0.5;
double zoomInAt = thisYear.GetPercentageFor( hoverOver );
Interval<DateTime, TimeSpan> zoomed = thisYear.Scale( zoomLevel, zoomInAt );

// Iterate over the interval, e.g. draw labels.
zoomed.EveryStepOf( TimeSpan.FromDays( 1 ), d => DrawLabel( d ) );

As you might notice, the timeRepresentation interval has just one generic parameter (Interval<int>), whereas thisYear has two (Interval<DateTime, TimeSpan>). The less generic (one type parameter) class is a simple wrapper around the more generic base type which has two type parameters; the first denotes the type used to represent any position within the range, whereas the second type is used to represent differences between these positions. When these types are the same, the simplified wrapper can be used. Likewise, a TimeInterval wrapper can easily be created if you find Interval<DateTime, TimeSpan> to be too verbose.

Worth noting here to understand how it works under the covers is the constructor which sets two public static fields used during operations when conversions to double are needed. Arguably, this could be improved by having a factory creating the intervals and using constructor injection instead.

public TimeInterval( DateTime start, bool isStartIncluded, DateTime end, bool isEndIncluded )
	: base( start, isStartIncluded, end, isEndIncluded )
{
	ConvertDoubleToSize = d => new TimeSpan( (long)Math.Round( d ) );
	ConvertSizeToDouble = s => s.Ticks;
}

Once you start incorporating the notion of an interval in your programming arsenal you will be amazed by the opportunities which present themselves where to use them! Some actual examples within my core library:

To get an impression of the full range of currently supported operations, check out the unit tests.

1 Comment

From Personal Information Management to Humane Interaction

While discussing file management in the paper on Laevo I presented today at the UIST conference, I conclude …

[…], in essence files are a remnant of the original desktop metaphor. Users are forced to mentally connect window representations to the files they represent. When restoring window configurations users are [unnecessarily] confronted with finding all the related files.

I reflect on this later in the discussion:

[…], raising interesting questions for further research on how window management can be redesigned to outgrow its original purpose. Further research on Laevo is therefore to increasingly move away from files, as their main intent of persisting information could be replaced by persisting window configurations […]

This is in line with an old post of mine on window management, where I concluded:

Taking this to the extreme: assume closing a window would be the same as deleting a file. Would you actually ever have to know about the underlying file system again? Window management and file management could become one and the same thing.

Originally I titled the current post, “From File Management to Time Management”, since one of the conceptual challenges I like to confront myself with is to design for never having to reopen a file again. Rather, I want to support revisiting the full context (including the window representation of the file) which the original file was part of. As a desktop interface, Laevo uses a temporal representation allowing you to revisit any prior, or planned activity in time.

However, after a yet again inspiring talk by Bret Victor on “The Humane Representation of Thought: a trail map for the 21st century” as the closing keynote of the UIST 2014 conference, I realized that just as file management is a remnant of the original desktop metaphor, so is window management. Windows are a side effect of the digital rectangles we’ve grown so accustomed to within our lives. Window representations are mere visual abstractions of richer concepts and ideas which could be expressed in entirely different ways using all of our senses, rather than being restricted to visual and symbolic notations. The reason why we stick to them is because they allow for dynamic (connected) behavior, which is where the tangible all-around-us world falls short. Following the same argument that we should be phasing out file management, so should we attempt to eliminate the need for window management. The more intermediate abstractions we can remove to interact with the concepts and ideas we actually want to address, the better.

Nonetheless, my underlying thesis remains. The temporal (and associated contextual) dimension is a very tangible, humane concept, we should continue to design for.

1 Comment

Laevo presentation @ UIST 2014 conference

A first paper on Laevo has been accepted to the ACM Symposium on User Interface Software and Technology (UIST) 2014 in Honolulu, Hawaii.

Laevo: A Temporal Desktop Interface for Integrated Knowledge Work

I will be presenting the 8th of October, including a live demo of the system. Looking forward to the conference! The publication includes a 30s teaser and a longer video showcasing the different supported interactions.

Leave a comment

Getting started with the Java SignalR SDK

Microsoft has just released a Java SignalR SDK which allows Java and Android clients to access ASP.NET SignalR back ends. The library is open source, and currently it is up to you to build the .jar packages yourself. For your convenience I’ve uploaded my built .jar files. Given that this library as of yet is still fairly undocumented, and I spent quite some time on getting it up and running, I figured I’d provide a short introduction tutorial here. I found the C# SignalR client documentation to be the most useful while figuring out the API as the classes and methods overall seem to correspond. The tests in the GitHub repository are another useful resource. I’ll mainly be focusing on the specific differences in the Java library, and refer you to the original documentation for more elaborate information.

We will create a simple Hub supporting bidirectional communication. A quick and easy way to get a C# back end up and running for the purpose of this tutorial is to self-host a SignalR server in a simple console or WPF application. The following C# code shows a simple hub with one method which can be called by the Java client, SendMessage.

public class MessageHub : Hub
{
	public static event Action<string, string> MessageReceived = delegate { };

	public void SendMessage( string name, string message )
	{
		MessageReceived( name, message );
	}
}

I added a static event handler which can be consumed by the console or WPF front end to display the received message. SendMessage is called from a different thread, so in case you want to update the UI, don’t forget to use a dispatcher!

MessageHub.MessageReceived  += ( name, message ) => _dispatcher.Invoke(
    () => { MessageBox.Content = String.Format( "{0} said {1}", name, message ); } );

Onwards to the client side code! To set up a Java project which can use the SignalR client API, add the ‘signalr-client-sdk.jar’ and ‘gson-2.2.2.jar’ to the project build path. For Android projects the references need to be added differently. Drag the two jars, and the additional ‘signalr-client-sdk-android.jar’ to the libs folder in Eclipse. By doing so they will automatically be added as Android libraries.

As mentioned before, the SignalR Java client follows the same structure as the C# client API, thus setting up a connection is quite similar. However, for Android applications an additional platform component needs to be loaded as shown below; also don’t forget to add internet permission to your manifest file, or you will receive a SocketException when trying to connect.

Platform.loadPlatformComponent( new AndroidPlatformComponent() );
// Change to the IP address and matching port of your SignalR server.
String host = "http://192.168.0.xxx:8080";
HubConnection connection = new HubConnection( host );
HubProxy hub = connection.createHubProxy( "MessageHub" );

This simply configures the connection. Establishing the actual connection is somewhat different than the C# documentation due to limitations of Java. To mimic language support for async in C#, the SignalRFuture class is introduced. Asynchronous operations return an instance of this class, without actually performing any real work yet. What follows is example code of how to start the connection synchronously by calling get() on the SignalRFuture. Don’t forget to cleanly stop() the connection when shutting down the application.

SignalRFuture<Void> awaitConnection = connection.start();
try {
	awaitConnection.get();
} catch (InterruptedException e) {
	// Handle ...
} catch (ExecutionException e) {
	// Handle ...
}

In case your server is up and running, you should now be ready to start listening to and submitting messages. Again, listening to events in C# is more straightforward since it supports lambdas as the C# client API documentation demonstrates.

stockTickerHubProxy.On<Stock>( "UpdateStockPrice", stock => Console.WriteLine(
    "Stock update for {0} new price {1}", stock.Symbol, stock.Price) );

Doing something similar in Java requires elaborate inline anonymous classes, or the creation of a handler class per event you want to listen to. Suppose the server would send a message “context.Clients.All.UpdateStatus( “Online” );”, handling this the ‘C# way’ would like as follows:

hub.on( "UpdateStatus",
    new SubscriptionHandler<String>() {
        @Override
        public void run( String status ) {
           // Since we are updating the UI,
           // we need to use a handler of the UI thread.
           final String fStatus = status;
           handler.post( new Runnable() {
               @Override
               public void run() {
                   statusField.setText( fStatus );
               }
           } );
        }
    }
, String.class );

Therefore, Microsoft has seemingly added a method not available in the C# API to the Java client. Calling hub.subscribe( listener ) where listener is an object implementing corresponding methods for every available incoming event is a much more straightforward way to listen to messages. Under the covers this uses reflection to hook everything up correctly. These methods need to be public!

hub.subscribe( this );
...
public void UpdateStatus( String status )
{
	final String fStatus = status;
	handler.post(new Runnable(){
		@Override
		public void run() {
			statusField.setText( fStatus );
		}});
}

More complex types work as well, as long as it is supported by JSON. I don’t know the specifics, but this will be dependent on the SignalR server and the gson library used by the SignalR Java client. The following code prepares the client to call a new method on the server which you can add to the MessageHub: “public void SendCustomType( CustomType object ) { … }“.

// A simple C# class which can be sent over SignalR.
public class CustomType
{
	public string Name;
	public int Id;
}
// The same type as defined in Java.
public class CustomType
{
	public String Name;
	public int Id;
}

Finally, calling the earlier SendMessage() and the newly added SendCustomType() can be done as follows. As you can see, remote method invocation again returns a SignalRFuture, and a subsequent get() is needed.

try {
    hub.invoke( "SendMessage", "Client", "Hello world!" ).get();
    hub.invoke( "SendCustomType",
        new CustomType() {{ Name = "Universe"; Id = 42; }} ).get();
} catch (InterruptedException e) {
	// Handle ...
} catch (ExecutionException e) {
	// Handle ...
}

Similarly, you can simply pass custom objects from the server to the client by adding the custom type as a method parameter: “public void SomeMethod( CustomType bleh ) { … }

23 Comments

Generic Attributes in C#

As awesome as C# is, once you want to do some more advanced stuff with attributes, you quickly run into several limitations. There is even a Microsoft Connect entry on this issue.

  • Attributes can’t be generic, since a generic type cannot derive from ‘Attribute’.
  • An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.

Using TypeDescriptor and a whole bunch of custom code these limitations can be overcome. In this post I will describe an easier straightforward way by which to create something similar to generic attributes, ignoring the second issue for now. In future posts I will discuss how and where these attributes can be used for something I previously called attribute metabehavior.

The idea is quite straightforward; although attributes can’t be generic, nothing prevents you from adding generic instances to them. These instances can later be extracted at run time using reflection. The trick of course is initializing the generic instance. Once you know the Activator class can create instances by knowing their Type definition, the solution becomes self-evident. By simply passing the generic type as an argument to the attribute, instance creation can be delegated to Activator. Optional constructor arguments can also be passed as attribute arguments.

public class BehaviorAttribute : Attribute
{
	/// <summary>
	///   The dynamically created instance of the type passed to the constructor.
	/// </summary>
	public object DynamicInstance { get; private set; }

	/// <summary>
	///   Create a new attribute and initialize a certain type.
	/// </summary>
	/// <param name = "dynamicType">The type to initialize.</param>
	/// <param name = "constructorArguments">
	///   The arguments to pass to the constructor of the type.
	/// </param>
	public BehaviorAttribute(
		Type dynamicType,
		params object[] constructorArguments )
	{
		DynamicInstance =
			Activator.CreateInstance( dynamicType, constructorArguments );
	}
}

This attribute can then be be applied as follows:

class Answer<T>
{
	public T Value;

	public Answer( T value )
	{
		Value = value;
	}
}

[BehaviorAttribute( typeof( Answer<int> ), 42 )]
class TheWorld {}

Using ordinary reflection, the instance can be extracted.

Type type = typeof( TheWorld );
var behavior = (BehaviorAttribute)type
    .GetCustomAttributes( typeof( BehaviorAttribute ), false ).First());
var genericInstance = (Answer<int>)behavior.DynamicInstance;
int answer = genericInstance.Value;

What follows is up to you, how will you use this? I’ll describe a few advanced use cases in subsequent posts.

5 Comments

Follow

Get every new post delivered to your Inbox.