How to write code for if there are two overlapping if conditions in code - coding-style

There are two functions isBusy and isSad. I want to implement the following logic in most readable and production ready way. But I am not sure if it is the ideal way to write code since the function isSad is called twice.
if isBusy
{
person.busy=true
if isSad
{
person.sad=true
}
return person
}
if isSad
{
person.sad=true
return person
}
// some code
return person

Are you after something like this?
person.busy = isBusy
person.sad = isSad
if person.busy or person.sad
{
return person
}
// run logic
return person

Related

Function that returns a bool result and show errors in case of a false return

I want to have a function that validate an object.
In case of a false result I want to know the reason why my object isn't valid.
This is a sample algorithm:
public bool ValidObject(MyObjectClass obj)
{
if(obj==null)
{
throw Exception("obj cannot be null");
return false;
}
if(obj.A=='x'){
throw Exception("obj cannot be x");
return false;
}
....
....
// other validations
....
...
if(obj.Students.Count()==100)
{
throw Exception("some error message");
return false;
}
return true;
}
If I call my function:
if(ValidateObject(this.Obj))
{
InsertIntoDB(this.Obj);
}
else
{
//do something
}
I will get an error if my object is invalid. But I dont't want this.
But maybe in some cases I want to know the reason why my object is invalid.
I don't want to make to functions that do the same but one of them throw exceptions. I don't think is a right approach.
So, my first thought was to make the previous function private and to create another public function:
public bool ValidObject2(MyObjectClass obj, bool withErrors=false)
{
try
{
return ValidObject(obj);
}
catch(Exception ex)
{
if(withErrors)
{
throw ex;
}
return false;
}
}
What do you think? Do you have other ideas ?
The Rails way:
Have a method save which saves to the DB, and, in case of validation errors, just holds on to them without raising an exception.
Provide a getter validation_errors which returns a list of the errors in the previous save.
Make a trivial method save_with_validation which first calls save and then raises an exception if and only if validation_errors returns a non-empty set of errors. (Depending on your language, you might be able to get away with a shorter name like save!)

How do I tell ReactiveUI to update bindings (i.e. RaiseCanExecuteChanged())?

How do I tell ReactiveUI to update bindings?
Normally, I would do something like this:
string _instructorNameInput;
public string InstructorNameInput
{
get { return _instructorNameInput; }
set
{
this.RaiseAndSetIfChanged(ref _instructorNameInput, value);
Submit.RaiseCanExecuteChanged();
}
}
However, the following isn't supported:
Submit.RaiseCanExecuteChanged();
As a result, how can I force bindings to update based on the CanExecute predicate that my command relies on?
Updated:
public partial class FormViewModel : ReactiveObject
{
public FormViewModel()
{
Submit = ReactiveCommand.Create(this.WhenAnyValue(x => x.CanSubmit));
Submit.Subscribe(x => OnSubmit());
}
bool _canExecute;
public bool CanSubmit
{
get { return !GetUnsatisfied().Any(); }
set { this.RaiseAndSetIfChanged(ref _canExecute, value); } // Need to update view based on command.CanExecute state change
}
void OnSubmit()
{
var rosterInfo = new RosterInfo(new Course(CourseInput.Name),
new Instructor(InstructorNameInput, InstructorIdInput));
var repository = GetRepository();
repository.AddCourseInfo(rosterInfo);
Publish(REQUEST_NAVIGATION_TO_SUBMITION_CONFIRMATION, rosterInfo);
}
ObservableCollection<RequiredField> GetUnsatisfied()
{
RequiredFields.Clear();
RequiredFields = Review();
return RequiredFields;
}
}
Multiple issues:
Have a read at the fundamentals on ReactiveObject, in particular how "Read-Write Properties" are written.
In your case, this.WhenAnyValue(x => x.CanSubmit) will trigger a refresh on the command whenever the property CanSubmit changes, but this one never does, because you never call the setter (and the getter has an incorrect impl).
Currently, your method GetUnsatisfied() has "polling" semantics, which mean you need something to trigger this method to update your command. This isn't reactive at all, you should instead bind/listen to updates.
If there's no way for you to make your Review() logic reactive, then you may do something like:
var canExec = Observable.Timer(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1))
.Select(_ => !GetUnsatisfied().Any());
Submit = ReactiveCommand.Create(canExec);
Submit.Subscribe(x => OnSubmit());
Basically, having a timer to do your polling.
(But I strongly suggest going further down the reactive way)

