Question

This violates a SOLID coding principles, which one? After you know which one Refactor the code....

This violates a SOLID coding principles, which one? After you know which one
Refactor the code.

public abstract class Bird
    {
        public abstract void LayEgg();
        public abstract void FlyAway();
    }
    public class Penguin : Bird
    {
        public override void LayEgg()
        {
            //Make husband penguin do all the incubation work.
        }
        public override void FlyAway()
        {
            //Penguins can't fly.
            throw new NotImplementedException();
        }

        public void SwimAway()
        {
            //Swimming is way more fun.
        }
    }

Homework Answers

Answer #1

The above code violates the Liskov substitution principle what states that: If class A is a subtype of class B, then we should be able to replace B with A without disrupting the behavior of our program.

By throwing an exception- Bird that couldn't fly, we are inherently changing the behavior of our program. This is a blatant violation of Liskov substitution.

See below, how you can fix the code :

The solution to these problems is a correct inheritance hierarchy, and in our case, we would solve the problem by differentiating classes of Birds with and without flying ability. Even though a Penguin is a Bird, it cannot fly.

Bird.java

public abstract class Bird {
    public abstract void LayEgg();
}

FlyingBird.java (Try changing the class name to more meaningful according to you)

public abstract class FlyingBird extends Bird{
    public abstract void FlyAway();
}

NonFlyingBird.java (Try changing the class name to more meaningful according to you)

public abstract class NonFlyingBird extends Bird{
}

Penguin.java

public class Penguin extends FlyingBird {
    @Override
    public void LayEgg() {
        // Make husband penguin do all the incubation work.
    }

    @Override
    public void FlyAway() {
        //Penguins can't fly. throw new NotImplementedException();
    }

    public void SwimAway(){
        //Swimming is way more fun
    }
}

If you have any doubt then put in the comments. Also, do upvote the solution.

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions