Feb 22, 2014

comparison with boolean

One of the things that smells for me in code is the comparison with boolean literals in C#.
All those things like
image
Recently, I was trying to find out, what makes people write such code and came to the conclusion that this is either lack of knowledge of statically typed language or mistake or just a fear of legacy code.
Let me explain the latter. There is a code that is stated it is working (possibly for decades). And there is a need to add a feature/fix a bug in that code. After the work is done, there could be changes that result in such code, and the person who does that changes is afraid of moving forward and lefts the comparison as it is.
Note, that this situation is just my imagination, I do not know exactly why such code exists. The situation is based on client’s legacy code, I have to work on. However, that’s not only clients with 10-years old code. Here is the same in Microsoft documentation:
http://msdn.microsoft.com/en-us/library/bb546150.aspx
The example text:
image

Jan 12, 2014

Git Extensions credentials issue

Second time I faced the issue while working with fresh-installed Git and GitExtensions. While pushing changes to github, GitExtensions said

geissue

I quickly realized that I already fought with that and here is the link to solution, so I could easily find it.

In short, the issue is in the global gitconfig file, [credential] option get some unnecessary backslashes.

Jan 5, 2014

Knockout in short

Knockout is a MVVM-style binding JavaScript framework. Home: http://knockoutjs.com/ – there are docs, tutorials (interactive also) and other. Could be extended by custom bindings.

View Model – pure JavaScript object.

To activate knockout on page: ko.applyBindings(viewModelObjectInstance); Can take second param (DOM object) to activate certain object only.

Observables

ko.observable() - functions that can update the UI when data changes, when setting multiple observables you could chain calls.

Computed

ko.computed() – computed observable. 1st par\am – computing func, second (optional) – ‘this’ for that func. With passing object like {read:func, write:func, owner: obj} you could create writeable computed observable. Computed recomputes dependencies when created and on each run. Circular are avoided (doesn’t enters reevaluating itself).

ko.isComputed(obj) – for all computed

ko.isObservable(obj) – for observables, observableArrays, all computed

ko.isWriteableObservable(obj) – for observables, observableArrays, writeable computed

Observable Arrays

Collections.

Methods like native: indexOf, slice, pop, push, shift, unshift, reverse, sort, splice. unshift\shift  = push\pop but for array start. splice = slice with removing from source array.

Own methods: remove, removeAll. destroy, destroyAll – set _destroy property to objects.

Bindings

Are done via HTML attribute data-bind, like <input data-bind=”text: myName”/>.

visible – applies to .style.display – sets to none or resets back to prev value.

text – sets the element content (innerText or textContent). Escapes the HTML. Could be used in containerless syntax (when no container is allowed in place where you need text) <!——ko text: name——> <!——/ko——>.

html – works with innerHTML.

css – add/remove classes. Static syntax - takes JavaScript object= “css {className: bool_JS_Expr }”. Dynamic syntax= “css: propertyName”.

style – takes JavaScript object. Use fontWeight instead off font-weight (see more in doc)

attr – any attribute. Takes JavaScript object.

Control flow

foreach – iterates by array copying the underlying HTML template. Could take a JS object, param data means array, as is an alias to be used in underlying HTML, there are also several callbacks. Also could use containerless binding syntax.

if, ifnot – adds or removes DOM and maintains bindings. Could be in containerless syntax.

with – creates binding context. Supports containerless.

Form bindings

click – binds a function. First param DOM object, second – event. clickBubble binding allows to sop bubbling. Return true from func to allow default action.

event – bind func to any event. Uses JS object syntax. Params and default action are as in click binding, bubbling is also similer (youreventBubble: false)

submit – like click.

enable, disable, hasFocus – intuitive.

value – for input, select, textarea (use checked for checkboxes).

checked – for checkboxes ad radiobuttons.

options, selectedOptions – for select. Main param is an array.

Templates