What is the MVC version of this code?

i'm trying to wrap my head around how to enterprise up my code: taking a simple routine and splitting it up into 5 or 6 methods in 3 or 4 classes.
i quickly came up three simple examples of code how i currently write it. Could someone please convert these into an MVC/MVP obfuscated version?
Example 1: The last name is mandatory. Color the text box red if nothing is entered. Color it green if stuff is entered:
private void txtLastname_TextChanged(object sender, EventArgs e)
{
//Lastname mandatory.
//Color pinkish if nothing entered. Greenish if entered.
if (txtLastname.Text.Trim() == "")
{
//Lastname is required, color pinkish
txtLastname.BackColor = ControlBad;
}
else
{
//Lastname entered, remove the coloring
txtLastname.BackColor = ControlGood;
}
}
Example 2: The first name is optional, but try to get it. We'll add a bluish tint to this "try to get" field:
private void txtFirstname_TextChanged(object sender, EventArgs e)
{
//Firstname can be blank.
//Hint them that they should *try* to get it with a bluish color.
//If they do enter stuff: it better be not all spaces.
if (txtFirstname.Text == "")
{
//Nothing there, hint it blue
txtFirstname.BackColor = ControlRequired;
}
else if (txtFirstname.Text.Trim() == "")
{
//They entered spaces - bad user!
txtFirstname.BackColor = ControlBad;
}
else
{
//Entered stuff, remove coloring
txtFirstname.BackColor = SystemColors.Window;
}
}
Example 3 The age is totally optional. If an age is entered, it better be valid:
private void txtAge_TextChanged(object sender, EventArgs e)
{
//Age is optional, but if entered it better be valid
int nAge = 0;
if (Int32.TryParse(txtAge.Text, out nAge))
{
//Valid integer entered
if (nAge < 0)
{
//Negative age? i don't think so
txtAge.BackColor = ControlBad;
}
else
{
//Valid age entered, remove coloring
txtAge.BackColor = SystemColors.Window;
}
}
else
{
//Whatever is in there: it's *not* a valid integer,
if (txtAge.Text == "")
{
//Blank is okay
txtAge.BackColor = SystemColors.Window;
}
else
{
//Not a valid age, bad user
txtAge.BackColor = ControlBad;
}
}
}
Every time i see MVC code, it looks almost like random splitting of code into different methods, classes, and files. i've not been able to determine a reason or pattern to their madness. Without any understanding of they why it's being one some way, it makes no sense. And using the words model, view, controller and presenter, like i'm supposed to know what that means, doesn't help.
The model is your data.
The view shows data on screen.
The controller is used to carry out
the users actions
And oranges taste orangy.
Here's my attempt at splitting things up in order to make the code more difficult to follow. Is this anywhere close to MVC?
private void txtFirstname_TextChanged(object sender, EventArgs e)
{
FirstnameTextChangedHandler(sender, e);
}
private void FirstnameTextChangedHandler(sender, e)
{
string firstname = GetFirstname();
Color firstnameTextBoxColor = GetFirstnameTextBoxColor(firstname);
SetFirstNameTextBoxColor(firstnameTextBoxColor);
}
private string GetFirstname()
{
return txtFirstname.Text;
}
private Color GetFirstnameTextBoxColor(string firstname)
{
//Firstname can be blank.
//Hint them that they should *try* to get it with a bluish color.
//If they do enter stuff: it better be not all spaces.
if (firstname == "")
{
//Nothing there, hint it blue
return GetControlRequiredColor();
}
else if (firstname.Trim() == "")
{
//They entered spaces - bad user!
return GetControlBadColor();
}
else
{
//Entered stuff, remove coloring
return GetControlDefaultColor();
}
}
private Color GetControlRequiredColor()
{
return ControlRequired;
}
private Color GetControlBadColor()
{
return ControlBad;
}
private Color GetControlGoodColor()
{
return ControlGood;
}
//am i doin it rite
i've obfuscated the code, but it's still altogether. The next step in the MVC obfuscation, i gather, is to hide the code in 3 or 4 different files.
It's that next step that i don't understand. What is the logical separation of which functions are moved into what other classes? Can someone translate my 3 simple examples above into full fledged MVC obfuscation?
Edit: Not ASP/ASP.NET/Online. Pretend it's on a desktop, handheld, surface, kiosk. And pretend it's language agnostic.
The purpose of MVC/MVP patterns is not obfuscation, but separation of concerns. Obfuscation is to (conceal the) intended meaning in communication, making communication confusing, intentionally ambiguous, and more difficult to interpret: ref. The use of patterns is to make the code cleaner and more understandable. I suggest you start out by reading the wikipedia entries on MVC and MVP.
Both patterns are ways of structuring your code so that your application is broken up into elements that carry out specific purposes that have clearly defined interaction boundaries. Rather than having code that specifically addresses business concerns, input/output handling, and presentation throughout the various classes of the application, these concerns are separated and isolated in the various architectural components. These architectural elements are insulated from one another by the interaction boundaries (interfaces) making them more independent of one another and easier to modify without affect the application as a whole.
The main idea I have when implementing MVC for Windows Forms is that I want to have unit tests for my model and my controller. In order to achieve that, my controller should not know anything about the views using it, and so any notifications that should be handled on UI level are implemented as events. In your example, my controller would look something like this:
class Controller
{
// This is the model we are operating on
private Model model_;
public enum Status
{
Normal,
Required,
Good,
Bad
}
public delegate void FirstNameStatusChangedDelegate(Status newStatus);
public event FirstNameStatusChangedDelegate FirstNameStatusChangedEvent;
public string FirstName
{
get { return model_.FirstName; }
set
{
if (value == "")
RaiseFirstNameStatusChanged(Status.Required);
else if ( value.Trim() == "" )
RaiseFirstNameStatusChanged(Status.Bad);
else
{
model_.FirstName = value;
RaiseFirstNameStatusChanged(Status.Normal);
}
}
}
private void RaiseFirstNameStatusChanged(Status newStatus)
{
if ( FirstNameStatusChangedEvent != null )
FirstNameStatusChangedEvent(newStatus);
}
}
And the view would provide handlers for the FirstNameStatusChanged event:
class View : Form
{
private Controller controller_;
private static readonly Dictionary<Controller.Status, Color> statusColors_ = new Dictionary<Controller.Status, Color>
{
{Controller.Status.Normal, SystemColors.Window},
{Controller.Status.Required, ControlRequired},
{Controller.Status.Good, ControlGood},
{Controller.Status.Bad, ControlRed}
};
public View(Controller controller)
{
InitializeComponent();
controller_ = controller;
contoller_.FirstNameStatusChangedEvent += OnFirstNameStatusChanged;
}
private void txtFirstname_TextChanged(object sender, EventArgs e)
{ controller_.FirstName = txtFirstName.Text; }
private void OnFirstNameStatusChanged(Controller.Status newStatus)
{ txtFirstName.BackColor = statusColors_[newStatus]; }
}
Most of what you doing in your code belongs to the Controller class since it describes the the logic. Your View should just describe UI and give easy access to UI components. Model class should describe your data model.
The idea is simple: Controller does everything, but it has to know about the View and the Model. For example as View is initialized, Controller sets up all the logic ( kinda what you already doing). As Model is assigned to the Controller - it sets the values into appropriate UI controls and does the same to retrieve data and return is as Model.
So basically you give your data model class to the controller, it does the editing and returns your data as model class again.
It would be very hard to follow MVC in classic ASP.NET if possible, so I will reply based on MVP.
On your first example, you are trying to do a validation. Validating a surname is the responsibility of Presenter. Showing the field red is the responsibility of View. So, your view class would be like this:
private void Page_Load()
{
this._presenter = new Presenter();
}
private void txtLastname_TextChanged(object sender, EventArgs e)
{
txtLastName.BackColor = presenter.IsLastnameValid(txtLastName.Text) ?
ControlGood : ControlBad;
}
And your presenter class would be something like this:
public Presenter()
{
public bool IsLastNameValid(string lastname)
{
return string.IsNullOrEmpty(lastname);
}
}
Last name is your model here.
Please note that I prepared this classes only for showing how would you form an MVP structure. In real world, there are lots of better ways to do validation. Normally you would use this approach for your business instead of validation.
Ian,
If you want the controls to validate immediately, you need to use javascript or jQuery. This is also true for classic ASP.NET. Since you are using Code Behind methods, I assume that your validation waits for a postback.
The following examples are from the NerdDinner project. NerdDinner is an open source project that serves as an example of ASP.NET MVC architecture. The authors have graciously provided a tutorial with it, available at http://nerddinnerbook.s3.amazonaws.com/Intro.htm
When a form is submitted in ASP.NET MVC, it enters the corresponding controller as a FormCollection object:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues) {
Dinner dinner = dinnerRepository.GetDinner(id);
try
{
UpdateModel(dinner);
dinnerRepository.Save();
}
catch
{
ModelState.AddModelErrors(dinner.GetRuleViolations())
}
return RedirectToAction("Details", new { id = dinner.DinnerID });
}
UpdateModel takes the form values and attempts to stuff them into the dinner object. The dinner object looks like this:
public partial class Dinner {
public bool IsValid {
get { return (GetRuleViolations().Count() == 0); }
}
public IEnumerable<RuleViolation> GetRuleViolations() {
yield break;
}
public IEnumerable<RuleViolation> GetRuleViolations() {
if (String.IsNullOrEmpty(Title))
yield return new RuleViolation("Title is required", "Title");
if (String.IsNullOrEmpty(Description))
yield return new RuleViolation("Description is required", "Description");
if (String.IsNullOrEmpty(HostedBy))
yield return new RuleViolation("HostedBy is required", "HostedBy");
if (String.IsNullOrEmpty(Address))
yield return new RuleViolation("Address is required", "Address");
if (String.IsNullOrEmpty(Country))
yield return new RuleViolation("Country is required", "Address");
if (String.IsNullOrEmpty(ContactPhone))
yield return new RuleViolation("Phone# is required", "ContactPhone");
if (!PhoneValidator.IsValidNumber(ContactPhone, Country))
yield return new RuleViolation("Phone# does not match country", "ContactPhone");
yield break;
}
partial void OnValidate(ChangeAction action) {
if (!IsValid)
throw new ApplicationException("Rule violations prevent saving");
}
}
Notice the IsValid method and the RuleViolations enumerator. If everything is set up properly, all you have to do is define your validations in here, and ASP.NET MVC will take care of the rest for you.
The final validated result looks like this:
I encourage you to get the NerdDinner application and tutorial at http://nerddinner.codeplex.com/

