It seems that for a very long time, since Blogger implemented the ugly system that changes the blog domain to a local domain, my blog was inaccessible for people in the UK and other places where the domain country had more segments, like co.in, co.uk, com.au, etc. due to a bug in my solution for it. I need to apologize for that. I fixed the problem now, but damn it is a long standing bug, a full three years.
Some of you may have heard of C# 6, the new version of the Microsoft .NET programming language, but what I am not certain about is that you know you can use it right now. I had expected that a new version of the language will be usable from the brand new upcoming fifth version of the .NET runtime, but actually no, you can use it right now in your projects, because the new features have been implemented in the compiler, in Visual Studio and, you have no idea how cool it is until you try, in ReSharper.
One might say: "Hell, I've seen these syntactic sugar thingies before, they are nothing but a layer over existing functionality. New version, my ass, I stick with what I know!", but you run the risk of doing as one of my junior developer colleagues did once, all red faced and angry, accusing me that I have replaced their code with question marks. I had used the null-coalescing operator to replace five line blocks like if (something == null) { ....
Let me give you some examples of these cool features, features that I have discovered not by assiduously learning them from Microsoft release documents, by but installing ReSharper - only the coolest software ever - who recommends me the changes in existing code. Let's see what it does.
Example 1: properties with getters and no setters
Classic example:
publicint Count { get { return _innerList.Count; } }
Same thing using C# 6 features?
publicint Count => _innerList.Count;
Cool or what?
Example 2: null checking in a property chain
Classic example:
if (Granddaddy!=null) { if (Daddy!=null) { if (Child!=null) { return Grandaddy.Daddy.Child.SomeStupidProperty; } } }
publicint Number { get { return _number; } set { if (_number!=value) { _number=value; OnPropertyChanged("Number"); //with some custom code you could have used a better, but slower version: //OnPropertyChanged(()=>Number); } } }
C# 6 version?
publicint Number { get { return _number; } set { if (_number!=value) { _number=value; OnPropertyChanged(nameof(Number)); // this assumes that we have a base class with a method called OnPropertyChaged, but we can already to things inline: PropertyChanged?.Invoke(this,newnew PropertyChangedEventArgs(nameof(Number)) } } }
Example 4: overriding or implementing simple methods
I don't particularly like this, but it can simplify some code when used right. Classic example:
return degrees*Math.PI/180;
C# 6 way:
//somewhere above: usingstatic System.Math;
return degrees*PI/180;
There are other more complex features as well, like special index initializers for Dictionary objects, await in catch and finally blocks, Auto-property initializers and Primary Constructors for structs. You can use all these features in any .NET version 4 and above. All you need is the new Roslyn compiler.
There are a lot of people asking around what is the difference between BindingList<T> and ObservableCollection<T> and therefore, there are a lot of answers. I am writing this entry so that next time I look it up, I save StackOverflow some bandwidth. Also, because my blog is cooler :)
So, the first difference between BindingList and ObservableCollection is that BindingList implements cascading notifications of change. If any of the items in the list implements INotifyPropertyChanged, it will accept any change from those items and expose it as a list changed event, including the index of the item that initiated the change. ObservableCollection does not do that. So BindingList is better, right?
Wrong. BindingList is not "properly supported" by WPF, say some. Why is that? Well, because BindingList, as its MSDN page says, is just "an alternative to implementing the complete IBindingList interface". Yes, you've got it. BindingList is a lazy, thin, ineffective implementation of the interface. The Missing Docs blog has a very good explanation of this. Do keep in mind that BindingList was created during the time of Windows Forms and is being used by WPF only as an afterthought.
So let's use ObservableCollection then! No. The functionalities implemented by BindingList are far superior to that of ObservableCollection. Just thinking that you must somehow handle changes of every object in the list is killing the idea.
A subtle recommendation on the same MSDN page goes like this: "the typical solutions programmer will use a class that provides data binding functionality, such as BindingSource, instead of directly using BindingList". Well, what does that mean? It means using System.Windows.Forms.BindingSource, which does about everything, since it implements IBindingListView, IBindingList, IList, ICollection, IEnumerable, ITypedList, ICancelAddNew, ISupportInitializeNotification, ISupportInitialize, ICurrencyManagerProvider and is also a subclass of Component. A bit heavy, though, isn't it?
There is more. The BindingListCollectionView page says "Specifically, IBindingList is required for BindingListCollectionView, and IBindingListView is an optional interface that gives additional sorting and filtering support.", which indicates that IBindingListView is also useful when getting a collection view for your object.
To recap: the best solution seems to be an ObservableCollection<T> that also implements IBindingListView (which itself implements IBindingList). The implementation must be scalable (getting the index of an object that causes a change in an efficient manner), though and I wonder, if I am implementing IBindingList, why should I even bother with inheriting from ObservableCollection? The same StackOverflow user seems interested only in the INotifyCollectionChanged interface for the ObservableCollection which is also implemented by IBindingListView!
Therefore, let's implement a class that explicitly implements IBindingListView and IList<T>, then publish the members we actually use! What could possibly go wrong? My idea is to store the index of an item next to the item, therefore removing the need to search for it. It seems that I must first implement an advanced List<T>, with a fast and efficient IndexOf method, then I can basically just copy paste the BindingList code and use this class of mine as the base. Unfortunately, BindingList uses Collection<T> as the base class, which itself implements IList<T>, IList, IReadOnlyList<T>. It seems I will have to implement all.
Immediately I have hit a snag. IBindingView is very difficult to implement, since it tries to filter using a string that is interpreted as a sort of DSL, so I would use a lot of reflection and weird conditions. Sorting is not much better. This is an interface invented when .NET did not support Predicates and lambda expressions, which would make sorting and filtering trivial and the subject of another post. So I go back to implementing a scalable BindingList, and just implement INotifyCollectionChanged over it.
For an implementation of IBindingView, check this out: BindingListView
Code time.
I've decided to implement the IndexOf caching as a dictionary with the objects as keys. The values are lists of integers representing all indexes of that value or object. Frankly I never realized that IndexOf for lists was not taking a start parameter, so it only returns the first occurrence of an item in the list.
There are three classes: AdvancedCollection is a fast IndexOf implementation of Collection. AdvancedBindingList is the copy pasted code of BindingList, with the base class changed from Collection to AdvancedCollection and with INotifyCollectionChanged implemented over it. SecurityUtils is only needed for the AddNew method of IBindingList and is again copy pasted from the Microsoft code. Enjoy!
Just a short revelation that I had. It starts with the definition of free speech, which is considered free if it does no harm. This is what is called the principle of harm. But what is increasingly happening all over the world is that more and more of what people do is considered harmful. Things like racism or misogyny have been now joined by online bullying, pro-life discussions, fat shaming, you name it. The result is a reduction of free speech.
If you want free speech, then brave the words of others. It is the penchant of humans and all life in general to categorize the world and then act in different ways based on discrete cases. It is not entirely correct, but it is how nervous systems work since worms were invented. It is a biological impossibility to be confronted with human behavior and not consider one category of people better than another based not only on color, but whatever you see differentiate them. And while I understand the need to push back with legislation against some biases that have become counterproductive, we have to eventually dial back even on those. Adding more exceptions to how thinking and feeling works just pushes people away and stifles the ability to speak freely.
An especially worrying trend puts copyright and commercial interests higher and higher on the list of things you should not cross. It is becoming so powerful a concept that it is increasingly used to stop people from expressing themselves. Online reviewers are being sued for not liking a product, people are being stopped from reading controversial material by buying the rights and then not publishing it and so on. But even small things that seem proper at first glance are just as toxic, like protecting children from all kinds of perceived threats. Forget they are children, just analyse the social cost of having them exposed to something; people learn from experience, there is always a balance between harm and evolution.
When will it end, you might ask yourself. Think of border cases like Snowden. Do you side with him, for disclosing information that affects all of us, literally, or do you side with the people that say he committed treason? Do you think encryption should be banned, so that governments can better take care of us by knowing everything there is to know about what we communicate? How about getting fined by the hotel you've just been to because you write a negative review. Are all these worth stopping people from calling you fat, gay, colored, old, stupid, or whatever you feel offends you most?
This book opened my eyes on multiple levels. First of all it went right through my Dunning–Kruger effect that made me hope that writing would be easy. Second, it showed me how to see the world as a writer, which is hugely valuable.
Writing Vivid Settings is also a value packed reference book. Rayne Hall doesn't go artificially raising your expectation level - you know the type: "in this book I will show you how to eliminate hunger and solve poverty, but before that...", he instead just goes right into it. In fact the transition to actual useful information was so abrupt that I found myself feeling grateful before I could even understand what the book was about. Then, when I did, it hit me even harder, because I understood not only what I was missing in my writing, but also what I was missing in my every day perception.
If I were to summarize the book, it is all about consciously describing from the point of view of your characters, in a way that makes the reader connect emotionally and subconsciously to the character and scene. In Hall's view there is no such thing as objective scenes, they are defined more than anything else by the character that observes them. The book advises to describe through the senses: smells, sounds, the lighting of the room, the way things feel to the touch, etc, then go towards what the character would most likely notice, based on their own personality and background, making sure to use similes so that the memory of the scene becomes anchored in the reader's mind in the same way it would in the mind of the observer in the book. Yes, it does sound weird, doesn't it? Make the reader feel as the person who doesn't really exist except in the writer's head.
Each chapter in the book explains elements on how to describe the surroundings, when to use them, how to use them, what to avoid, professional examples from other books and some assignments to make you get right to it. And there is where it becomes interesting. When I told my wife about it, she immediately recognized exercises for "grounding", something that is used in mindfulness and gestalt psychology. As an example: describe the smells in the room, then the way the light enters it and how it changes the colors, then some background sounds, all by using verbs that are very specific and indicative of the character's mood and similes that would be indicative of the character's background. I kind of mixed several chapters in this, so you can get the point. Well, when is the last time you ever did something like that in your life? When were you last conscious of the sounds and smells around you and what they evoke? When did you last compare the light in a place to a living thing, with a mind of its own, just because you can? It is all about bringing all those vague perceptions to a form that can be communicated, to others and to yourself.
That is the trick to good writing, for sure, but also a way of observing the world around you. Suddenly, I felt like a little child that doesn't see the world around because he doesn't know how. I found myself going places and trying to describe the scene as instructed in the book - many of the assignments in it suggest doing right that, anyway - and it was hard. It was more than hard, it felt impossible. Like living your life on a psychologist's bench, always asking you "what does that mean?" and "how does it make you feel?" and "what will that lead to?". But how alive the world seemed while doing that! Aware of my own senses, feelings and their roots, I could suddenly understand people who enjoy life for its own sake. The book's description is "Do you want your readers to feel like they're really there—in the place where the story happens?" After reading it, it seemed that I was never there in the first place.
It probably doesn't say things differently from other writing books, but it certainly opened my eyes. I also absolutely loved how it didn't start with marketing bullshit and got right into it, with theory, examples and exercises. It can be used as a reference, before and after writing, since it has exercises on improving already existing work. I think this is a great book.
I've decided to read some of the stuff that takes place in the Star Trek universe, for research purposes. I was particularly interested in Starfleet Academy and, since Next Generation was clearly the best Star Trek series yet, I went with that one. So here I am reviewing the first three in a fourteen book series called Star Trek The Next Generation: Starfleet Academy Book Series, all written by Peter David. And, boy, am I disappointed!
It's not that I expected some high end drama, but in reality each one of these books is a booklet that one can read in about 2 hours. All three of them together are barely a novel. And the thing is that this is exactly what I was looking for: a history of the crew of the Enterprise from when they were cadets. What am I disappointed for? It is a "written by numbers" book. It is one of those "write a novel in nine days" thing, only each is probably written in five. The characters are shallow, undeveloped, details are missing and there is no real science fiction in there. I mean the real stuff, the one that takes into account centuries of cultural and technological evolution in which we had eugenic wars and a third World War, in which we encountered a myriad of alien species that are very different from us. There is no social commentary, no psychological evolution, no high technology and no real personal drama. And I understand. Just take a look at the bibliography of Peter David, it needs its own page. The man is a writing monster. However, it is clearly a quantity vs quality thing.
Anyway, I will review all three books as a single story, which in fact it is. All about Worf at the Academy, Worf's First Adventure is about proving himself in a simulated battle against the Romulans, while Line of Fire and Survival are about him taking command of a diplomatic mission on a joint Federation-Klingon colony.
From the first pages we get that Worf has a conflicted personality, stuck somewhere between the strict tenets of the Klingon culture and the Human education from his parents, unclear if he is more Klingon or more Human. His parents are proud of him and his adoptive brother as they embark for the Starfleet Academy, but from then on, for three "books" of adventure, we don't hear anything about those parents anymore. In fact, the first book is there merely to prove Worf's superiority over his human brother who is forced to leave the Academy as soon as the story ends. Afterward, we don't read anything about him, either. There are more pages dedicated to grumpy and violent behavior than it is to what the Academy entails, what are the courses, or how disjointed lectures can form a cadet into an officer in a four year standard program. It is not explained why some are engineers and some are in security, even when they are taking the same classes. Nor is it made obvious how the teaching methods in the twentyfourth century differ from the ones in 1980. Worf simply floats from one sequence to the other, like in a dream, without the need for continuity or context or even common sense.
To summarize: Worf comes to the Academy, learns nothing new and his innate values and abilities help him go through the challenges posed by a Starfleet training. I mean, really, there is a part there about how Worf was taught to be in a certain way and not helping a team member when in need was simply not conceivable. So basically... he remains unchanged. True, Worf is one of the most stubborn and difficult to change characters in Star Trek, but still, a good story needs some sort of development, some sort of life changing challenge, any kind of challenge at all.
In truth, this level of writing makes me more confident on my prospects of writing books myself, but I don't want to read stuff like this.
I am a .NET programmer living and working in Bucharest, Romania.
Posts are divided into programming and misc.
Check out the icons above on how to contact or chat with me.
Unless otherwise specified, all code or any type of work you find on this blog is under MIT license. While I welcome attribution, I don't require it. Just use anything in any way you see fit. Consider it completely and utterly shared for the lulz.