Use template binding. Can take either id of template or JS object with params. Manages the DOM to be generated inside and data to be used for binding.

Binding context

$parent, $parents (all parents chain), $root, $data (current context), $index(foreach only), $parentContext (for nested loops), $rawData (usually the same as $data), $context (current binding context),  $element (DOM element for current binding).

Nov 2, 2013

Moq

Moq - one of modern frameworks for mocking objects. It could do anything that could do inheritance in .NET. There is Castle under the hood, like Rhino.Mocks. But, there is no such diversity of object types - all of them are mocks. Yet there are 2 mock modes - that simplifies understanding.
And complicating thing is that Moq uses instances of Mock class to setup objects behavior and expectations. Below, Mock means Moq' class and mock means object instance that we need for test. I woud use the following style for examples:
public interface IRepository
{
    string ReadData();

    string Storage { get; set; }

    void SetData(object o);

    event EventHandler OnReading;
}

Creating objects

There are several means of creating object.
First, you could call
Mock<IRepository> mock = new Mock<IRepository>();
This constructor creates Mock for class or interface. There are several overloaded constructors - to specify mock mode, parameters for instance constructor (in case class has no parameterless constructor).
Modes available:
  • Loose - never throws, tries to return default values
  • Strict - throws in case there is no expectation for called method/property
Second option is to get mock-object directly:
IRepository repo = Mock.Of<IRepository>();
You could get an infinite collection and retrieve as many instances as you need:
IQueryable<IRepository> repos = Mocks.Of<IRepository>();
However, you would need an appropriate instance of Mock class to setup behavior of mock object:
Mock<IRepository> mock = Mock.Get(repo);

Mock abilities

You could tune mock object behavior, setup expectations.
Here are its properties:
  • Behavior - current mode, Loose or Strict
  • CallBase - should the base class be called in case expectations are not specified
  • DefaultValue - wat to return in Loose mode. You could get nulls for reference types, or try to create mocks for them automatically (you cannot create mock for sealed class obviously)
  • Object - instance of mock


Setting up behavior

There are a bunch of methods for setting up behavior:
  • Setup is used for defining expectations for methods.
  • SetupGet - for property getters
  • SetupSet - for property setters
  • SetupProperty - defines property to have "property behavior". That means that property would persist anything passed to setter.
  • SetupAllProperties - the same as SetupProperty - but for all properties at once.
All those methods allow to set expectations using Fluent method calls chain:
mock.Setup(r => r.ReadData()).Returns(() => "some result");

mock.Setup(r => r.ReadData())
     .Callback(() => Console.WriteLine("Read call"))
     .Throws<ApplicationException>();

mock.Setup(r => r.ReadData()).Verifiable();

That's quite intuitive: Returns defines what to return, Throws - what to throw, Callback - what to call.
Verifiable is for validation. All Verifiable expectations would be checked when calling Verify().

There is also SetReturnsDefault - that method sets the default value for some type. In example String    is a reference type, default value is null, but that could be changed:
mock1.SetReturnsDefault("abc");
All strings returned by mock1 by default would equal "abc".

In case arguments are not known beforehand, you could use It class:
mock.Setup(r => r.SetData(It.IsInRange("a", "c", Range.Exclusive)));
mock.Setup(r => r.SetData(It.IsAny<int>()));
mock.Setup(r => r.SetData(
    It.IsRegex("^4[0-9]{12}(?:[0-9]{3})?$")));//VISA credit card
There could be any arbitrary code:
Expression<Func<string, bool>> fridayPredicate =
    v => v == "HelloWorld" &&
    DateTime.Now.DayOfWeek == DayOfWeek.Friday;
mock.Setup(r => r.SetData(It.Is(fridayPredicate)));

Validation

There is no Fluent interface, but a lot of Verify methods, similar to Setup.
You could verify all expectations, marked as Verifiable - or just all expectation disregarding of marks (Verify and VerifyAll).
Also you could verify if particular class member has been called (with configurable error message and number of calls that is expected - from Never to range):
var mock = new Mock<IRepository>();