Simple MVC NerdDinners Lambda

In this code from Microsoft's MVC Tutorial NerdDinners:
public class DinnerRepository {
private NerdDinnerDataContext db = new NerdDinnerDataContext();
//
// Query Methods
public IQueryable<Dinner> FindAllDinners() {
return db.Dinners;
}
public IQueryable<Dinner> FindUpcomingDinners() {
return from dinner in db.Dinners
where dinner.EventDate > DateTime.Now
orderby dinner.EventDate
select dinner;
}
public Dinner GetDinner(int id) {
return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
}
//
// Insert/Delete Methods
public void Add(Dinner dinner) {
db.Dinners.InsertOnSubmit(dinner);
}
public void Delete(Dinner dinner) {
db.RSVPs.DeleteAllOnSubmit(dinner.RSVPs);
db.Dinners.DeleteOnSubmit(dinner);
}
//
// Persistence
public void Save() {
db.SubmitChanges();
}
}
What does:
public Dinner GetDinner(int id) {
return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
}
the "d" mean? How does this code work? I know it it bringing back dinners where dinnerid matches id from the function parameter. I don't understand the "d goes to..." means. I know it is a lambda but I don't really get it. What is the "d" for? What does it do?
Could this have been written without the lambda here (how)?
You should probably read up on anonymous methods.
Basically the code you are referring to can be written as an anonymous method without lamba syntax like this:
public Dinner GetDinner(int id) {
return db.Dinners.SingleOrDefault(delegate (Dinner d) {
return d.DinnerID == id;
});
}
This is similar too...
from d in db.Dinners
where d.DinnerID == id
select d
The code basically loops around the dinners returning the first Dinner or the default if none is found.
This is a case where the naming conventions used in a sample aren't always appropriate in production. Using a "d" as a local variable is usually fround upon and choosing a variable name of "dinner" would probably be more appropriate, although in this case the scope of d is so small it is clear either way, as long as you know how lambda expressions work.
You need to understand lambda syntax and what it's used for.
Here's an article that does a decent job of explaining it.
However, to shortly answer your question in regards to the NerdDinner context, "d" in this context is just a parameter passed into the lamda expression that is a Dinner object.
This bit of code:
d => d.DinnerID == id
Can be thought of as defining a function of type Func<Dinner, bool>.
Whatever you pass it to, this function can be called, and passed Dinner, and it will give back a bool.
void Foo(Func<Dinner, bool> f)
{
bool result = f(new Dinner());
}
In your real example, the function SingleOrDefault will call the function you give it multiple times, passing it a different Dinner each time, and will return the Dinner for which the function returns true.
In fact, as you're using IQueryable, this is only conceptually what happens. The chances are, the code of the function is converted into SQL, and all the execution is done inside the database.

