Returning early from a function - language-agnostic

I'm having a mental block, can someone remind me what the correct term for returning early from a function is, i.e.
private MyObject DoSomeStuff(string myValue)
{
//What is this called?!?!?
if(myValue == string.Empty)
return null;
MyObject obj = new MyObject();
obj.Value = myValue;
return obj;
}

I believe it's called a guard clause.

I would potentially call this an Interrupt. Or, simply, and Early Return. Break might work, too.

I would call it a "precondition test".

Related

Play framework: call GET from server side

This might be a silly question. I am beginner in Play Framework.
I have one controller which is called as below
GET /getData someController.getData()
And controller is implemented as below
Result someController() {
SomeObject obj = new SomeObject();
obj.prop1 = "Something";
obj.prop2 = "Something";
return ok(Json.toJson(obj));
}
Now, I have another controller in which I need to call this method and get the response body say, value of obj.prop1.
I need to do to something like this
String s = someController().prop1;
In short words I need to get access to JSON object of response sent by someController.
I have not shown the full code, but you'll get what I meant.
Create one private method, which handle you logic. There is no need to call controller, call the private method from controllers.
private SomeObject someMethod(){
SomeObject obj = new SomeObject();
obj.prop1 = "Something";
obj.prop2 = "Something";
return obj
}
Result someController1(){
SomeObject obj = someMethod();
}
Result someController2(){
SomeObject obj = someMethod();
}

How can I find out what argument was given to a mocked method?

If I write something like this:
verify().that( mockPromise.handleFault( any() ))
it works fine to tell me that 'handleFault' was invoked.
But later I want to invoke the fault handler function that was passed in. The handler will be a private function so there isn't another way to access it.
In Java Mockito, the feature you're looking for is called ArgumentCaptor. In short, it's a special kind of Matcher (like any()) that matches any type of object and keeps the object it "matches" in a variable.
Unfortunately, it looks like it's not available in Flex yet.
The good news is that if you feel like it, you can probably write an implementation of the Matcher interface that does exactly that--save its most recent value and return true--in fifteen minutes or so. :)
Good luck!
Based on Jeff's answer, I did this:
import org.mockito.api.Matcher;
class ArgumentCaptor implements Matcher
{
private var _value:*;
public function ArgumentCaptor()
{
}
public function get value():*
{
return _value;
}
public function describe():String
{
return "";
}
public function matches(value:*):Boolean
{
_value = value;
return true;
}
}
which can be used like:
var argCaptor:ArgumentCaptor = new ArgumentCaptor();
verify().that( mockPromise.handleFault( argThat(argCaptor) ));
argCaptor.value; // the argument

Is it possible to register an open generic delegate in autofac?

