I'd like to know what's the default approach for those times when you need a variable to have been set in order for a given method/another variable initialization to work.
Like this:
Everything works if I initialize var A after var B. But not the other way around. I wrote the constructor, so I'll do that myself, but I'm not really sure where the code that tests for var B's existence should be. Or even if it should exist at all, for I have written the constructor and I initialize the values the order I see fit, but I feel it's a little insecure because it is not very robust in case anything changes.
Mind you, I'm talking about instance variables, if that helps.
FA
The answer can be influenced by the reason why a must be set before b.
Explicit Object Dependencies
If the reason is that b depends upon a, then the simplest thing to do is to make that dependency explicit at the time that b is created. For example, if a and b were objects then:
var a = new A(...);
var b = new B(a, ...);
var op = new Operation(b);
op.perform();
In this way, it is not possible to initialize the objects out of order. Note that A and B could be newly introduced wrapper objects that contain the original operation parameters.
Fluent Interface
If the reason is that the operation itself must know the value of a in order to perform some configuration in preparation for the arrival of b, then the operation constructor could be replaced by a fluent interface:
Operation op = Operation.withA(a).withB(b);
op.perform();
We must take care to define this fluent interface in such a way that withB can only be called after withA has been called. For example:
public class Operation {
private final C _c;
private final B _b;
private Operation(C c, B b) {
_c = c;
_b = b;
}
public static BStep withA(final A a) {
return new BStep() {
public Operation withB(B b) {
C c = setUpStateDependentUponA(a);
return new Operation(c, b);
}
};
};
public interface BStep {
Operation withB(B b);
}
public void perform() {
// do something with _c and _b
}
}
Here, C has been introduced to capture that state that is dependent upon a alone prior to the arrival of b. Note how the constructor of Operation is not visible to client code and that withB cannot possibly be called until after withA has been called.
I check before each time I access the variable, but if it is an instance variable and you initialize B in the constructor you should be safe. I use something like-
if (isset(var B)
{ do something with var A }
else
{ error handler }
or
try
{
if (isset(var B))
do something with a;
else
throw new Exception("attribute B has not been set.");
}
catch (Exception $e)
{
echo $e->getMessage();
return NULL;
}
Related
I want a particular function to be executed and return a value to another SWC in AUTOSAR architecture. for example :
SWC-1
boolean operation(int a, int b)
{
if (a == b)
return true;
else
return false;
}
SWC - 2
int main()
{
int a = 2, b = 3;
boolean ret = false;
ret = operation(2,3);
if(ret == true)
{
//perform some activity
}
}
I want to a perform operation function call in SWC-2. The function is defined in SWC-1. In AUTOSAR architecture, how can i configure these functions? Can i do it as sender receiver method or client- server method ? Which is the best way to design in AUTOSAR ?
This is obviously a case for client/server communication. The function operation has to be modeled as a ClientServerOperation inside a ClientServerInterface. Also, an RPortPrototype (typed by the ClientServerInterface) is required to exist on SWC2 for calling the operation using the Rte_Call API for calling the operation.
The server side is a bit more complicated to configure and it would take some effort to explain everything in detail. I‘d recommend having a look at the AUTOSAR specification documents „TPS Software Component Template“ and „SWS RTE“ to understand how the interaction between the software-components works.
I would like to ask for a help and suggestions what is a correct approach in my case (probably its easy but I'm just starting with JUnit). Here is a part of my code
public boolean arrayListEmpty()
{
if(numericalSequence.isEmpty() == true)
return true;
else
return false;
}
This is a public method from model which I suppose i should test, it's just returning true if my numericalsequence is empty as you can see. I cant check it directly invoking numericalSequence.isEmpty (in controller where I need it) because it is private.
So obvious thing is to check
assertEquals(true, test.arrayListEmpty());
So my question is about suggestions what other asserts should I use/what cases should I predict which can come out. Should I in Test method fill numericalSequence with some values and assert it also? (for me its not necessary because any value inserted into sequence = not null but maybe it is not so easy)
First of all, welcome to Stack Overflow!
Looking at your question, it sounds like you're new to unit-testing (correct me if I'm wrong). So, I'll break my answers in to two sections; (1) answering your question, and (2) to give a general direction of how to write good tests and testable classes.
1. Answering your question
There are a couple more use cases you can think of here:
What happens if numericalSequence is null?
What if numericalSequence has 1 element?
What if numericalSequence has a null element?
Some of the cases above may not be possible depending on how your class is set up, but it's a test worth having so that any changes to the class that violates the "previously agreed behavior" of one of these test cases would fail.
2. Writing good tests
There are no strict guidelines on what to do in order to write good tests, however, if you structure your code to be testable, you'll find that writing good tests becomes easier, and would be less of chore. Allow me to explain.
NOTE: This is not a comprehensive guide, but is meant to start your journey in to the path of how to write better code, and better tests
So assume a class that needs to be tested is written like this:
class MyClass {
// NOTE: This is not `final`
private List<Integer> numericalSequence;
public MyClass() {
this.numericalSequence = new ArrayList<>();
}
public void doSomething(Integer x) {
if (x < 0) {
numericalSequence = new ArrayList<>();
} else {
numericalSequence.add(2 * x);
}
}
public boolean arrayListEmpty() {
// NOTE: Your sample code can be reduced to this one-liner
return numericalSequence.isEmpty();
}
}
Here are some of the flaws in the above code:
doSomething method allows nullable (boxed integer) values and so can cause NullPointerException in the first if statement.
The numericalSequence member is not final and hence the code that sets it to null is valid inside the doSomething method
The arrayListIsEmpty method does not check if numericalSequence is null
If I want to test how arrayListIsEmpty behaves when numericalSequence is null, or has null elements, it is hard to do so, unless you know how to get the class to that state.
If the class was re-written to the following:
class MyClass {
private final List<Integer> numericalSequence;
public MyClass() {
this(new ArrayList<>());
}
// Should be made public only if the classes that use this one needs to
// initialize this instance with the sequence. Make this package-private
// otherwise.
public MyClass(List<Integer> sequence) {
this.numericalSequence = sequence;
}
public void doSomething(int x) {
if (x < 0) {
// COMPILE ERROR: Cannot assign to a final member
// numericalSequence = new ArrayList<>();
numericalSequence.clear();
} else {
numericalSequence.add(2 * x);
}
}
public boolean arrayListEmpty() {
return numericalSequence == null || numericalSequence.isEmpty();
}
}
A few things to note about the above structure:
There are two constructors; the default invokes the one that takes a list of integers as the sequence, so that it reuses any logic that both would need to share. There are no logic in this example, but hopefully you'll come across one soon.
The doSomething() method doesn't accept Integer value, but int value that makes sure that x is never null (Java numerical primitive types cannot be null). This also means, numericalSequence cannot contain null values through doSomething().
Since numericalSequence can be initialized from outside of this class, the arrayListEmpty() method makes sure to check that numericalSequence is either null is truly empty.
Now you can write test cases like so:
#Test
public void arrayListEmpty_WhenListIsNull() {
MyClass test = MyClass(null);
assertTrue(test.arrayListEmpty());
}
#Test
public void arrayListEmpty_WhenListIsEmpty() {
MyClass test = MyClass();
assertTrue(test.arrayListEmpty());
}
#Test
public void arrayListEmpty_WhenListHasOnlyOneNonNullElement() {
List<Integer> sequence = new ArrayList<>();
sequence.add(0);
MyClass test = new MyClass(sequence);
assertFalse(test.arrayListEmpty());
}
#Test
public void arrayListEmpty_WhenListHasOnlyOneNullElement() {
List<Integer> sequence = new ArrayList<>();
sequence.add(null);
MyClass test = new MyClass(sequence);
assertFalse(test.arrayListEmpty());
}
Since doSomething() adds/clears the sequence, when writing tests for doSomething() make sure the call and verify the state of the class by checking the return value of arrayListEmpty().
For example:
#Test
public void doSomething_WhenInputLessThanZero() {
List<Integer> sequence = new ArrayList<>();
sequence.add(0);
MyClass test = new MyClass(sequence);
test.doSomething(-1);
assertTrue(test.arrayListEmpty());
}
My intention was to show a couple of things:
Structure your tests cases to be small and concise
Design your class to be easily testable
Hope this helps.
When using Castle.Facilities.AutoTx facility with [Transaction(TransactionScopeOption.RequiresNew)] attribute, the expected new System.Transactions.CommittableTransaction is not created.
You can easily test it with the following unit test
using System.Transactions;
using Castle.Facilities.AutoTx.Testing;
using Castle.MicroKernel.Registration;
using Castle.Transactions;
using Castle.Windsor;
using NUnit.Framework;
namespace Castle.Facilities.AutoTx.Tests
{
public class TransService
{
private readonly NewTransService _s2;
public TransService(NewTransService s2)
{
_s2 = s2;
}
[Transaction]
public virtual string DoInTrans()
{
var currentTransaction = System.Transactions.Transaction.Current;
Assert.That(currentTransaction != null, "The current transaction mustn't be null.");
string transId = currentTransaction.TransactionInformation.LocalIdentifier;
_s2.DoInNewTrans(transId);
return transId;
}
}
public class NewTransService
{
[Transaction(TransactionScopeOption.RequiresNew)]
public virtual string DoInNewTrans(string parentTransId)
{
var currentTransaction = System.Transactions.Transaction.Current;
Assert.That(currentTransaction != null, "The current transaction mustn't be null.");
string transId = currentTransaction.TransactionInformation.LocalIdentifier;
Assert.AreNotEqual(parentTransId, transId, "Ambient transaction must differ from parent");
return transId;
}
}
public class SingleThread_NewAmbient
{
private WindsorContainer _Container;
[SetUp]
public void SetUp()
{
_Container = new WindsorContainer();
_Container.AddFacility<AutoTxFacility>();
_Container.Register(Component.For<TransService>());
_Container.Register(Component.For<NewTransService>());
}
[TearDown]
public void TearDown()
{
_Container.Dispose();
}
[Test]
public void Automatically_Starts_New_CommitableTransaction()
{
using (var scope = new ResolveScope<TransService>(_Container))
scope.Service.DoInTrans();
}
}
}
Am I misunderstanding the purpose of [Transaction(TransactionScopeOption.RequiresNew)] or is it a bug?
I have been digging into the Castle.Transactions source code and I was able to fix the behavior by changing following piece of code in Castle.Transactions.TransactionManager.ITransactionManager.CreateTransaction(ITransactionOptions transactionOptions):
if (activity.Count == 0)
tx = new Transaction(new CommittableTransaction(new TransactionOptions
...
to
if (activity.Count == 0 || transactionOptions.Mode == TransactionScopeOption.RequiresNew)
tx = new Transaction(new CommittableTransaction(new TransactionOptions
...
Can someone from Castle experts / owners check this?
Author here,
I think your code is great and would merge a PR with it if it doesn't break other tests. =)
The reason that RequiresNew isn't well supported is because it's in 99% of the cases an anti-pattern. You're after encapsulating your unit of work in a transaction; and your unit of work should correspond 1-1 with the business operation that should be consistent.
Now, if you have a transaction going on the current thread, like you'd have in your case if you need to use 'RequiresNew', then you're either after reading dirty data or spawning an unrelated transaction (from a business-operation perspective). Hence, you should be doing it in another thread.
Since transactions are 'ambient' and not explicit in the control flow in a programming language like C#, you're left with your 'call context slots' to save the transaction reference in; but from your code's point of view these don't exist; what you have are partial functions that only work in a transactional context. If you spawn a second transaction; how are you going to coordinate that with the current transaction? It's hard; and likely to lead to problems.
An aside
In other transactional systems, like geteventstore.com you get an explicit transaction identifier -- you have one in System.Transactions, too, but it's not explicit in the API/ABI/ADO.Net to the database, hence you can't use it the same way. With an explicit transaction identifier you can solve failures when it becomes 'in doubt', i.e. the 'generals problem'; you can't with System.Transactions. Instead you must mount the transaction MMC on the DTC in question and manually roll it back or forward.
Castle Windsor passes the registered concrete type to Controller's constructors. A typical implementation (no pun intended) is:
private readonly IDepartmentRepository _deptsRepository;
public DepartmentsController(IDepartmentRepository deptsRepository)
{
if (deptsRepository == null)
{
throw new ArgumentNullException("deptsRepository");
}
_deptsRepository = deptsRepository;
}
I need to pass the ctor a second parameter, if possible, so that I can pass that val on to the Repository constructor (I know: tramp data alert, but I don't know if there's a straightforward way around it:
public DepartmentsController(IDepartmentRepository deptsRepository, int DBInstance)
{
if (deptsRepository == null)
{
throw new ArgumentNullException("deptsRepository");
}
_deptsRepository = deptsRepository(DBInstance);
}
REPOSITORY
public DepartmentRepository(int dbInst)
{
string connStr = string.Format("Phoo{0}Bar", dbInst);
using (var conn = new OleDbConnection(connStr))
{
using (var cmd = conn.CreateCommand())
{
. . .
Is it possible to tweak what Castle Windsor sends to the Controller constructor this way? If so, how?
AND/BUT: For this to be of any value (to me, anyway), I need to be able to get the int val (that will be passed to the Controller) from the URL the client sends. IOW, if the client asks the server for data via:
http://locohost:4242/Platypus/GetAll/1
I need to pass a "1" as the second argument to PlatypusController.
If the user asks the server for data via:
http://locohost:4242/Platypus/GetAll/42
I need to pass a "42" as the second argument to PlatypusController.
etc.
This is what I did to solve my Controller/Repository data context Dilemma:
0) Added a database context argument to the Controller's routing attribute. IOW, this:
[Route("api/HHSUsers/GetAll")]
...got changed to this:
[Route("api/HHSUsers/GetAll/{dbContext=03}")]
1) Passed that database context arg to the Repository. To wit, this:
return _hhsusersrepository.GetAll();
...got changed to this:
return _hhsusersrepository.GetAll(dbContext);
...so that the Controller method is now:
[Route("api/HHSUsers/GetAll/{dbContext=03}")]
public IEnumerable<HHSUsers> GetAllHHSUsersRecords(int dbContext)
{
return _hhsusersrepository.GetAll(dbContext);
}
2) Changed the corresponding method in the Repository interface from:
IEnumerable<HHSUsers> GetAll();
...to this:
IEnumerable<HHSUsers> GetAll(string dbContext);
3) Changed the Repository method from this:
public HHSUsersRepository()
{
// All the data is loaded here in the ctor
}
public IEnumerable<HHSUsers> GetAll()
{
return hhsusers;
}
....to this:
public IEnumerable<HHSUsers> GetAll(string dbContext)
{
LoadHHSUsers(dbContext);
return hhsusers;
}
private void LoadHHSUsers(int dbContext)
{
string connStr = string.Format("Foo{0}Bar", dbContext);
// The same as previously from this point on, except that this:
// using (var conn = new OleDbConnection(#"Foo Bar Phoo Bar etc"...
// becomes:
// using (var conn = new OleDbConnection(connStr))
4) Tack the dbcontext val to the end of the URL when calling the method, so that it is this:
http://localhost:28642/api/HHSUsers/GetAll/42
...instead of this:
http://localhost:28642/api/HHSUsers/GetAll
If the data context to use is "03" I can omit the dbcontext arg from the URL, as 03 is the default value I set when I appended "=03" to the Controller's "dbContext" routing attribute arg.
I know some fancy-pants propeller-heads will find fault with this for some reason (for one reason because of the tramp data going here and there and everywhere like a hobo on steroids), but my response is the same as that of an athlete who is getting trash-talked by an opposing player and yet whose team is winning: just point at the scoreboard. IOW, this works for me, so that's pretty much all I care about. Style points are for runway models and, again, fancy-pants propeller-heads (AKA Star-Bellied Sneeches (as opposed to us plain
cats with the unstarred bellies)); see "The perfect is the enemy of the good."
This simple way has that self-same benefit -- of being (relatively) simple to grok and, thus, modify/refactor as necessary. Inelegant? Sure, but so was Joe Kapp.
Data is passed to a function "explicitly" whereas a method is "implicitly passed" to the object for which it was called.
Please could you explain the difference between these two ways of passing data? An example in java or c# would help.
The language Java and Python are good examples in illustrating this. In Python, the object is passed explicitly whenever a method of a class is defined:
class Example(object):
def method(self, a, b):
print a, b
# The variable self can be used to access the current object
Here, the object self is passed explicitly as the first argument. This means that
e = Example()
e.method(3, 4)
is effectively the same as calling method(e, 3, 4) if method were a function.
However, in Java the first argument is not explicitly mentioned:
public class Example {
public void method(int a, int b) {
System.out.println(a + " " + b);
// The variable this can be used to access the current object
}
}
In Java, it would be:
Example e = Example();
e.method(3, 4);
The instance e is passed to method as well but the special variable this can be used to access it.
Of course, for functions each argument is passed explicitly because each argument is mentioned in both the function definition and where the function is called. If we define
def func(a, b, c):
print a, b, c
then we can call it with func(1, 2, 3) which means all arguments are explicitly passed.
In this context a method can be considered to be a function that has access to the object it's bound to. Any properties of this object can be accessed from the method, even though they didn't appear in the signature of the function. You didn't specify a language, but let me give an example in PHP as it's pretty prevalent and easy to read even if you didn't use it.
Edit: the languages were added after I wrote this; maybe someone can translate this to one of those languages if needed.
<?php
/* Explicit passing to a function */
function f($a, b)
{
return $a + b;
}
// f(1, 2) == 3
class C
{
public $a, $b;
/* $a and $b are not in the parameter list. They're accessed via the special $this variable that points to the current object. */
public function m()
{
return $this->a + $this->b;
}
}
$o = new C();
$o->a = 1;
$o->b = 2;
//$o->m() == 3