Is this control of flow structure good practice?

I want to re-write a method that has way too many nested if statements.
I came up with this approach and wanted your opinions:
public void MyMethod()
{
bool hasFailed = false;
try
{
GetNewOrders(out hasFailed);
if(!hasFailed)
CheckInventory(out hasFailed);
if(!hasFailed)
PreOrder(out hasFailed);
// etc
}
catch(Exception ex)
{
}
finally
{
if(hasFailed)
{
// do something
}
}
}
I've done stuff similar to that, but without the exception handling:
BOOL ok = CallSomeFunction();
if( ok ) ok = CallSomeOtherFunction();
if( ok ) ok = CallYetAnotherFunction();
if( ok ) ok = WowThatsALotOfFunctions();
if( !ok ) {
// handle failure
}
Or if you want to be clever:
BOOL ok = CallSomeFunction();
ok &= CallSomeOtherFunction();
ok &= CallYetAnotherFunction();
...
If you are using exceptions anyway, why do you need the hasFailed variable?
Not really. Your methods should raise an exception in case of an error to be caught by your "catch" block.
As far as I can see this is an example of cascade steps where second and third one will be executed if first and first and second are valid, i.e. return hasFailed==false.
This code can be made much more elegant using Template Method and Decorator design pattern.
You need one interface, concrete implementation, abstract class and several subclasses of the abstract class.
public interface Validator {
public boolean isValid();
}
public class GetNewOrders implements Validator {
public boolean isValid() {
// same code as your GetNewOrders method
}
}
public abstract class AbstractValidator implements Validator {
private final Validator validator;
public AbstractValidator(Validator validator) {
this.validator = validator;
}
protected boolean predicate();
protected boolean isInvalid();
public final boolean isValid() {
if (!this.validator.isValid() && predicate() && isInvalid())
return false;
return true;
}
}
public class CheckInventory extends AbstractValidator {
public CheckInventory(Validator validator) {
super(validator);
}
#Override
public boolean predicate() {
return true;
}
#Override
public boolean isInvalid() {
// same code as your CheckInventory method
}
}
public class PreOrder extends AbstractValidator {
public CheckInventory(Validator validator) {
super(validator);
}
#Override
public boolean predicate() {
return true;
}
#Override
public boolean isInvalid() {
// same code as your PreOrder method
}
}
Now your method can look much more elegant:
public void MyMethod() {
bool success = false;
try {
Validator validator = new GetNewOrders();
validator = new CheckInventory(validator);
validator = new PreOrder(validator);
success = validator.isValid();
} finally {
if (!success) {
// do something
}
}
}
Validator object can be created in one line, but I prefer this style since it makes obvious the order of validation. Creating new validation link in the chain is matter of subclassing AbstractValidator class and implementation of predicate and isInvalid methods.
Without commenting on the try/catch stuff since I really don't know what is going on there, I would change it so the called methods return true/false for success and then just check them depending on the boolean short-circuiting to avoid calling later methods if the preceding method failed.
public void MyMethod()
{
bool success = false;
try
{
success = GetNewOrders()
&& CheckInventory()
&& PreOrder();
// etc
}
catch(Exception ex) { }
finally
{
if(!success)
{
}
}
}
This doesn't really look good to me. The use of the hasFailed variable is really not nice. if GetNewOrders fails with an exception, you for instance end up inside the catch block with hasFailed = false !
Opposed to other answers here I believe there MAY be legitimate uses for boolean "hasFailed" that are not exceptional. But I really don't think you should mix such a condition into your exception handler.
I know I'll probably duplicate a few posts: What's wrong with else? You could also use lazy evaluation (a() && b()) to link methods - but that relies on status being given as return value, which is more readable anyhow IMHO.
I don't agree with posters that you should raise an exception, because exceptions should be raised if program faults occur or the program enters an exceptional state because of operations. Exceptions are not business logic.
I would do it like this:
public void MyMethod()
{
bool success = false;
try
{
GetNewOrders(); // throw GetNewOrdersFailedException
CheckInventory(); // throw CheckInventoryFailedException
PreOrder(); // throw PreOrderFailedException
success = true;
}
catch( GetNewOrdersFailedException e)
{
// Fix it or rollback
}
catch( CheckInventoryFailedException e)
{
// Fix it or rollback
}
catch( PreOrderFailedException e)
{
// Fix it or rollback
}
finally
{
//release resources;
}
}
Extending an exception is rather trivial,
public NewExecption : BaseExceptionType {}
Well, I don't like code that appears to get a list of orders and then process them, and then stop processing them when an error occurs, when surely it should skip that order and move to the next? The only thing to completely fail on is when the database (source of orders, destination of preorders) dies. I think that the entire logic is a bit funky really, but maybe that's because I don't have experience in the language you are using.
try {
// Get all of the orders here
// Either in bulk, or just a list of the new order ids that you'll call the DB
// each time for, i'll use the former for clarity.
List<Order> orders = getNewOrders();
// If no new orders, we will cry a little and look for a new job
if (orders != null && orders.size() > 0) {
for (Order o : orders) {
try {
for (OrderItem i : o.getOrderItems()) {
if (checkInventory(i)) {
// Reserve that item for this order
preOrder(o, i);
} else {
// Out of stock, call the magic out of stock function
failOrderItem(o, i);
}
}
} catch (OrderProcessingException ope) {
// log error and flag this order as requiring attention and
// other things relating to order processing errors that aren't database related
}
}
} else {
shedTears();
}
} catch (SQLException e) {
// Database Error, log and flag to developers for investigation
}
Your new approach is not that bad for a simple set of instructions, but what happens when additional steps are added? Do you / would you ever require transactional behavior? (What if PreOrder fails? or If the next step after PreOrder fails?)
Looking forward, I would use the command pattern:
http://en.wikipedia.org/wiki/Command_pattern
...and encapsulate each action as a concrete command implementing Execute() and Undo().
Then it's just a matter of creating a queue of commands and looping until failure or an empty queue. If any step fails, then simply stop and execute Undo() in order on the previous commands. Easy.
Chris solution is the most correct. But I think you should not do more than you need. Solution should be extandable and that's enough.
Change value of a parameter is a bad practice.
Never use empty generic catch statement, at least add a comment why you do so.
Make the methods throw exception and handle them where it is appropriate to do so.
So now it is much more elegant :)
public void MyMethod()
{
try
{
GetNewOrders();
CheckInventory();
PreOrder();
// etc
}
finally
{
// do something
}
}

Resources