How to test a writeonly property - rhino-mocks

In my application, using MVP pattern, presenter is setting some properties on view.For example, Iview has string Customer {set;}.Now, I want to test that this property was set with some value "x".How can I do the test with rhino mocks?

Don't define write-only properties. As the .NET design guidelines say:
Do not provide set-only properties.
If the property getter cannot be provided, use a method to implement the functionality instead. The method name should begin with Set followed by what would have been the property name. For example, AppDomain has a method called SetCachePath instead of having a set-only property called CachePath.
In most cases, defining a read/write property is much easier, and it makes it a breeze to unit testi the owning type. You wouldn't need Rhino Mocks for that, as you can simply read the value directly from the property.
However, if you rather want a mutating method as described in the design guidelines, you must make it virtual to be able to use Rhino Mocks to verify that it was correctly called. Although this is certainly possible, it's more complicated to set up, so I would only take that route if there were compelling reasons to do so.

Related

Registering all classes that inherit from a particular abstract class in Kotlin

I have a singleton object called registry.
I also have an abstract base class, say Operation with an abstract field called name. I expect other people to subclass this abstract class and create classes denoting specific operations. I want to be able to store name -> Subclass mapping in my registry object.
Ideally, people who subclass this will not even know about this registration. But if that is unavoidable, I prefer them to write as little code as possible just next to their class declaration.
What is the best way of doing this?
The issue here is name being abstract.
If name were a constructor parameter, then you could simply put the code in the your abstract class's constructor. Every subclass, sub-subclass,… instance will call that constructor (directly or indirectly), so it would always get called. (That doesn't apply to a few special cases such as deserialisation and cloning, so you might have to handle those explicitly.)
However, your abstract class's constructor will get called before the sub(sub…)class constructor(s), and so the instance won't be fully initialised and its name property might not be available yet.
The options I see are:
Refactor your class so that the name is a constructor parameter (and can't be changed thereafter), and add your code to the constructor. (If that restriction is feasible, then this is the simplest solution, both for you and for implementers of subclasses, who won't need to do anything extra.)
Provide a method that subclasses can call once the name has been set up. (You'll have to make it clear in the documentation that subclasses must call that method; unfortunately, I don't know of any way to enforce it.)
It may be possible to use annotations and compiler plug-ins and/or runtime libraries, similar to frameworks such as Spring. But I don't know the details, and that's likely to take much more work; it may also need your implementers to add plug-ins and/or libraries to their project, so probably isn't worth it unless you're doing a lot of other frameworky stuff too.
In each case, you can get the name value and the concrete subclass (using this::class or this::class.java), and store them in your registry. (It doesn't look like you're asking about the internals of the registry; I assume you have that side of things covered.)

setting/getting object's property value directly or by method?

This is more general question to any OOP, please before answer consider readability and efficiency.
Here is example in Javascript:
function fnc () {
this.var = "abc";
this.setVar = function (val) {
this.var = val;
}
this.getVar = function () {
return this.var;
}
}
Now, i can set value of var via method:
fnc.setvar("abc");
or
fnc.var = "abc";
I can also get it directly:
console.log(fnc.var)
or via get method:
console.log(fnc.getVar())
Here comes the question:
If the result is the same which option is better? what are the pros and cons for direct or method way?
This highly depends on the features and patterns used in a given language.
Behaviour driven languages
In Java or C++ classes are defined by their behaviour, read "methods". The interfaces and the whole inheritance are based on methods. Fields are 2nd class citizens. Therefore you use methods to get and set attributes. This is the only way of overriding the access and ensuring the integration is correct after you change something later on. Having all fields hidden behind methods also enables you finer grained control (for example getter without a corresponding setter, or a setter that does a calculation instead of simply setting an attribute), but you need a lot of boilerplate, so you write lots of code that does not really add to your business logic and makes the code harder to read from within the class. What makes the code harder to read, however, makes it easier to understand from the client-side through interfaces, as they fully define a class. This concept of methods over attributes usually comes along with visibility settings for methods and attributes. This way you define what is meant for outside world and what is meant for this class or package only. Attributes are almost always private (read "for this class only").
Property driven languages
In languages like JavaScript or Python classes/objects are defined by their fields, read "attributes". Even methods are nothing more than attributes and so both methods and attributes can be overriden (or hidden), switched at runtime etc. Given that you gain nothing but false security using getters and setters, and given that every function call less means better performance and shorter stacktrace, using fields directly is the preferred usage in scripting languages. Regarding readability: the code itself is much easier to read and to understand, but interfaces as known from behaviour based languages don't exist here except in form of documentation (if the code author writes one). Visibility of methods and attributes is usually always public, but some languages offer special annotations or naming schemas to show which methods or fields are meant to be private. There is no strong or no enforcement at all though.
BTW-JFYI: Python has a special solution for the extendability of fields: properties. This is a special thing which enables you using getter and setter with proper logic inside the class but present the field as plain attribute to the outside world. See Python #property versus getters and setters for further reading.
Don't consider the immediate result only. Most software is going to be modified at some point. Considering that, you are more flexible when using getter and setter methods as opposed to direct attribute access.
However the best option - if applicable - is to not use setters at all but create immutable objects.