I want to register a generic delegate that resolves itself at runtime, but I cannot find a way to do this on generics.
Given a delegate that looks like this:
public delegate TOutput Pipe<in TInput, out TOutput>(TInput input);
And given a discretely registered delegate that look like this:
public class AnonymousPipe<TInput, TOutput>
{
public Pipe<TInput, TOutput> GetPipe(IContext context)
{...}
I want to register a function along the lines of this:
builder.RegisterGeneric(typeof(Pipe<,>)).As(ctx =>
{
var typeArray = ctx.RequestedType.GetGenericArguments();
// this can be memoized
var pipeDefinition = ctx.Resolve(typeof(AnonymousPipe<,>).MakeGenericType(typeArray));
return pipeDefinition.GetPipe(ctx);
I cannot find a way to provide an implementation of the generic as a parameter in Autofac - I may just be missing something. I know I can do this through a generic object or interface, but I want to stick with the lightness of a delegate. It makes unit testing super simple on the injection of these.
Any thoughts? I am having to do discrete registrations at the moment(one per type combination and no generics).
I can only come up with the registration source solution (the universal hammer in Autofac.)
class PipeSource : IRegistrationSource
{
public bool IsAdapterForIndividualComponents { get { return true; } }
public IEnumerable<IComponentRegistration> RegistrationsFor(
Service service,
Func<Service, IEnumerable<IComponentRegistration>> registrationAccessor)
{
var swt = service as IServiceWithType;
if (swt == null || !swt.ServiceType.IsGenericType)
yield break;
var def = swt.ServiceType.GetGenericTypeDefinition();
if (def != typeof(Pipe<,>))
yield break;
var anonPipeService = swt.ChangeType(
typeof(AnonymousPipe<,>).MakeGenericType(
swt.ServiceType.GetGenericArguments()));
var getPipeMethod = anonPipeService.ServiceType.GetMethod("GetPipe");
foreach (var anonPipeReg in registrationAccessor(anonPipeService))
{
yield return RegistrationBuilder.ForDelegate((c, p) => {
var anon = c.ResolveComponent(anonPipeReg, p);
return getPipeMethod.Invoke(anon, null); })
.As(service)
.Targeting(anonPipeReg)
.CreateRegistration();
}
}
}
Then:
builder.RegisterSource(new PipeSource());
Now, I'm certain that I can't type that code into a web page and have it actually compile and run, but it might come close :)

Passing multiple Include statements into a repository?

I am trying to figure out a way to pass a collection of include statements into my repository so that I can have it include specific entities. Below is some sample code from my repository.
public TEntity GetById(Guid id)
{
return id != Guid.Empty ? GetSet().Find(id) : null;
}
private IDbSet<TEntity> GetSet()
{
return _unitOfWork.CreateSet<TEntity>();
}
The GetByID method calls the GetSet to return the entity set. I was thinking, if I could somehow pass in a collection of entities to include (via an expression) as part of my GetById, this way I wouldn't have to expose the GetSet to my services. So, something like this:
var entity = _repository.GetById(theId, e => {e.Prop1, e.Prop2, e.Prop3});
I could then pass that expression into my GetSet method and pass it into an include statement. Thoughts?
I have done something like this in my code recently. Would the following work for you?
public TEntity GetById(Guid id, params Expression<Func<TEntity, object>>[] includeProperties)
{
if (id == Guid.Empty) return null;
var set = _unitOfWork.CreateSet<TEntity>();
foreach(var includeProperty in includeProperties)
{
set.Include(includeProperty);
}
return set.First(i => i.Id == id);
}
Then you would call it like this...
var entity = _repository.GetById(theId, e => e.Prop1, e=> e.Prop2, e=> e.Prop3);
I know this doesn't exactly follow your pattern, but I think you could refactor it as required.
I don't think Paige Cook's code will work quite as shown.
I've included a modified version of the code that should work instead:
public TEntity GetById(Guid id, params Expression<Func<TEntity, object>>[] includeProperties)
{
if (id == Guid.Empty) return null;
IQueryable<TEntity> set = _unitOfWork.CreateSet<TEntity>();
foreach(var includeProperty in includeProperties)
{
set = set.Include(includeProperty);
}
return set.First(i => i.Id == id);
}
I only spotted this by tracing the SQL generated by Entity Framework, and realised the original code was only giving the illusion of working, by using lazy-loading to populate the entities specified for inclusion.
There's actually a more terse syntax for applying the Include statements using the LINQ Aggregate method, which is in the blog post linked to. My post also improves the method slightly by having a fall-back to the Find method, when no includes are needed and also shows an example of how to implement a "GetAll" method, using similar syntax.
It's bad idea to store context in non-local space, for many reasons.
I modify Steve's code and get this for my ASP.NET MVC projects:
public aspnet_User FirstElement(Func<aspnet_User, bool> predicate = null, params Expression<Func<aspnet_User, object>>[] includes)
{
aspnet_User result;
using (var context = new DataContext())
{
try
{
var set = context.Users.AsQueryable();
for (int i = 0; i < includes.Count(); i++ )
set = set.Include(includes[i]);
if (predicate != null)
result = set.ToList().FirstOrDefault(predicate);
else
result = set.ToList().FirstOrDefault();
}
catch
{
result = null;
}
}
return result;
}
The include method can be strung together in your linq query like so:
var result = (from i in dbContext.TableName.Include("RelationProperty")
.Include("RelationProperty")
.Include("RelationProperty")
select i);

Best practice for interface with a getter function that could return multiple types

I have several data manipulation widgets that all implement a custom IPropertyEditor interface. I would like to include a GetValue getter, but the return types could be String, Boolean or int, off the top of my head. In AS3, all of that inherits from Object, so I could have GetValue return an object, but I don't feel great about that approach. At the risk of asking a subjective question, does anyone have any recommendations on how to approach this?
In ActionScript I'm pretty sure you can set a variable return type by defining a function in the following way:
public function getValue():* {
return "Any of these would be fine.";
return true;
return 1;
return new Sprite();
}
Hope that helps.
In practice, there is an actual getter/setter model in ActionScript. For your case, you could use it like this:
private var _value:*;
public function get value() : * {
return _value;
}
public function set value(val:*) : void {
if (typeof val == "int" || typeof val == "boolean" || typeof val == "string") {
_value = val;
}
}
This limits the user to setting (per your requirements) the value of this "value" property to data types int, Boolean, or String.