mock.Verify();

mock.VerifyAll();

mock.Verify(r=>r.ReadData(), "Read Data was not called");
mock.Verify(r=>r.SetData(123));

mock.VerifyGet(r => r.Storage, Times.AtLeast(4));

mock.VerifySet(r => r.Storage = "", 
    Times.Between(1, 10, Range.Exclusive));

Class It for arguments:
var mock = new Mock<IRepository>();

mock.Object.Storage = "b";

mock.VerifySet(r=>
    r.Storage = It.IsInRange("a", "c", Range.Exclusive));

Events

Events handling in Moq is quite interesting thing. There is method Raise, that accepts delegate as a first argument and EventArgs as a second. That delegate should attach a handler to event that is subject of handling. Moq runs delegate in a separate context, catching all class members calls. It catches add event method and thus knows what event to raise. Only virtual events could be handled that way (which limits this functionality greatly).
Looks like this:
string called = "one";

var mock = new Mock<IRepository>();
IRepository repo = mock.Object;
repo.OnReading += (sender1, eventArgs) => { called += "called"; };

EventHandler sampleHandler = (sender, args) =>
    { throw new NotImplementedException(); };

mock.Raise(r => r.OnReading += sampleHandler, new EventArgs());

Assert.AreEqual(called, "onecalled");

Delegate code is not important, Moq intercepts assignment and does not do anything in fact.

Conclusion

Framework is light and flexible in use, API is intuitive and easy, there is no complexities because of long library growth. Obsolete members and classes have [Obsolete] attribute, code is well documented.

Sources looks fine, there are attributes [SuppressMessage] for tuning code analysis (remove warnings about intentionally made things).

I described a part of Moq, it has much more, but I think there could be issues in complex situations, in example - there is no easy way to check order of method calls. However such tests would be quite brittle - I'm not sure of their value.

I like Moq more than Rhino.Mocks, both has their own pros and cons, but simplicity and organization won.

Rhino Mocks–what is it

Rhino Mocks, the mocking framework, appeared at 2005. It hasn’t had any changes for two years and author announced that he will not support the project anymore. Then, there was a guy who decided to continue development of Rhino Mocks. I took a look at source code – he would definitely have what to change and improve. Code is abandoned, documentation is almost absent.
Here, the last update.

May 27, 2013

mocking frameworks

In the next several subsequent posts I want to revise mocking frameworks available today, describe key features, provide examples and compare with alternatives.

Mock-objects are usually used in unit-tests to separate the object under test from its dependencies. Unit-tests are supposed to test objects independently, so the behavior of test should depend only on code of target object. To reach that goal the object dependencies should be replaced to stubs, that are doing nothing or just enough for test to pass. The mocking framework is the thing that simplifies generation of such stubs.

Also, mock-objects could come in handy in other test types, when there is need to check interaction with modules that are not written yet, or with system that works too slow to be used in automated testing.

There are different types of mock-objects:

  • stub - dumb objects.They don't contain any logic, their methods and properties return default values. Such objects are used for the cases when exact values are not needed or that dependency is not required for the test but should be passed into constructor of class under test and so on.
  • mock - clever stubs. They could check whether the certain method have been called and what arguments were used. Those objects are used to check if the target object interacts with its dependencies correctly.
  • fake - that is, usually, object, that has some functionality - just enough for testing.
 The first framework to be considered - Rhino Mocks.

May 5, 2013

The first post


As the header says, this is the first post in this blog. I plan to write about software development and everything around, the aim is to learn to use blog posting for self-development.
Since I want to use blog for obtaining skills in writing, I need some constraints not to throw writing away after few several postings. The constraint would be to create new blog entry at least once a week.
Today is Sunday and the next week starts tomorrow :)