Simple setter function or set with a property?

Just curious to know what difference does it make if one uses a setter function or a property to set a value? Which of the above two should be preferred?
column.setWidth(10);
column.width = 10;
Well, that largely depends on what programming language you are using, or, in other words, whether it supports the concept of properties or not. However, lets look at the problem from a general perspective.
The very basic point of view is properties are just plain syntactic sugar, making reading and writing values to some assumed backing field easier and, which is the important point, defining a clear contract for your code's user. Assumed because there needs not be any backing field at all or they can be many.
The high-level semantic difference between a setter function and a native property setter can be thought as follows:
A setter function is primarily still a function, hence the reader assumes it executes certain action using its arguments; being actually a setter is then just a convention.
A native property setter is primarily a way to write a value into some assumed backing storage / into the backing object; there's no implied notion of executing an action even though the hidden implementation details of the setter may work like that.
Many practicle ramifications of using property accessors (getters and setter) were discussed in this question and its answers.
Prefer properties. Actually it depends on your language. If you develop Python that all attributes are public in Python.

OOP confusion in classes

I am from a C# background and have been doing programming for quite some time now. But only recently i started giving some thoughts on how i program. Apparently, my OOP is very bad.
I have a few questions maybe someone can help me out. They are basic but i want to confirm.
1- In C#, we can declare class properties like
private int _test;
and there setter getters like
public int Test {get; set;}
Now, lets say i have to use this property inside the class. Which one will i use ? the private one or the public one ? or they both are the same ?
2- Lets say that i have to implement a class that does XML Parsing. There can be different things that we can use as input for the class like "FILE PATH". Should i make this a class PROPERTY or should i just pass it as an argument to a public function in the class ? Which approach is better. Check the following
I can create a class property and use like this
public string FilePath {get; set;}
public int Parse()
{
var document = XDocument.Load(this.FilePath);
.........//Remaining code
}
Or
I can pass the filepath as a parameter
public int Parse(string filePath)
On what basis should i make a decision that i should make a property or i should pass something as argument ?
I know the solutions of these questions but i want to know the correct approach. If you can recommend some video lectures or books that will be nice also.
Fields vs Properties
Seems like you've got a few terms confused.
private int _test;
This is an instance field (also called member).
This field will allow direct access to the value from inside the class.
Note that I said "inside the class". Because it is private, it is not accessible from outside the class. This is important to preserve encapsulation, a cornerstone of OOP. Encapsulation basically tells us that instance members can't be accessed directly outside the class.
For this reason we make the member private and provide methods that "set" and "get" the variable (at least: in Java this is the way). These methods are exposed to the outside world and force whoever is using your class to go trough your methods instead of accessing your variable directly.
It should be noted that you also want to use your methods/properties when you're inside the current class. Each time you don't, you risk bypassing validation rules. Play it safe and always use the methods instead of the backing field.
The netto result from this is that you can force your logic to be applied to changes (set) or retrieval (get). The best example is validation: by forcing people to use your method, your validation logic will be applied before (possibly) setting a field to a new value.
public int Test {get; set;}
This is an automatically implemented property. A property is crudely spoken an easier way of using get/set methods.
Behind the scenes, your code translates to
private int _somevariableyoudontknow;
public void setTest(int t){
this._somevariableyoudontknow = t;
}
public int getTest(){
return this._somevariableyoudontknow;
}
So it is really very much alike to getters and setters. What's so nice about properties is that you can define on one line the things you'd do in 7 lines, while still maintaining all the possibilities from explicit getters and setters.
Where is my validation logic, you ask?
In order to add validation logic, you have to create a custom implemented property.
The syntax looks like this:
private int _iChoseThisName;
public int Test {
get {
return _iChoseThisName;
}
set {
if(value > 5) { return _iChoseThisName; }
throw new ArgumentException("Value must be over 5!");
}
}
Basically all we did was provide an implementation for your get and set. Notice the value keyword!
Properties can be used as such:
var result = SomeClass.Test; // returns the value from the 'Test' property
SomeClass.Test = 10; // sets the value of the 'Test' property
Last small note: just because you have a property named Test, does not mean the backing variable is named test or _test. The compiler will generate a variablename for you that serves as the backing field in a manner that you will never have duplication.
XML Parsing
If you want your second answer answered, you're going to have to show how your current architecture looks.
It shouldn't be necessary though: it makes most sense to pass it as a parameter with your constructor. You should just create a new XmlParser (random name) object for each file you want to parse. Once you're parsing, you don't want to change the file location.
If you do want this: create a method that does the parsing and let it take the filename as a parameter, that way you still keep it in one call.
You don't want to create a property for the simple reason that you might forget to both set the property and call the parse method.
There are really two questions wrapped in your first question.
1) Should I use getters and setters (Accessors and Mutators) to access a member variable.
The answer depends on whether the implementation of the variable is likely to change. In some cases, the interface type (the type returned by the getter, and set by the setter) needs to be kept consistent but the underlying mechanism for storing the data may change. For instance, the type of the property may be a String but in fact the data is stored in a portion of a much larger String and the getter extracts that portion of the String and returns it to the user.
2) What visibility should I give a property?
Visibility is entirely dependent on use. If the property needs to be accessible to other classes or to classes that inherit from the base class then the property needs to be public or protected.
I never expose implementation to external concerns. Which is to say I always put a getter and setter on public and protected data because it helps me ensure that I will keep the interface the same even if the underlying implementation changes. Another common issue with external changes is that I want a chance to intercept an outside user's attempt to modify a property, maybe to prevent it, but more likely to keep the objects state in a good or safe state. This is especially important for cached values that may be exposed as properties. Think of a property that sums the contents of an array of values. You don't want to recalculate the value every time it is referenced so you need to be certain that the setter for the elements in the array tells the object that the sum needs to be recalculated. This way you keep the calculation to a minimum.
I think the second question is: When do I make a value that I could pass in to a constructor public?
It depends on what the value is used for. I generally think that there are two distinct types of variables passed in to constructors. Those that assist in the creation of the object (your XML file path is a good example of this) and those that are passed in because the object is going to be responsible for their management. An example of this is in collections which you can often initialize the collection with an array.
I follow these guidelines.
If the value passed in can be changed without damaging the state of the object then it can be made into a property and publicly visible.
If changing the value passed in will damage the state of the object or redefine its identity then it should be left to the constructor to initialize the state and not be accesible again through property methods.
A lot of these terms are confusing because of the many different paradigms and languages in OO Design. The best place to learn about good practices in OO Design is to start with a good book on Patterns. While the so-called Gang of Four Book http://en.wikipedia.org/wiki/Design_Patterns was the standard for many years, there have since been many better books written.
Here are a couple resources on Design Patterns:
http://sourcemaking.com/design_patterns
http://www.oodesign.com/
And a couple on C# specific.
http://msdn.microsoft.com/en-us/magazine/cc301852.aspx
http://www.codeproject.com/Articles/572738/Building-an-application-using-design-patterns-and
I can possibly answer your first question. You asked "I have to use this property inside the class." That sounds to me like you need to use your private variable. The public method which you provided I believe will only do two things: Allow a client to set one of your private variables, or to allow a client to "see" (get) the private variable. But if you want to "use this property inside the class", the private variable is the one that should be your focus while working with the data within the class. Happy holidays :)
The following is my personal opinion based on my personal experience in various programming languages. I do not think that best practices are necessarily static for all projects.
When to use getters, when to use private instance variables directly
it depends.
You probably know that, but let's talk about why we usually want getters and setters instead of public instance variables: it allows us to aquire the full power of OOP.
While an instance variable is just some dump piece of memory (the amount of dumbness surely depends on the language you're working in), a getter is not bound to a specific memory location. The getter allows childs in the OOP hirarchy to override the behaviour of the "instance variable" without being bound to it. Thus, if you have an interface with various implementations, some may use ab instance variable, while others may use IO to fetch data from the network, calculate it from other values, etc.
Thus, getters do not necessarily return the instance variable (in some languages this is more complicated, such as c++ with the virtual keyword, but I'll try to be language-independent here).
Why is that related to the inner class behaviour? If you have a class with a non-final getter, the getter and the inner variable may return different values. Thus, if you need to be sure it is the inner value, use it directly. If you, however, rely on the "real" value, always use the getter.
If the getter is final or the language enforces the getter to be equal (and this case is way more common than the first case), I personally prefer accessing the private field directly; this makes code easy to read (imho) and does not yield any performance penalty (does not apply to all languages).
When to use parameters, when to use instance variables/properties
use parameters whereever possible.
Never use instance variables or properties as parameters. A method should be as self-contained as possible. In the example you stated, the parameterized version is way better imo.
Intance variables (with getters or not) are properties of the instance. As they are part of the instance, they should be logically bound to it.
Have a look at your example. If you hear the word XMLParser, what do you think about it? Do you think that a parser can only parse a single file it is bound to? Or do you think that a parser can parse any files? I tend to the last one (additionally, using an instance variable would additionally kill thread-safety).
Another example: You wish to create an XMLArchiver, taking multiple xml documents into a single archive. When implementing, you'd have the filename as a parameter of the constructor maybe opening an outputstream towards the file and storing a reference to it as an instance variable. Then, you'd call archiver.add(stuff-to-add) multiple times. As you see, the file (thus, the filename) is naturally bound to the XMLArchiver instance, not to the method adding files to it.

When to use private methods?

I understand what public/protected/private accessors mean in Java or PHP for instance. However, when would you choose whether to make a method private?
Imagine I have a class that handles configuration strings - they must conform to a particular regular expression, and if so, further logic is performed to make sure the strings are valid.
I currently have this code in a private method in a Configuration class. This class accepts configuration strings and then returns values to client code after validating the strings.
However, I want to unit test the validation code, so perhaps it should be in another class. I typically don't do this though unless I know that the code will be reused. If it will only be used by a single class as in this case, I normally just make the method private.
So, my question is - what design rules should inform a programmer that a particular method should be private compared to being moved into its own class?
The Single Responsibility Principle is what I usually have in mind. Also, consider if you really need the validation in this class or if it does not have anything to do with it (perhaps the validation should not be handled in the domain logic but another layer above it).
Private methods, as you probably already know should not be tested in unit tests so if you really need to test this kind of functionality perhaps you should put it in its own validation class, responsible for validation only and then test it.
Then if function i use only local in object and i don't want show to other objects her because i can use her in future and make mistake and this will do some mess in my code i don't must thinking a lot to think what function i must use and what i can't use.
I using private method everywhere and doing some simple and short public methods to get/set data to my objects then i don't have mess in my code.
You should use private method when you are refactoring your code in class.
for example if you have some peace of code that repeats more than one in code.
you should to make extract method refactoring.
look at more refactoring methods
refactor
Implement you validation logic as a strategy as in the strategy pattern. This way you can not only unit test them separately but also replace the validation logic later on easily if and when required.
So make a separate Validator class which implements IValidator interface. Then compose your Configuration class with the appropriate Validator by injecting it as a dependency in Configuration's constructor.
Leave the private validation methods in the same class, and make the unit test class a friend of that class (in C++, at least--in Java, put the unit test in the same package).
Read more about SOLID design principles
SOLID
If no special requirement, keep members as private. I think its main purpose is to make better "encapsulation" and maintenance.
For example, you define a Car.class with different steer mode. Car(.class) has a member maxSpeed, which is setted by a setter: Car.maxSpeedSet(int mode). then the user cannot directly know or change the value for maxSpeed, except by changing its mode through the method.
In this way, users don't need to care or write a function about how maxSpeed is got from the mode. And when you need to change the function: maxSpeed = f(mode), you don't have to change it everywhere the Car is used. you just change the method maxSpeedSett(). perfect for encapsulation and maintenance, isn't it?
if a member is only: x= a, 'public' seems good enough but make sure you will not change the method of assigning in the future, especially when there are too many dependance on the class.